cverdict-mcp 0.2.0 → 0.2.1

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.
@@ -24128,13 +24128,22 @@ var MCP_SERVER = {
24128
24128
  name: `io.github.${BRAND.repo}`,
24129
24129
  title: BRAND.name,
24130
24130
  /** Same as mcp/package.json (checked by a test). */
24131
- version: "0.2.0",
24131
+ version: "0.2.1",
24132
24132
  /** npm package name: `npx -y cverdict-mcp`. */
24133
24133
  npm: `${BRAND.slug}-mcp`,
24134
24134
  /** Where the server is documented. */
24135
24135
  docs: `${REPO_URL}/blob/main/mcp/README.md`
24136
24136
  };
24137
24137
  var CLONE_DIR = BRAND.repo.split("/")[1];
24138
+ JSON.stringify({ mcpServers: { [BRAND.slug]: {
24139
+ command: "npx",
24140
+ args: ["-y", MCP_SERVER.npm]
24141
+ } } });
24142
+ `${BRAND.slug}${MCP_SERVER.npm}`, `${BRAND.slug}${MCP_SERVER.npm}`, `${JSON.stringify({
24143
+ name: BRAND.slug,
24144
+ command: "npx",
24145
+ args: ["-y", MCP_SERVER.npm]
24146
+ })}`, `${BRAND.slug}${MCP_SERVER.npm}`;
24138
24147
  `${BRAND.slug}${BRAND.slug}`, `${BRAND.slug}${BRAND.slug}`, `${REPO_URL}${CLONE_DIR}${BRAND.slug}`;
24139
24148
  /** Data bases the server tries, in order: the data branch on GitHub, then the site's /data/ rewrite. */
24140
24149
  var MCP_DATA_BASES = [`${RAW_DATA_URL}/v1/`, `${BRAND.siteUrl}/data/v1/`];
@@ -24291,6 +24300,13 @@ var PACKAGE_ECOSYSTEMS = [
24291
24300
  "Packagist",
24292
24301
  "NuGet"
24293
24302
  ];
24303
+ var OS_ECOSYSTEMS = [
24304
+ "Debian",
24305
+ "Ubuntu",
24306
+ "Alpine"
24307
+ ];
24308
+ var ALL_ECOSYSTEMS = [...PACKAGE_ECOSYSTEMS, ...OS_ECOSYSTEMS];
24309
+ var isOsEcosystem = (eco) => OS_ECOSYSTEMS.includes(eco);
24294
24310
  /** Tier for a score at a given knob. Shared so the site and pipeline always agree. */
24295
24311
  function tierFor(score, exploited, weaponized, knob) {
24296
24312
  if (exploited) return "exploited";
@@ -24306,6 +24322,211 @@ function rowFromColumns(cols, values) {
24306
24322
  function rowsFromTable(table) {
24307
24323
  return table.rows.map((r) => rowFromColumns(table.cols, r));
24308
24324
  }
24325
+ // shared/os.ts
24326
+ /** Debian releases by codename (OSV names them by number: "Debian:12"). sid has no number. */
24327
+ var DEBIAN_CODENAMES = {
24328
+ buzz: "1.1",
24329
+ hamm: "2.0",
24330
+ slink: "2.1",
24331
+ potato: "2.2",
24332
+ woody: "3.0",
24333
+ sarge: "3.1",
24334
+ etch: "4.0",
24335
+ lenny: "5.0",
24336
+ squeeze: "6.0",
24337
+ wheezy: "7",
24338
+ jessie: "8",
24339
+ stretch: "9",
24340
+ buster: "10",
24341
+ bullseye: "11",
24342
+ bookworm: "12",
24343
+ trixie: "13",
24344
+ forky: "14",
24345
+ duke: "15"
24346
+ };
24347
+ /** Ubuntu releases by codename (OSV names them by number: "Ubuntu:22.04:LTS"). */
24348
+ var UBUNTU_CODENAMES = {
24349
+ trusty: "14.04",
24350
+ xenial: "16.04",
24351
+ bionic: "18.04",
24352
+ focal: "20.04",
24353
+ jammy: "22.04",
24354
+ kinetic: "22.10",
24355
+ lunar: "23.04",
24356
+ mantic: "23.10",
24357
+ noble: "24.04",
24358
+ oracular: "24.10",
24359
+ plucky: "25.04",
24360
+ questing: "25.10",
24361
+ resolute: "26.04"
24362
+ };
24363
+ /** The distro of a package URL type and namespace (`pkg:deb/debian/…`, `pkg:apk/alpine/…`), or null. */
24364
+ function osEcosystemOfPurl(type, namespace) {
24365
+ const t = type.toLowerCase();
24366
+ const ns = (namespace ?? "").toLowerCase();
24367
+ if (t === "deb" && ns === "debian") return "Debian";
24368
+ if (t === "deb" && ns === "ubuntu") return "Ubuntu";
24369
+ if (t === "apk" && ns === "alpine") return "Alpine";
24370
+ return null;
24371
+ }
24372
+ /** A distro name as SBOMs write it ("debian", "Ubuntu", "alpine"), or null. */
24373
+ function osEcosystemOfName(name) {
24374
+ const n = name.trim().toLowerCase();
24375
+ return n === "debian" ? "Debian" : n === "ubuntu" ? "Ubuntu" : n === "alpine" ? "Alpine" : null;
24376
+ }
24377
+ /**
24378
+ * The release key v1/os/ uses ("12", "22.04", "v3.20") from what an SBOM says: a package URL's
24379
+ * `distro` qualifier ("debian-12", "debian-12.8", "bookworm", "ubuntu-22.04", "jammy",
24380
+ * "alpine-3.20.3", "3.20.3") or an operating-system component's version. Null when it names no
24381
+ * release we can read (sid, edge, or nothing).
24382
+ */
24383
+ function osRelease(eco, text) {
24384
+ if (!text) return null;
24385
+ let t = text.trim().toLowerCase();
24386
+ if (t.length > 64) return null;
24387
+ t = t.replace(/^(?:debian|ubuntu|alpine)[-_ ]?/, "");
24388
+ if (eco === "Debian") {
24389
+ if (Object.hasOwn(DEBIAN_CODENAMES, t)) return DEBIAN_CODENAMES[t];
24390
+ const m = /^(\d{1,2})(?:\.\d+)*$/.exec(t);
24391
+ if (!m) return null;
24392
+ return Number(m[1]) >= 7 ? m[1] : /^\d\.\d/.test(t) ? t.slice(0, 3) : null;
24393
+ }
24394
+ if (eco === "Ubuntu") {
24395
+ if (Object.hasOwn(UBUNTU_CODENAMES, t)) return UBUNTU_CODENAMES[t];
24396
+ const m = /^(\d{2}\.\d{2})(?:\.\d+)?(?:[ -]?lts)?$/.exec(t);
24397
+ return m ? m[1] : null;
24398
+ }
24399
+ const m = /^v?(\d{1,2}\.\d{1,3})(?:\.\d+)?$/.exec(t);
24400
+ return m ? `v${m[1]}` : null;
24401
+ }
24402
+ /** The package key in a v1/os/ file: "<release>/<source package>". */
24403
+ var osPackageKey = (release, source) => `${release}/${source}`;
24404
+ /** The v1/os/ file of a release, relative to v1/: "os/debian-12.json". */
24405
+ var osFile = (eco, release) => `os/${eco.toLowerCase()}-${release}.json`;
24406
+ /** Release keys are short and plain, so they are safe in a file name. */
24407
+ var OS_RELEASE_RE = /^(?:\d{1,2}(?:\.\d{1,2})?|v\d{1,2}\.\d{1,3})$/;
24408
+ /** Userland source packages whose names start with "linux-": checked like any other package. */
24409
+ var LINUX_USERLAND = /* @__PURE__ */ new Set([
24410
+ "linux-atm",
24411
+ "linux-entra-sso",
24412
+ "linux-ftpd",
24413
+ "linux-ftpd-ssl",
24414
+ "linux-pam"
24415
+ ]);
24416
+ /**
24417
+ * The Linux kernel's source packages: "linux" itself (whose linux-libc-dev headers are what a
24418
+ * container image holds) and the kernel builds ("linux-6.1", "linux-lts", "linux-aws",
24419
+ * "linux-signed-amd64"). A container runs on its host's kernel, so v1/os/ leaves the kernel out and
24420
+ * a check reports these packages as not checked, never clean. An unknown "linux-…" name counts as a
24421
+ * kernel build, so it too is not checked rather than wrongly clean.
24422
+ */
24423
+ function isKernelSource(name) {
24424
+ if (name === "linux") return true;
24425
+ return name.startsWith("linux-") && !LINUX_USERLAND.has(name) && !name.startsWith("linux-firmware");
24426
+ }
24427
+ // shared/os-load.ts
24428
+ /**
24429
+ * Which v1/os/ release files a check needs, and how they join the package index: shared by the
24430
+ * Check page, the CLI and the MCP server, which each fetch the files their own way. Only the
24431
+ * releases the user's packages name are fetched, so a check without distro packages fetches nothing.
24432
+ */
24433
+ /** A compact OS entry (OsAffect) as the PackageAffect the matcher reads: its advisory, and ">=0" back at the start of each range. */
24434
+ function expandAffect(entry, prefix) {
24435
+ if (!Array.isArray(entry) || typeof entry[0] !== "string" || !Array.isArray(entry[1])) return null;
24436
+ const [cve, ranges, advisory] = entry;
24437
+ const out = [];
24438
+ for (const r of ranges) {
24439
+ if (!Array.isArray(r) || !r.every((e) => typeof e === "string")) return null;
24440
+ out.push(r.length > 0 && r[0].startsWith(">=") ? [...r] : [">=0", ...r]);
24441
+ }
24442
+ return [
24443
+ cve,
24444
+ typeof advisory === "string" ? advisory : `${prefix}-${cve}`,
24445
+ out
24446
+ ];
24447
+ }
24448
+ /** The distro releases a list of packages names (packages without a release, or skipped, need none). */
24449
+ function osNeeds(components) {
24450
+ const out = /* @__PURE__ */ new Map();
24451
+ for (const c of components) {
24452
+ if (!c.eco || c.skip || !c.release || !isOsEcosystem(c.eco)) continue;
24453
+ const eco = c.eco;
24454
+ out.set(`${eco}/${c.release}`, {
24455
+ eco,
24456
+ release: c.release
24457
+ });
24458
+ }
24459
+ return [...out.values()];
24460
+ }
24461
+ function osPlan(index, needs) {
24462
+ const plan = {
24463
+ files: /* @__PURE__ */ new Map(),
24464
+ notFollowed: /* @__PURE__ */ new Set(),
24465
+ failed: /* @__PURE__ */ new Set()
24466
+ };
24467
+ for (const n of needs) {
24468
+ const tag = `${n.eco}/${n.release}`;
24469
+ const source = index?.sources?.find((s) => s.ecosystem === n.eco);
24470
+ if (!index || !source?.ok) {
24471
+ plan.failed.add(tag);
24472
+ continue;
24473
+ }
24474
+ const entry = index.releases.find((r) => r.ecosystem === n.eco && r.release === n.release);
24475
+ if (!entry) continue;
24476
+ const file = OS_RELEASE_RE.test(n.release) ? osFile(n.eco, n.release) : null;
24477
+ if (!entry.followed || entry.file !== file || file === null) plan.notFollowed.add(tag);
24478
+ else plan.files.set(tag, file);
24479
+ }
24480
+ return plan;
24481
+ }
24482
+ /**
24483
+ * The package index with distro release files merged in: their packages, their source status (so
24484
+ * the ecosystem counts as available) and the rows of CVEs the index does not have yet. `noPage`:
24485
+ * the CVEs added that have no CVE page (no detail shard), which link to cve.org.
24486
+ */
24487
+ function mergeOsFiles(base, files) {
24488
+ if (files.length === 0) return {
24489
+ file: base,
24490
+ noPage: /* @__PURE__ */ new Set()
24491
+ };
24492
+ const have = new Set(rowsFromTable(base.cves).map((r) => r.id));
24493
+ const packages = { ...base.packages };
24494
+ const sources = [...base.sources];
24495
+ const rows = [...base.cves.rows];
24496
+ const noPage = /* @__PURE__ */ new Set();
24497
+ for (const f of files) {
24498
+ const eco = f.ecosystem;
24499
+ const merged = new Map(Object.entries(packages[eco] ?? {}));
24500
+ for (const [key, list] of Object.entries(f.packages ?? {})) {
24501
+ if (!Array.isArray(list)) continue;
24502
+ merged.set(key, list.map((e) => expandAffect(e, f.prefix)).filter((e) => e !== null));
24503
+ }
24504
+ packages[eco] = Object.fromEntries(merged);
24505
+ for (const s of f.sources) if (!sources.some((x) => x.ecosystem === s.ecosystem)) sources.push(s);
24506
+ const tracked = new Set(f.tracked);
24507
+ const order = base.cves.cols.map((c) => f.cves.cols.indexOf(c));
24508
+ const idCol = f.cves.cols.indexOf("id");
24509
+ for (const r of f.cves.rows) {
24510
+ const id = r[idCol];
24511
+ if (have.has(id)) continue;
24512
+ have.add(id);
24513
+ rows.push(order.map((j) => j < 0 ? null : r[j]));
24514
+ if (!tracked.has(id)) noPage.add(id);
24515
+ }
24516
+ }
24517
+ return {
24518
+ file: {
24519
+ ...base,
24520
+ packages,
24521
+ sources,
24522
+ cves: {
24523
+ cols: base.cves.cols,
24524
+ rows
24525
+ }
24526
+ },
24527
+ noPage
24528
+ };
24529
+ }
24309
24530
  var DIGITS = /^\d+$/;
24310
24531
  /** Numeric comparison of two digit strings of any length (leading zeros allowed). */
24311
24532
  function cmpDigits(a, b) {
@@ -24614,6 +24835,103 @@ var COMPOSER_STABILITY = {
24614
24835
  pl: 5,
24615
24836
  p: 5
24616
24837
  };
24838
+ var composer = {
24839
+ parse: capped((raw) => {
24840
+ const m = COMPOSER_RE.exec(raw.toLowerCase());
24841
+ if (!m) return null;
24842
+ const dev = m[7] !== void 0;
24843
+ const stability = m[5] ? COMPOSER_STABILITY[m[5]] : dev ? 0 : 4;
24844
+ return {
24845
+ n: [
24846
+ m[1],
24847
+ m[2] ?? "0",
24848
+ m[3] ?? "0",
24849
+ m[4] ?? "0"
24850
+ ],
24851
+ stability,
24852
+ numbers: (m[6] ?? "").split(/[.-]/).filter((x) => x !== ""),
24853
+ dev: dev && m[5] !== void 0
24854
+ };
24855
+ }),
24856
+ cmp(a, b) {
24857
+ for (let i = 0; i < 4; i++) {
24858
+ const c = cmpDigits(a.n[i], b.n[i]);
24859
+ if (c !== 0) return c;
24860
+ }
24861
+ if (a.stability !== b.stability) return a.stability - b.stability;
24862
+ for (let i = 0; i < Math.max(a.numbers.length, b.numbers.length); i++) {
24863
+ const c = cmpDigits(a.numbers[i] ?? "0", b.numbers[i] ?? "0");
24864
+ if (c !== 0) return c;
24865
+ }
24866
+ if (a.dev !== b.dev) return a.dev ? -1 : 1;
24867
+ return 0;
24868
+ }
24869
+ };
24870
+ var DPKG_UPSTREAM = /^[0-9][0-9A-Za-z.+~:-]*$/;
24871
+ var DPKG_REVISION = /^[0-9A-Za-z.+~]+$/;
24872
+ /** dpkg's character order: "~" before everything (even the end), letters before other symbols. */
24873
+ function dpkgOrder(c) {
24874
+ if (c === void 0 || c >= "0" && c <= "9") return 0;
24875
+ if (c >= "A" && c <= "Z" || c >= "a" && c <= "z") return c.charCodeAt(0);
24876
+ if (c === "~") return -1;
24877
+ return c.charCodeAt(0) + 256;
24878
+ }
24879
+ var isDigit = (c) => c !== void 0 && c >= "0" && c <= "9";
24880
+ /** dpkg's verrevcmp: alternating non-digit and digit runs, digits compared as numbers. */
24881
+ function verrevcmp(a, b) {
24882
+ let i = 0;
24883
+ let j = 0;
24884
+ while (i < a.length || j < b.length) {
24885
+ while (i < a.length && !isDigit(a[i]) || j < b.length && !isDigit(b[j])) {
24886
+ const ac = dpkgOrder(a[i]);
24887
+ const bc = dpkgOrder(b[j]);
24888
+ if (ac !== bc) return ac - bc;
24889
+ i++;
24890
+ j++;
24891
+ }
24892
+ let x = "";
24893
+ let y = "";
24894
+ while (isDigit(a[i])) x += a[i++];
24895
+ while (isDigit(b[j])) y += b[j++];
24896
+ const c = cmpDigits(x || "0", y || "0");
24897
+ if (c !== 0) return c;
24898
+ }
24899
+ return 0;
24900
+ }
24901
+ var dpkg = {
24902
+ parse: capped((s) => {
24903
+ const colon = s.indexOf(":");
24904
+ const epoch = colon >= 0 ? s.slice(0, colon) : "0";
24905
+ if (!/^\d{1,9}$/.test(epoch)) return null;
24906
+ const rest = colon >= 0 ? s.slice(colon + 1) : s;
24907
+ const hyphen = rest.lastIndexOf("-");
24908
+ const upstream = hyphen >= 0 ? rest.slice(0, hyphen) : rest;
24909
+ const revision = hyphen >= 0 ? rest.slice(hyphen + 1) : "";
24910
+ if (!DPKG_UPSTREAM.test(upstream) || hyphen >= 0 && !DPKG_REVISION.test(revision)) return null;
24911
+ return {
24912
+ epoch,
24913
+ upstream,
24914
+ revision
24915
+ };
24916
+ }),
24917
+ cmp(a, b) {
24918
+ return cmpDigits(a.epoch, b.epoch) || verrevcmp(a.upstream, b.upstream) || verrevcmp(a.revision, b.revision);
24919
+ }
24920
+ };
24921
+ /** Pre-release suffixes sort before the release, post-release ones after it. */
24922
+ var APK_SUFFIX = {
24923
+ alpha: 0,
24924
+ beta: 1,
24925
+ pre: 2,
24926
+ rc: 3,
24927
+ cvs: 5,
24928
+ svn: 6,
24929
+ git: 7,
24930
+ hg: 8,
24931
+ p: 9
24932
+ };
24933
+ var APK_PRE = 4;
24934
+ var APK_RE = /^(\d+(?:\.\d+)*)([a-z]?)((?:_(?:alpha|beta|pre|rc|cvs|svn|git|hg|p)\d*)*)(?:~[0-9a-f]+)?(?:-r(\d+))?$/;
24617
24935
  var COMPARATORS = {
24618
24936
  npm: semver,
24619
24937
  "crates.io": semver,
@@ -24622,36 +24940,54 @@ var COMPARATORS = {
24622
24940
  RubyGems: rubygems,
24623
24941
  NuGet: nuget,
24624
24942
  Maven: maven,
24625
- Packagist: {
24626
- parse: capped((raw) => {
24627
- const m = COMPOSER_RE.exec(raw.toLowerCase());
24943
+ Packagist: composer,
24944
+ Debian: dpkg,
24945
+ Ubuntu: dpkg,
24946
+ Alpine: {
24947
+ parse: capped((s) => {
24948
+ const m = APK_RE.exec(s);
24628
24949
  if (!m) return null;
24629
- const dev = m[7] !== void 0;
24630
- const stability = m[5] ? COMPOSER_STABILITY[m[5]] : dev ? 0 : 4;
24631
- return {
24632
- n: [
24633
- m[1],
24634
- m[2] ?? "0",
24635
- m[3] ?? "0",
24636
- m[4] ?? "0"
24637
- ],
24638
- stability,
24639
- numbers: (m[6] ?? "").split(/[.-]/).filter((x) => x !== ""),
24640
- dev: dev && m[5] !== void 0
24641
- };
24950
+ const out = m[1].split(".").map((v, i) => ({
24951
+ t: 1,
24952
+ v,
24953
+ first: i === 0
24954
+ }));
24955
+ if (m[2]) out.push({
24956
+ t: 2,
24957
+ v: m[2]
24958
+ });
24959
+ for (const sfx of m[3].split("_").slice(1)) {
24960
+ const name = /^[a-z]+/.exec(sfx)[0];
24961
+ out.push({
24962
+ t: 3,
24963
+ rank: APK_SUFFIX[name],
24964
+ n: sfx.slice(name.length) || "0"
24965
+ });
24966
+ }
24967
+ if (m[4] !== void 0) out.push({
24968
+ t: 5,
24969
+ n: m[4]
24970
+ });
24971
+ out.push({ t: 6 });
24972
+ return out;
24642
24973
  }),
24643
24974
  cmp(a, b) {
24644
- for (let i = 0; i < 4; i++) {
24645
- const c = cmpDigits(a.n[i], b.n[i]);
24646
- if (c !== 0) return c;
24647
- }
24648
- if (a.stability !== b.stability) return a.stability - b.stability;
24649
- for (let i = 0; i < Math.max(a.numbers.length, b.numbers.length); i++) {
24650
- const c = cmpDigits(a.numbers[i] ?? "0", b.numbers[i] ?? "0");
24975
+ for (let i = 0;; i++) {
24976
+ const x = a[i];
24977
+ const y = b[i];
24978
+ if (x.t !== y.t) {
24979
+ if (x.t === 3 && x.rank < APK_PRE) return -1;
24980
+ if (y.t === 3 && y.rank < APK_PRE) return 1;
24981
+ return x.t > y.t ? -1 : 1;
24982
+ }
24983
+ let c = 0;
24984
+ if (x.t === 1 && y.t === 1) c = !x.first && (x.v[0] === "0" || y.v[0] === "0") ? cmpText(x.v, y.v) : cmpDigits(x.v, y.v);
24985
+ else if (x.t === 2 && y.t === 2) c = cmpText(x.v, y.v);
24986
+ else if (x.t === 3 && y.t === 3) c = x.rank - y.rank || cmpDigits(x.n, y.n);
24987
+ else if (x.t === 5 && y.t === 5) c = cmpDigits(x.n, y.n);
24988
+ else return 0;
24651
24989
  if (c !== 0) return c;
24652
24990
  }
24653
- if (a.dev !== b.dev) return a.dev ? -1 : 1;
24654
- return 0;
24655
24991
  }
24656
24992
  }
24657
24993
  };
@@ -24780,6 +25116,99 @@ function ecosystemOfPurlType(type) {
24780
25116
  return PURL_TYPES.get(type.toLowerCase()) ?? null;
24781
25117
  }
24782
25118
  /**
25119
+ * The advisory databases whose records may be published, with their licences. A record whose ID
25120
+ * prefix is not listed here is never published, so this list is always complete. Adding a
25121
+ * database means adding it here together with any notice its licence requires.
25122
+ */
25123
+ var ATTRIBUTION = [
25124
+ {
25125
+ name: "GitHub Advisory Database",
25126
+ url: "https://github.com/advisories",
25127
+ license: "CC-BY-4.0",
25128
+ prefixes: ["GHSA"],
25129
+ notice: null
25130
+ },
25131
+ {
25132
+ name: "PyPI Advisory Database",
25133
+ url: "https://github.com/pypa/advisory-database",
25134
+ license: "CC-BY-4.0",
25135
+ prefixes: ["PYSEC"],
25136
+ notice: null
25137
+ },
25138
+ {
25139
+ name: "Go Vulnerability Database",
25140
+ url: "https://pkg.go.dev/vuln/",
25141
+ license: "CC-BY-4.0",
25142
+ prefixes: ["GO"],
25143
+ notice: null
25144
+ },
25145
+ {
25146
+ name: "RustSec Advisory Database",
25147
+ url: "https://rustsec.org/",
25148
+ license: "CC0-1.0 (content imported from the GitHub Advisory Database: CC-BY-4.0)",
25149
+ prefixes: ["RUSTSEC"],
25150
+ notice: null
25151
+ },
25152
+ {
25153
+ name: "Drupal security advisories (OSV)",
25154
+ url: "https://github.com/DrupalSecurityTeam/drupal-advisory-database",
25155
+ license: "MIT, Copyright (c) 2025 Ackama",
25156
+ prefixes: ["DRUPAL-CORE", "DRUPAL-CONTRIB"],
25157
+ notice: `The MIT License (MIT)
25158
+
25159
+ Copyright (c) 2025 Ackama
25160
+
25161
+ Permission is hereby granted, free of charge, to any person obtaining a copy
25162
+ of this software and associated documentation files (the "Software"), to deal
25163
+ in the Software without restriction, including without limitation the rights
25164
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
25165
+ copies of the Software, and to permit persons to whom the Software is
25166
+ furnished to do so, subject to the following conditions:
25167
+
25168
+ The above copyright notice and this permission notice shall be included in
25169
+ all copies or substantial portions of the Software.
25170
+
25171
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25172
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25173
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25174
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25175
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25176
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25177
+ THE SOFTWARE.`
25178
+ }
25179
+ ];
25180
+ /**
25181
+ * The distro advisory databases behind v1/os/ (OS_ECOSYSTEMS), one record type each: the per-CVE
25182
+ * tracker records, which cover every release. Their licences differ from ATTRIBUTION's, so their
25183
+ * data is never merged into v1/packages.json: Ubuntu's and Alpine's are share-alike (CC-BY-SA-4.0),
25184
+ * and Debian states no licence for its tracker data (OSV.dev issue 6430), so only facts are kept
25185
+ * (package names, version ranges, CVE IDs) and the data is removed if Debian asks.
25186
+ */
25187
+ var OS_ATTRIBUTION = [
25188
+ {
25189
+ name: "Debian Security Tracker (via OSV.dev)",
25190
+ url: "https://security-tracker.debian.org/",
25191
+ license: "No licence stated by Debian; only facts are kept (package names, version ranges, CVE IDs), removed on request",
25192
+ prefixes: ["DEBIAN-CVE"],
25193
+ notice: null
25194
+ },
25195
+ {
25196
+ name: "Ubuntu CVE Tracker (Canonical, via OSV.dev)",
25197
+ url: "https://github.com/canonical/ubuntu-security-notices",
25198
+ license: "CC-BY-SA-4.0",
25199
+ prefixes: ["UBUNTU-CVE"],
25200
+ notice: "Ubuntu security data © Canonical Ltd., licensed under CC BY-SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0/). Changes: reduced to package names, version ranges and CVE IDs."
25201
+ },
25202
+ {
25203
+ name: "Alpine SecDB (via OSV.dev)",
25204
+ url: "https://secdb.alpinelinux.org/",
25205
+ license: "CC-BY-SA-4.0",
25206
+ prefixes: ["ALPINE-CVE"],
25207
+ notice: "Alpine Linux security database, licensed under CC BY-SA 4.0 (https://secdb.alpinelinux.org/license.txt). Changes: reduced to package names, version ranges and CVE IDs."
25208
+ }
25209
+ ];
25210
+ [...ATTRIBUTION, ...OS_ATTRIBUTION];
25211
+ /**
24783
25212
  * packages.json and packages-older.json as one index for the matcher: rows of both, and per ecosystem
24784
25213
  * and package key the entries of both. `older` may be null (an older data tree, or a failed load): the
24785
25214
  * result then is `tracked` as is. When the two come from different runs, a CVE in both keeps its
@@ -24824,739 +25253,781 @@ function mergePackageFiles(tracked, older) {
24824
25253
  packages
24825
25254
  };
24826
25255
  }
24827
- // cli/src/data.ts
24828
- /** A packages.json that matches the contract well enough to match against; else the reason it does not. */
24829
- function checkPackagesFile(doc) {
24830
- if (typeof doc !== "object" || doc === null || Array.isArray(doc)) return "not a JSON object";
24831
- const d = doc;
24832
- if (d.schema_version !== 1) return `schema_version ${String(d.schema_version)}, this tool reads 1`;
24833
- if (typeof d.generated_at !== "string" || Number.isNaN(Date.parse(d.generated_at))) return "no generated_at";
24834
- if (!Array.isArray(d.sources)) return "no sources";
24835
- if (!d.cves || !Array.isArray(d.cves.cols) || d.cves.cols.join() !== ROW_COLS.join() || !Array.isArray(d.cves.rows)) return "cves columns do not match";
24836
- if (typeof d.packages !== "object" || d.packages === null) return "no packages";
24837
- return d;
24838
- }
24839
- // mcp/src/data.ts
25256
+ // site/src/check/match.ts
24840
25257
  /**
24841
- * Reads the published data tree (shared/contract.ts) for the MCP tools.
25258
+ * Matches parsed packages against v1/packages.json: which tracked CVEs affect which versions.
24842
25259
  *
24843
- * - Bases are tried in order (the data branch on raw.githubusercontent.com, then the site's /data/
24844
- * rewrite). A 404 is final; 429, 403 and timeouts move that base to the back for 10 minutes;
24845
- * network errors, refused redirects, 5xx and malformed files fall through to the next base.
24846
- * - Every tool call runs under one deadline (10 s); each attempt must answer with headers within
24847
- * 4 s, and its body must not pause for 4 s. Bodies are capped at 24 MB decoded, which also stops
24848
- * a compression bomb from a mirror.
24849
- * - Files are checked before use: schema_version, generated_at, and the exact ROW_COLS of row
24850
- * tables, so no `__proto__` column can reach rowFromColumns.
24851
- * - Parsed files are cached per pipeline run. meta.json is refetched after 300 s (raw and the site
24852
- * cache for 300 s anyway); any other file is reused while its generated_at names meta's instant, and
24853
- * otherwise refetched at most once per 300 s. When a refresh fails, the last good copy answers
24854
- * and the answer's data.warning says so.
24855
- * - Nothing runs between calls: no polling, and every timer is cleared when its call ends.
25260
+ * The rule is OSV's, through shared/versions.ts (the pipeline uses the same code): a version is
25261
+ * affected when an advisory lists it or one of its ranges contains it. Anything that cannot be
25262
+ * compared is "possibly affected", never clean. Lookups go through Maps built once from the file,
25263
+ * so a package named `__proto__` or `constructor` cannot reach Object.prototype.
24856
25264
  */
24857
- /** A failure the tools report to the agent as is (isError: true). */
24858
- var DataError = class extends Error {
24859
- reasons;
24860
- constructor(message, reasons = []) {
24861
- super(message);
24862
- this.reasons = reasons;
24863
- this.name = "DataError";
25265
+ /** "Debian/12": how a distro release is named in OsCoverage. */
25266
+ var osTag = (eco, release) => `${eco}/${release}`;
25267
+ var NOT_CHECKED_ORDER = [
25268
+ "eco-down",
25269
+ "os-eol",
25270
+ "os-unknown",
25271
+ "os-release",
25272
+ "os-kernel",
25273
+ "ecosystem",
25274
+ "no-purl",
25275
+ "bad-purl",
25276
+ "not-registry",
25277
+ "dev-branch",
25278
+ "go-stdlib"
25279
+ ];
25280
+ /** The fixed version the matching range names next above `version`, if any. */
25281
+ function fixedIn(eco, version, ranges) {
25282
+ const c = COMPARATORS[eco];
25283
+ const v = c.parse(version);
25284
+ if (v === null) return null;
25285
+ for (const range of ranges) {
25286
+ if (compileRanges(eco, [range])(version) !== true) continue;
25287
+ let best = null;
25288
+ for (const e of range) {
25289
+ const p = parseEvent(e);
25290
+ if (p?.op !== "<") continue;
25291
+ const key = c.parse(p.v);
25292
+ if (key !== null && c.cmp(key, v) > 0 && (best === null || c.cmp(key, best.key) < 0)) best = {
25293
+ key,
25294
+ text: p.v
25295
+ };
25296
+ }
25297
+ if (best) return best.text;
24864
25298
  }
24865
- };
24866
- /** The file is not on the data branch (HTTP 404). Final: no other base is tried. */
24867
- var DataUnavailable = class extends DataError {};
24868
- /** The file has another schema_version. Final, and never answered from a cached copy. */
24869
- var SchemaMismatch = class extends DataError {};
24870
- var BadData = class extends Error {};
24871
- var DEFAULTS = {
24872
- metaTtlMs: 3e5,
24873
- attemptTimeoutMs: 4e3,
24874
- callTimeoutMs: 1e4,
24875
- maxBytes: 25165824,
24876
- maxShards: 64,
24877
- shardConcurrency: 6,
24878
- skipMs: 6e5,
24879
- now: Date.now
24880
- };
24881
- var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
24882
- var TIER_SET = new Set(TIERS);
24883
- /** A short string: ids, types and sources are tens of characters. */
24884
- var short = (v) => typeof v === "string" && v.length <= 200;
24885
- /** Every EventItem field with its type, so the tool never trips over a mirror's file. */
24886
- function isEvent(i) {
24887
- return short(i.id) && short(i.type) && short(i.cve) && short(i.via) && typeof i.title === "string" && typeof i.detail === "string" && (i.url === null || typeof i.url === "string") && TIER_SET.has(i.tier_after) && (i.tier_before === null || TIER_SET.has(i.tier_before)) && Number.isFinite(i.score) && typeof i.backfill === "boolean";
24888
- }
24889
- function need(ok, why) {
24890
- if (!ok) throw new BadData(why);
25299
+ return null;
24891
25300
  }
24892
- var parse$1 = {
24893
- meta: (j) => {
24894
- need(isObject(j.window) && Array.isArray(j.sources) && typeof j.knob_default === "number", "missing window, sources or knob_default");
24895
- return j;
24896
- },
24897
- rows: (j) => {
24898
- const cols = j.cols;
24899
- need(Array.isArray(cols) && cols.length === ROW_COLS.length && ROW_COLS.every((c, i) => cols[i] === c), "columns differ from ROW_COLS");
24900
- need(Array.isArray(j.rows) && j.rows.every((r) => Array.isArray(r) && r.length === ROW_COLS.length), "a row has the wrong length");
24901
- const rows = rowsFromTable({
24902
- cols: ROW_COLS,
24903
- rows: j.rows
25301
+ var isAffect = (a) => Array.isArray(a) && typeof a[0] === "string" && typeof a[1] === "string" && Array.isArray(a[2]);
25302
+ var GO_MAJOR = /^v[0-9]+$/;
25303
+ /**
25304
+ * Go paths an advisory names that may belong to a module in the file: the same path in other
25305
+ * letter case, and paths inside the module. A path belongs to the longest module of the file that
25306
+ * is a prefix of it (Go's rule), never across a /vN major-version element, which starts another
25307
+ * module. Prefixes compare in any letter case, so a lowercased package URL of a module owns the
25308
+ * paths inside it too. Built once per check from the file's own Go modules.
25309
+ */
25310
+ function goLookups(go, modules) {
25311
+ const lower = /* @__PURE__ */ new Map();
25312
+ const inside = /* @__PURE__ */ new Map();
25313
+ const add = (m, k, v) => {
25314
+ const list = m.get(k);
25315
+ if (list) list.push(v);
25316
+ else m.set(k, [v]);
25317
+ };
25318
+ const byLower = /* @__PURE__ */ new Map();
25319
+ for (const m of modules) add(byLower, m.toLowerCase(), m);
25320
+ for (const [key, list] of go) {
25321
+ if (!Array.isArray(list)) continue;
25322
+ add(lower, key.toLowerCase(), {
25323
+ key,
25324
+ list,
25325
+ reason: "name-case"
24904
25326
  });
24905
- return {
24906
- rows,
24907
- hay: rows.map((r) => `${r.id} ${r.cna} ${r.v} ${r.p} ${r.t}`.toLowerCase())
24908
- };
24909
- },
24910
- shard: (j) => {
24911
- need(isObject(j.items), "items is not an object");
24912
- return j;
24913
- },
24914
- kev: (j) => {
24915
- need(Array.isArray(j.entries), "entries is not a list");
24916
- return j;
24917
- },
24918
- woke: (j) => {
24919
- need(Array.isArray(j.items) && isObject(j.tracking), "items or tracking missing");
24920
- return j;
24921
- },
24922
- events: (j) => {
24923
- need(Array.isArray(j.items) && Number.isInteger(j.days) && Number.isInteger(j.max_items) && Number.isFinite(Date.parse(j.generated_at)), "items, days, max_items or generated_at missing");
24924
- need(j.items.every((i) => isObject(i) && typeof i.at === "string" && Number.isFinite(Date.parse(i.at)) && typeof i.vendor === "string" && typeof i.product === "string"), "an item has no valid at, vendor or product");
24925
- need(j.items.every(isEvent), "an item has a field of the wrong type");
24926
- return j;
24927
- },
24928
- /** packages.json and packages-older.json: the shape the matcher needs, with the exact row columns. */
24929
- packages: (j) => {
24930
- const checked = checkPackagesFile(j);
24931
- need(typeof checked !== "string", typeof checked === "string" ? checked : "");
24932
- return checked;
24933
- },
24934
- receipts: (j) => {
24935
- need(isObject(j.forward) && Array.isArray(j.forward.items), "forward log missing");
24936
- return j;
25327
+ if (byLower.has(key.toLowerCase())) continue;
25328
+ const parts = key.split("/");
25329
+ for (let i = parts.length - 1; i > 0; i--) {
25330
+ if (GO_MAJOR.test(parts[i])) break;
25331
+ const owners = byLower.get(parts.slice(0, i).join("/").toLowerCase());
25332
+ if (owners) {
25333
+ for (const owner of owners) add(inside, owner, {
25334
+ key,
25335
+ list,
25336
+ reason: "go-package"
25337
+ });
25338
+ break;
25339
+ }
25340
+ }
24937
25341
  }
24938
- };
24939
- var host = (url) => new URL(url).host;
24940
- function why(e) {
24941
- if (e instanceof AttemptTimeout) return e.message;
24942
- if (e instanceof BadData) return `not valid data: ${e.message}`;
24943
- const cause = e?.cause;
24944
- return cause?.code ?? cause?.message ?? (e instanceof Error ? e.message : String(e));
24945
- }
24946
- var AttemptTimeout = class extends Error {};
24947
- var Deadline = class extends Error {};
24948
- /** A promise that rejects with the signal's reason once it aborts, and a way to stop listening. */
24949
- function whenAborted(signal) {
24950
- let off = () => {};
24951
- const promise = new Promise((_, reject) => {
24952
- if (signal.aborted) return reject(signal.reason);
24953
- const on = () => reject(signal.reason);
24954
- signal.addEventListener("abort", on, { once: true });
24955
- off = () => signal.removeEventListener("abort", on);
24956
- });
24957
- promise.catch(() => {});
24958
25342
  return {
24959
- promise,
24960
- off
25343
+ lower,
25344
+ inside
24961
25345
  };
24962
25346
  }
24963
- /**
24964
- * Reads a body up to `max` decoded bytes. Every read races `stop`, so an abort ends the read even
24965
- * when it does not reach the stream itself; `progress` runs before each read (the stall timer).
24966
- */
24967
- async function readCapped(res, max, stop, progress) {
24968
- if (Number(res.headers.get("content-length") ?? "") > max) throw new Error(`body over ${max} bytes`);
24969
- if (!res.body) return "";
24970
- const reader = res.body.getReader();
24971
- const chunks = [];
24972
- let n = 0;
24973
- try {
24974
- for (;;) {
24975
- progress();
24976
- const { done, value } = await Promise.race([reader.read(), stop]);
24977
- if (done) break;
24978
- n += value.byteLength;
24979
- if (n > max) throw new Error(`body over ${max} bytes`);
24980
- chunks.push(value);
24981
- }
24982
- } catch (e) {
24983
- reader.cancel().catch(() => {});
24984
- throw e;
24985
- }
24986
- return Buffer.concat(chunks, n).toString("utf8");
24987
- }
24988
- var DataClient = class {
24989
- o;
24990
- files = /* @__PURE__ */ new Map();
24991
- /** Least recently inserted first; at most maxShards. */
24992
- shardCache = /* @__PURE__ */ new Map();
24993
- /** Fetches in progress, shared by concurrent calls, with the signal of the call that started each. */
24994
- inflight = /* @__PURE__ */ new Map();
24995
- skipUntil = /* @__PURE__ */ new Map();
24996
- /** Each running call's deadline, for the messages that name it. */
24997
- deadlines = /* @__PURE__ */ new WeakMap();
24998
- deadlineOf(signal) {
24999
- return this.deadlines.get(signal) ?? this.o.callTimeoutMs;
25000
- }
25001
- /** Requests sent, for tests and measurements. */
25002
- requests = 0;
25003
- constructor(opts) {
25004
- this.o = {
25005
- ...DEFAULTS,
25006
- fetch: (input, init) => fetch(input, init),
25007
- ...opts
25008
- };
25009
- if (this.o.bases.length === 0) throw new Error("DataClient needs at least one base URL");
25010
- }
25011
- get bases() {
25012
- return this.o.bases;
25013
- }
25014
- now() {
25015
- return this.o.now();
25016
- }
25017
- get shardConcurrency() {
25018
- return this.o.shardConcurrency;
25347
+ /** The key a component has in the index: its package key, after its release for a distro package. */
25348
+ var keyOf = (c, eco) => isOsEcosystem(eco) ? osPackageKey(c.release ?? "", c.name) : packageKey(eco, c.name);
25349
+ /** Check every package of `parsed` against the index. Pure: no I/O. */
25350
+ function checkComponents(parsed, file, os = null) {
25351
+ const rows = new Map(rowsFromTable(file.cves).map((r) => [r.id, r]));
25352
+ const index = /* @__PURE__ */ new Map();
25353
+ const ok = new Set(file.sources.filter((s) => s.ok).map((s) => s.ecosystem));
25354
+ for (const eco of ALL_ECOSYSTEMS) {
25355
+ const pkgs = file.packages?.[eco];
25356
+ if (ok.has(eco) && typeof pkgs === "object" && pkgs !== null) index.set(eco, new Map(Object.entries(pkgs)));
25019
25357
  }
25020
- /**
25021
- * Runs one tool call under its deadline. When the call ends, anything it left in flight (a
25022
- * shard fetch after another one failed) is aborted, so nothing keeps running between calls.
25023
- */
25024
- /** Run one tool call under a deadline: callTimeoutMs, or `timeoutMs` for a tool that reads larger files. */
25025
- async run(fn, timeoutMs = this.o.callTimeoutMs) {
25026
- const ac = new AbortController();
25027
- this.deadlines.set(ac.signal, timeoutMs);
25028
- const timer = setTimeout(() => ac.abort(new Deadline()), timeoutMs);
25029
- try {
25030
- return await fn(new DataCall(this, ac.signal));
25031
- } finally {
25032
- clearTimeout(timer);
25033
- ac.abort(new Deadline());
25358
+ const distinct = /* @__PURE__ */ new Map();
25359
+ const binaries = /* @__PURE__ */ new Map();
25360
+ for (const c of parsed.components) {
25361
+ const k = [
25362
+ c.eco ?? `~${c.type ?? ""}`,
25363
+ c.eco ? keyOf(c, c.eco) : c.name,
25364
+ c.version ?? "",
25365
+ c.skip ?? c.noVersion ?? ""
25366
+ ].join("\0");
25367
+ if (!distinct.get(k)) distinct.set(k, c.eco && isOsEcosystem(c.eco) ? { ...c } : c);
25368
+ if (c.eco && isOsEcosystem(c.eco)) {
25369
+ const list = binaries.get(k) ?? [];
25370
+ if (!list.includes(c.binary ?? c.name)) list.push(c.binary ?? c.name);
25371
+ binaries.set(k, list);
25034
25372
  }
25035
25373
  }
25036
- /** Bases in order, with the ones that recently answered 429 or 403, or timed out, moved to the back. */
25037
- orderedBases() {
25038
- const now = this.o.now();
25039
- const skipped = (b) => (this.skipUntil.get(b) ?? 0) > now;
25040
- return [...this.o.bases.filter((b) => !skipped(b)), ...this.o.bases.filter(skipped)];
25374
+ for (const [k, list] of binaries) {
25375
+ const c = distinct.get(k);
25376
+ if (list.length === 1 && list[0] === c.name) delete c.binary;
25377
+ else c.binary = list.join(", ");
25041
25378
  }
25042
- /**
25043
- * One GET within the call's deadline: response headers within attemptTimeoutMs, then a body that
25044
- * never pauses for longer than that (a slow body that keeps arriving is fine). The attempt has its
25045
- * own controller, aborted by a listener on the call's signal, and every await races it. Not
25046
- * AbortSignal.any(): its composite signal can be garbage-collected during a long body read, and
25047
- * then no abort reaches the read, which hung the call and every later call that joined its fetch.
25048
- */
25049
- async get(url, signal) {
25050
- if (signal.aborted) throw signal.reason;
25051
- const ac = new AbortController();
25052
- const forward = () => ac.abort(signal.reason);
25053
- signal.addEventListener("abort", forward, { once: true });
25054
- const stop = whenAborted(ac.signal);
25055
- const s = this.o.attemptTimeoutMs / 1e3;
25056
- let timer;
25057
- const arm = (why) => {
25058
- clearTimeout(timer);
25059
- timer = setTimeout(() => ac.abort(new AttemptTimeout(why)), this.o.attemptTimeoutMs);
25060
- };
25061
- arm(`timed out after ${s} s`);
25062
- this.requests++;
25063
- let res;
25064
- try {
25065
- res = await Promise.race([this.o.fetch(url, {
25066
- signal: ac.signal,
25067
- redirect: "error",
25068
- headers: { accept: "application/json" }
25069
- }), stop.promise]);
25070
- if (!res.ok) return {
25071
- status: res.status,
25072
- body: ""
25073
- };
25074
- return {
25075
- status: res.status,
25076
- body: await readCapped(res, this.o.maxBytes, stop.promise, () => arm(`stalled for ${s} s`))
25077
- };
25078
- } catch (e) {
25079
- throw ac.signal.aborted && !signal.aborted ? ac.signal.reason : e;
25080
- } finally {
25081
- clearTimeout(timer);
25082
- signal.removeEventListener("abort", forward);
25083
- stop.off();
25084
- if (res?.body && !res.bodyUsed) res.body.cancel().catch(() => {});
25379
+ const goIndex = index.get("Go");
25380
+ const goModules = /* @__PURE__ */ new Set();
25381
+ for (const c of distinct.values()) if (c.eco === "Go" && !c.skip) goModules.add(packageKey("Go", c.name));
25382
+ const go = goIndex ? goLookups(goIndex, goModules) : null;
25383
+ const notChecked = /* @__PURE__ */ new Map();
25384
+ const skip = (reason, c, eco, release) => {
25385
+ const k = `${reason}:${eco ?? ""}:${release ?? ""}`;
25386
+ let g = notChecked.get(k);
25387
+ if (!g) notChecked.set(k, g = release === void 0 ? {
25388
+ reason,
25389
+ eco,
25390
+ items: []
25391
+ } : {
25392
+ reason,
25393
+ eco,
25394
+ release,
25395
+ items: []
25396
+ });
25397
+ g.items.push(c);
25398
+ };
25399
+ const byCve = /* @__PURE__ */ new Map();
25400
+ const clean = [];
25401
+ const affectedKeys = /* @__PURE__ */ new Set();
25402
+ const possibleKeys = /* @__PURE__ */ new Set();
25403
+ for (const c of distinct.values()) {
25404
+ if (c.skip || !c.eco) {
25405
+ skip(c.skip ?? "ecosystem", c);
25406
+ continue;
25085
25407
  }
25086
- }
25087
- async fetchFile(path, parser, signal) {
25088
- const reasons = [];
25089
- for (const base of this.orderedBases()) {
25090
- const url = base + path;
25091
- let json;
25092
- try {
25093
- const res = await this.get(url, signal);
25094
- if (res.status === 404) throw new DataUnavailable(MCP_MSG.notPublished(path));
25095
- if (res.status < 200 || res.status > 299) {
25096
- if (res.status === 429 || res.status === 403) this.skipUntil.set(base, this.o.now() + this.o.skipMs);
25097
- reasons.push(`${host(url)}: HTTP ${res.status} for ${path}`);
25098
- continue;
25099
- }
25100
- json = JSON.parse(res.body);
25101
- need(isObject(json), "not a JSON object");
25102
- if (json.schema_version !== 1) throw new SchemaMismatch(MCP_MSG.schema(json.schema_version, 1));
25103
- need(typeof json.generated_at === "string", "no generated_at");
25104
- const now = this.o.now();
25105
- return {
25106
- value: parser(json),
25107
- gen: json.generated_at,
25108
- url,
25109
- loadedAt: now,
25110
- checkedAt: now,
25111
- warning: null
25112
- };
25113
- } catch (e) {
25114
- if (e instanceof DataError) throw e;
25115
- if (signal.aborted) throw new DataError(MCP_MSG.deadline([...reasons, `${host(url)}: no answer within ${this.deadlineOf(signal) / 1e3} s for ${path}`]), reasons);
25116
- if (e instanceof AttemptTimeout) this.skipUntil.set(base, this.o.now() + this.o.skipMs);
25117
- reasons.push(`${host(url)}: ${e instanceof SyntaxError ? "not valid JSON" : why(e)} for ${path}`);
25408
+ const eco = c.eco;
25409
+ if (isOsEcosystem(eco)) {
25410
+ const release = c.release ?? "";
25411
+ if (isKernelSource(c.name)) {
25412
+ skip("os-kernel", c, eco, release);
25413
+ continue;
25414
+ }
25415
+ const tag = osTag(eco, release);
25416
+ if (!os || !os.loaded.has(tag)) {
25417
+ skip(!os || os.failed.has(tag) ? "eco-down" : os.notFollowed.has(tag) ? "os-eol" : "os-unknown", c, eco, release);
25418
+ continue;
25118
25419
  }
25119
25420
  }
25120
- throw new DataError(MCP_MSG.allFailed(reasons), reasons);
25121
- }
25122
- /**
25123
- * A cached file, refreshed when needed. `gen` is the current meta.generated_at (null for meta
25124
- * itself, which only follows the TTL).
25125
- */
25126
- async load(path, parser, gen, signal) {
25127
- const cache = path.startsWith("cve/") ? this.shardCache : this.files;
25128
- const hit = cache.get(path);
25129
- const now = this.o.now();
25130
- if (hit && (gen !== null && Date.parse(hit.gen) === Date.parse(gen) || now - hit.checkedAt < this.o.metaTtlMs)) return hit;
25131
- let f = this.inflight.get(path);
25132
- if (!f) {
25133
- const mine = {
25134
- p: this.fetchFile(path, parser, signal),
25135
- signal
25421
+ const pkgs = index.get(eco);
25422
+ if (!pkgs) {
25423
+ skip("eco-down", c, eco);
25424
+ continue;
25425
+ }
25426
+ const key = keyOf(c, eco);
25427
+ const found = pkgs.get(key);
25428
+ const exact = Array.isArray(found) ? found : void 0;
25429
+ const lookups = exact ? [{
25430
+ key,
25431
+ list: exact,
25432
+ reason: null
25433
+ }] : [];
25434
+ if (eco === "Go" && go) {
25435
+ if (!exact) lookups.push(...go.lower.get(key.toLowerCase()) ?? []);
25436
+ lookups.push(...go.inside.get(key) ?? []);
25437
+ }
25438
+ const named = new Set((exact ?? []).filter(isAffect).map((a) => a[0]));
25439
+ const perCve = /* @__PURE__ */ new Map();
25440
+ for (const via of lookups) for (const a of via.list) {
25441
+ if (!isAffect(a)) continue;
25442
+ const [cve, id, ranges, versions = []] = a;
25443
+ if (via.reason && named.has(cve)) continue;
25444
+ const verdict = matchAffect(eco, c.version, ranges, versions);
25445
+ if (verdict === "not_affected") continue;
25446
+ let e = perCve.get(cve);
25447
+ if (e && e.via !== via) continue;
25448
+ if (!e) perCve.set(cve, e = {
25449
+ affected: [],
25450
+ unchecked: [],
25451
+ via
25452
+ });
25453
+ const listed = c.version !== null && versions.includes(c.version);
25454
+ const hit = {
25455
+ id,
25456
+ ranges,
25457
+ versions,
25458
+ listed,
25459
+ fixedIn: verdict === "affected" && c.version !== null && !listed ? fixedIn(eco, c.version, ranges) : null
25136
25460
  };
25137
- this.inflight.set(path, mine);
25138
- mine.p.then((e) => {
25139
- if (this.inflight.get(path) === mine) this.inflight.delete(path);
25140
- cache.delete(path);
25141
- cache.set(path, e);
25142
- if (cache === this.shardCache) {
25143
- for (const k of cache.keys()) if (cache.size > this.o.maxShards) cache.delete(k);
25144
- }
25145
- }, () => this.inflight.get(path) === mine && this.inflight.delete(path));
25146
- f = mine;
25461
+ (verdict === "affected" ? e.affected : e.unchecked).push(hit);
25147
25462
  }
25148
- const joined = f.signal !== signal;
25149
- const stop = joined ? whenAborted(signal) : null;
25150
- try {
25151
- return await (stop ? Promise.race([f.p, stop.promise]) : f.p);
25152
- } catch (err) {
25153
- if (joined && f.signal.aborted && !signal.aborted && !(err instanceof DataUnavailable) && !(err instanceof SchemaMismatch)) return this.load(path, parser, gen, signal);
25154
- const e = joined && signal.aborted && !(err instanceof DataError) ? new DataError(MCP_MSG.deadline([`no answer within ${this.deadlineOf(signal) / 1e3} s for ${path}`])) : err;
25155
- if (!hit || e instanceof DataUnavailable || e instanceof SchemaMismatch || !(e instanceof DataError)) throw e;
25156
- hit.checkedAt = this.o.now();
25157
- hit.warning = MCP_MSG.refreshFailed(e.reasons.length ? e.reasons : ["no answer in time"], new Date(hit.loadedAt).toISOString());
25158
- return hit;
25159
- } finally {
25160
- stop?.off();
25463
+ const id = `${eco}\u0000${key}\u0000${c.version ?? ""}`;
25464
+ let any = false;
25465
+ for (const [cve, e] of perCve) {
25466
+ if (!rows.has(cve)) continue;
25467
+ any = true;
25468
+ const inRange = e.affected.length > 0;
25469
+ const affected = inRange && e.via.reason === null;
25470
+ const unchecked = affected ? null : e.via.reason ?? c.noVersion ?? (c.version !== null && COMPARATORS[eco].parse(c.version) === null ? "version" : "range");
25471
+ let hits = byCve.get(cve);
25472
+ if (!hits) byCve.set(cve, hits = []);
25473
+ const hit = {
25474
+ eco,
25475
+ name: c.name,
25476
+ version: c.version,
25477
+ unchecked,
25478
+ advisories: inRange ? e.affected : e.unchecked
25479
+ };
25480
+ if (c.release) hit.release = c.release;
25481
+ if (c.binary) hit.binary = c.binary;
25482
+ if (e.via.reason) hit.named = e.via.key;
25483
+ hits.push(hit);
25484
+ (affected ? affectedKeys : possibleKeys).add(id);
25161
25485
  }
25486
+ if (!any) clean.push(c);
25162
25487
  }
25163
- };
25164
- /** One tool call: its deadline, the files it read and the warnings they carried. */
25165
- var DataCall = class {
25166
- dc;
25167
- signal;
25168
- files = /* @__PURE__ */ new Map();
25169
- warnings = /* @__PURE__ */ new Set();
25170
- metaEntry = null;
25171
- constructor(dc, signal) {
25172
- this.dc = dc;
25173
- this.signal = signal;
25174
- }
25175
- use(path, e) {
25176
- this.files.set(path, {
25177
- path: `v1/${path}`,
25178
- url: e.url,
25179
- generated_at: e.gen
25488
+ const cves = [];
25489
+ for (const [cve, packages] of byCve) {
25490
+ const row = rows.get(cve);
25491
+ if (row) cves.push({
25492
+ row,
25493
+ affected: packages.some((p) => p.unchecked === null),
25494
+ packages
25180
25495
  });
25181
- if (e.warning) this.warnings.add(e.warning);
25182
- return e.value;
25183
- }
25184
- async meta() {
25185
- this.metaEntry ??= await this.dc.load("meta.json", parse$1.meta, null, this.signal);
25186
- return this.use("meta.json", this.metaEntry);
25187
25496
  }
25188
- async file(path, parser) {
25189
- const meta = await this.meta();
25190
- return this.use(path, await this.dc.load(path, parser, meta.generated_at, this.signal));
25191
- }
25192
- /** The named shards (two hex digits each), fetched concurrently, a few at a time. */
25193
- async shards(names) {
25194
- const meta = await this.meta();
25195
- const out = /* @__PURE__ */ new Map();
25196
- const queue = [...new Set(names)];
25197
- const entries = /* @__PURE__ */ new Map();
25198
- const worker = async () => {
25199
- for (let name = queue.shift(); name !== void 0; name = queue.shift()) entries.set(name, await this.dc.load(`cve/${name}.json`, parse$1.shard, meta.generated_at, this.signal));
25200
- };
25201
- await Promise.all(Array.from({ length: Math.min(this.dc.shardConcurrency, queue.length) }, worker));
25202
- for (const name of [...new Set(names)]) {
25203
- const e = entries.get(name);
25204
- out.set(name, {
25205
- shard: this.use(`cve/${name}.json`, e),
25206
- url: e.url
25207
- });
25208
- }
25209
- return out;
25210
- }
25211
- };
25212
- /** CVERDICT_DATA_BASE: comma-separated base URLs. https only, or http on localhost for development. */
25213
- function basesFromEnv(value) {
25214
- if (!value?.trim()) return [...MCP_DATA_BASES];
25215
- return value.split(",").map((s) => s.trim()).filter(Boolean).map((s) => {
25216
- let u;
25217
- try {
25218
- u = new URL(s);
25219
- } catch {
25220
- throw new Error(`CVERDICT_DATA_BASE: not a URL: ${s}`);
25221
- }
25222
- const local = u.protocol === "http:" && [
25223
- "localhost",
25224
- "127.0.0.1",
25225
- "[::1]"
25226
- ].includes(u.hostname);
25227
- if (u.protocol !== "https:" && !local) throw new Error(`CVERDICT_DATA_BASE: use https (or http on localhost): ${s}`);
25228
- if (u.username || u.password || u.search || u.hash) throw new Error(`CVERDICT_DATA_BASE: no credentials, query or fragment: ${s}`);
25229
- return u.href.endsWith("/") ? u.href : `${u.href}/`;
25230
- });
25231
- }
25232
- function dataClientFromEnv(env) {
25233
- return new DataClient({ bases: basesFromEnv(env.CVERDICT_DATA_BASE) });
25497
+ for (const k of affectedKeys) possibleKeys.delete(k);
25498
+ const groups = [...notChecked.values()].sort((a, b) => NOT_CHECKED_ORDER.indexOf(a.reason) - NOT_CHECKED_ORDER.indexOf(b.reason) || (a.eco ?? "").localeCompare(b.eco ?? ""));
25499
+ const skipped = groups.reduce((n, g) => n + g.items.length, 0);
25500
+ return {
25501
+ format: parsed.format,
25502
+ total: parsed.components.length,
25503
+ distinct: distinct.size,
25504
+ checked: distinct.size - skipped,
25505
+ indexCves: rows.size,
25506
+ cves,
25507
+ affectedPackages: affectedKeys.size,
25508
+ possiblePackages: possibleKeys.size,
25509
+ notChecked: groups,
25510
+ clean,
25511
+ notes: parsed.notes
25512
+ };
25234
25513
  }
25235
- var c = (id, family, polarity, points, source, short, explain) => ({
25236
- id,
25237
- family,
25238
- polarity,
25239
- points,
25240
- source,
25241
- short,
25242
- explain
25243
- });
25244
- var CHIPS = [
25245
- c("kev.listed", "E", "up", 75, "kev", "CISA KEV", "Listed in CISA Known Exploited Vulnerabilities (or the CISA-ADP KEV block in the CVE record)."),
25246
- c("eukev.listed", "E", "up", 75, "eu-kev", "EU KEV", "Listed in ENISA’s EU Known Exploited Vulnerabilities catalog: ENISA or a national CSIRT of the EU CSIRTs Network reported exploitation. ENISA material, reproduced with acknowledgement."),
25247
- c("circl.listed", "E", "up", 75, "circl-kev", "CIRCL KEV", "CIRCL (Computer Incident Response Center Luxembourg, the CERT for Luxembourg’s private sector) lists it as confirmed exploited in its own known-exploited catalog (CC0-1.0), with evidence beyond exploitation attempts."),
25248
- c("ssvc.active", "E", "up", 75, "cisa-adp", "SSVC: active", "CISA Vulnrichment SSVC assessment says exploitation is active."),
25249
- c("vendor.exploited", "E", "up", 75, "cvelist", "Vendor: exploited", "The CNA’s own CVSS v4 vector says the bug is being attacked (E:A). VulDB vectors are ignored."),
25250
- c("vendor.itw", "E", "up", 75, "cvelist", "Vendor: in the wild", "The CNA description says the bug is exploited or “may have been exploited” in the wild."),
25251
- c("kev.ransomware", "E", "up", 5, "kev", "Ransomware", "CISA marks known use in ransomware campaigns. The flag lags, so its absence means little."),
25252
- c("x.metasploit", "X", "up", 34, "metasploit", "Metasploit", "A Metasploit module exists. Also forces at least the Likely tier."),
25253
- c("x.nuclei", "X", "up", 30, "nuclei", "Nuclei template", "A ProjectDiscovery Nuclei template exists, so it can be scanned for at internet scale. Forces at least Likely."),
25254
- c("x.exploitdb", "X", "up", 28, "exploitdb", "Exploit-DB", "An Exploit-DB entry references this CVE."),
25255
- c("epss.high", "X", "up", 27, "epss", "EPSS ≥ 10%", "EPSS gives ≥ 10% probability of exploitation activity in the next 30 days (only trusted after 14 days)."),
25256
- c("x.poc", "X", "up", 20, "poc-github", "PoC on GitHub", "At least one public proof-of-concept repo that passes basic vetting. Unverified code that may be malware."),
25257
- c("ssvc.poc", "X", "up", 10, "cisa-adp", "SSVC: PoC", "CISA SSVC assessment says a public proof of concept exists."),
25258
- c("vendor.functional", "X", "up", 24, "cvelist", "Vendor: working exploit", "The CNA’s CVSS v3 vector says functional or autonomous exploit code exists (E:F/E:H). That is weaponization, not proof of attacks: about a quarter of such CVEs reach KEV. VulDB vectors are ignored."),
25259
- c("vendor.poc", "X", "up", 10, "cvelist", "Vendor: PoC", "The CNA’s CVSS vector says a proof of concept exists (E:P). VulDB vectors are ignored."),
25260
- c("epss.mid", "X", "up", 8, "epss", "EPSS 1–10%", "EPSS between 1% and 10% (only trusted after 14 days)."),
25261
- c("fast.lane", "X", "up", 12, "computed", "Fast lane", "Less than 14 days old, attack vector Network with no user interaction, CISA SSVC automatable with total impact (or CVSS 9.0 or more while SSVC is not in yet), on an internet-facing edge device or a product already in CISA KEV. Attack tools can now turn a public reproducer into an exploit within hours for some bugs, before exploit feeds see it, so this stands in for an exploit sign. It is not evidence of attacks. The strongest X chip counts, so a real exploit replaces it."),
25262
- c("x.none", "X", "down", -14, "computed", "No exploit yet", "Two weeks after publication there is still no public exploit and EPSS is below 1%."),
25263
- c("x.early", "X", "down", -3, "computed", "No exploit yet (early)", "Less than 14 days old and no exploit signal yet. Weak evidence, so a small penalty: severity, SSVC and KEV history alone stay under the default evidence bar. Not applied to internet-facing edge devices, and replaced by the fast lane when that fires."),
25264
- c("x.too_new", "X", "unknown", 0, "computed", "Too new", "No exploit chip, but absence is not settled: a PoC repo is too new to vet, an exploit source could not be loaded this run, or the CVE is an internet-facing edge device under 14 days old."),
25265
- c("sev.crit_net", "SEV", "up", 13, "cvelist", "Critical · network", "CVSS ≥ 9.0 and attack vector Network."),
25266
- c("sev.crit", "SEV", "up", 6, "cvelist", "Critical", "CVSS ≥ 9.0, not network-reachable."),
25267
- c("sev.high", "SEV", "up", 1, "cvelist", "High", "CVSS 7.0–8.9. Half of all new CVEs are High or Critical, so this barely moves the needle."),
25268
- c("sev.low", "SEV", "down", -13, "cvelist", "Medium/Low", "CVSS below 7.0."),
25269
- c("sev.none", "SEV", "unknown", 0, "computed", "No CVSS", "Neither the CNA nor CISA-ADP published a CVSS score."),
25270
- c("ssvc.automatable", "SSVC", "up", 6, "cisa-adp", "Automatable", "CISA SSVC: steps 1–4 of the kill chain can be automated (wormable / mass-exploitable)."),
25271
- c("ssvc.not_automatable", "SSVC", "down", -2, "cisa-adp", "Not automatable", "CISA SSVC: exploitation cannot be reliably automated."),
25272
- c("ssvc.total", "SSVC", "up", 8, "cisa-adp", "Total impact", "CISA SSVC: full control of the affected component, or total information disclosure."),
25273
- c("ssvc.partial", "SSVC", "down", -6, "cisa-adp", "Partial impact", "CISA SSVC: limited control or information exposure."),
25274
- c("ssvc.missing", "SSVC", "unknown", 0, "computed", "No SSVC yet", "CISA has not published an SSVC assessment yet (usually arrives within a day)."),
25275
- c("prior.product", "PRIOR", "up", 10, "kev", "Product in KEV", "Other CVEs in this exact product are already in CISA KEV. Attackers return to the same targets."),
25276
- c("prior.vendor", "PRIOR", "up", 8, "kev", "Vendor in KEV", "Other products from this vendor are in CISA KEV."),
25277
- c("prior.none", "PRIOR", "down", -6, "kev", "Never in KEV", "Nothing from this vendor has ever been listed in CISA KEV."),
25278
- c("prior.unknown", "PRIOR", "unknown", 0, "computed", "KEV history unknown", "The record names no vendor, or the KEV catalog could not be loaded this run, so the KEV history check could not run."),
25279
- c("noise.hobby", "NOISE", "down", -20, "cvelist", "Tutorial project", "Student/tutorial code (SourceCodester, code-projects, PHPGurukul, …) that is rarely deployed."),
25280
- c("noise.disputed", "NOISE", "down", -15, "cvelist", "Disputed", "The CNA tagged this record as disputed."),
25281
- c("noise.wordpress", "NOISE", "down", -10, "cvelist", "WordPress plugin", "A WordPress plugin or theme. These are about 15% of all volume, and most have small install bases."),
25282
- c("noise.kernel", "NOISE", "down", -8, "cvelist", "Kernel bug-fix", "A Linux kernel CNA bug-fix CVE without total technical impact."),
25283
- c("ai.credit", "INFO", "info", 0, "cvelist", "AI-credited", "The CNA credits an AI system or AI lab for the discovery. Information only: AI-found bugs are exploited at about the base rate."),
25284
- c("batch", "INFO", "info", 0, "computed", "Batch release", "Published with 50+ other CVEs from the same CNA on the same day: a vendor patch day, or a bulk release by an aggregator CNA."),
25285
- c("kev.due", "INFO", "info", 0, "kev", "KEV due", "Federal agencies must remediate by the KEV due date."),
25286
- c("kev.forensic", "INFO", "info", 0, "kev", "Forensic triage", "CISA asks for forensic triage, not just patching (BOD 26-04)."),
25287
- c("sev.adp", "INFO", "info", 0, "cisa-adp", "CVSS from CISA", "The CNA gave no CVSS score; the CISA-ADP score is used instead."),
25288
- c("epss.cold", "INFO", "info", 0, "epss", "EPSS (cold)", "EPSS score shown for context only: the CVE is too new for EPSS to be meaningful."),
25289
- c("poc.hype", "INFO", "info", 0, "poc-github", "PoC hype", "More than 50 PoC repos appeared within a week. That measures attention, not weaponization, and fake PoCs often carry malware."),
25290
- c("poc.unvetted", "INFO", "info", 0, "poc-github", "Unvetted PoC", "Only brand-new, unstarred PoC repos exist. Not counted until they age or gain stars."),
25291
- c("circl.suspected", "INFO", "info", 0, "circl-kev", "CIRCL: suspected", "CIRCL lists exploitation as suspected, not confirmed (CC0-1.0). Information only."),
25292
- c("circl.attempts", "INFO", "info", 0, "circl-kev", "CIRCL: attempts", "CIRCL lists it as confirmed in its known-exploited catalog (CC0-1.0), but the only evidence is exploitation attempts, such as hits on a sinkhole. Attempts are not proof that an attack worked: information only."),
25293
- c("honeypot.siberkapan", "INFO", "info", 0, "siberkapan", "Honeypot attempts", "SiberKapan’s honeypot and web sensors in Turkey saw exploitation attempts (CC-BY-4.0). Attempts are not proof that an attack worked, and one sensor network gives too little data to set points: information only."),
25294
- c("edge.device", "INFO", "info", 0, "computed", "Edge device", "An internet-facing edge device: VPN, firewall, load balancer, email gateway, file transfer, webmail, remote support, SD-WAN or edge router (curated list in shared/edge.ts, explained in docs/SCORING.md). These are often attacked before any exploit is public, so the early no-exploit penalty does not apply."),
25295
- c("tag.eol", "INFO", "info", 0, "cvelist", "Unsupported product", "The product was unsupported when the CVE was assigned: there may be no patch. Replace or mitigate.")
25514
+ var GROUP_ORDER = [
25515
+ "exploited",
25516
+ "likely",
25517
+ "watch",
25518
+ "quiet",
25519
+ "possible"
25296
25520
  ];
25297
- Object.fromEntries(CHIPS.map((d) => [d.id, d]));
25298
- /** FNV-1a 32-bit hash of the upper-cased CVE ID. */
25299
- function fnv1a(input) {
25300
- let h = 2166136261;
25301
- for (let i = 0; i < input.length; i++) {
25302
- h ^= input.charCodeAt(i);
25303
- h = Math.imul(h, 16777619);
25304
- }
25305
- return h >>> 0;
25306
- }
25307
- /** Shard name for a CVE ID: two lowercase hex digits, e.g. "3f". */
25308
- function shardOf(cveId) {
25309
- return (fnv1a(cveId.trim().toUpperCase()) % 256).toString(16).padStart(2, "0");
25310
- }
25311
- var CVE_ID_RE = /^CVE-\d{4}-\d{4,}$/;
25312
- /**
25313
- * Slug of a vendor or product name: NFKD, accents dropped, lower case, every run of other
25314
- * characters becomes one hyphen, no hyphen at either end, at most SLUG_MAX characters. "" when
25315
- * nothing is left (a name with no ASCII letters or digits).
25316
- */
25317
- function slugify(name) {
25318
- return name.normalize("NFKD").replace(/\p{M}+/gu, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64).replace(/-+$/, "");
25521
+ /** CVEs grouped by tier at `knob` (possibly affected ones apart), each group by score, then newest. */
25522
+ function groupByTier(cves, knob) {
25523
+ const out = new Map(GROUP_ORDER.map((g) => [g, []]));
25524
+ for (const c of cves) out.get(c.affected ? tierFor(c.row.s, c.row.x === 1, c.row.w === 1, knob) : "possible").push(c);
25525
+ for (const list of out.values()) list.sort((a, b) => b.row.s - a.row.s || b.row.pub.localeCompare(a.row.pub) || a.row.id.localeCompare(b.row.id));
25526
+ return out;
25319
25527
  }
25320
- // shared/watch.ts
25321
- var normalizeName = (s) => s.trim().toLowerCase().replace(/\s+/g, " ");
25322
- /** True when a normalized name in `list` equals the vendor or the product. */
25323
- function matchesName(list, vendor, product) {
25324
- if (list.length === 0) return false;
25325
- return vendor !== "" && list.includes(normalizeName(vendor)) || product !== "" && list.includes(normalizeName(product));
25528
+ // cli/src/data.ts
25529
+ /** A packages.json that matches the contract well enough to match against; else the reason it does not. */
25530
+ function checkPackagesFile(doc) {
25531
+ if (typeof doc !== "object" || doc === null || Array.isArray(doc)) return "not a JSON object";
25532
+ const d = doc;
25533
+ if (d.schema_version !== 1) return `schema_version ${String(d.schema_version)}, this tool reads 1`;
25534
+ if (typeof d.generated_at !== "string" || Number.isNaN(Date.parse(d.generated_at))) return "no generated_at";
25535
+ if (!Array.isArray(d.sources)) return "no sources";
25536
+ if (!d.cves || !Array.isArray(d.cves.cols) || d.cves.cols.join() !== ROW_COLS.join() || !Array.isArray(d.cves.rows)) return "cves columns do not match";
25537
+ if (typeof d.packages !== "object" || d.packages === null) return "no packages";
25538
+ return d;
25326
25539
  }
25327
- // site/src/check/match.ts
25540
+ // mcp/src/data.ts
25328
25541
  /**
25329
- * Matches parsed packages against v1/packages.json: which tracked CVEs affect which versions.
25542
+ * Reads the published data tree (shared/contract.ts) for the MCP tools.
25330
25543
  *
25331
- * The rule is OSV's, through shared/versions.ts (the pipeline uses the same code): a version is
25332
- * affected when an advisory lists it or one of its ranges contains it. Anything that cannot be
25333
- * compared is "possibly affected", never clean. Lookups go through Maps built once from the file,
25334
- * so a package named `__proto__` or `constructor` cannot reach Object.prototype.
25544
+ * - Bases are tried in order (the data branch on raw.githubusercontent.com, then the site's /data/
25545
+ * rewrite). A 404 is final; 429, 403 and timeouts move that base to the back for 10 minutes;
25546
+ * network errors, refused redirects, 5xx and malformed files fall through to the next base.
25547
+ * - Every tool call runs under one deadline (10 s); each attempt must answer with headers within
25548
+ * 4 s, and its body must not pause for 4 s. Bodies are capped at 24 MB decoded, which also stops
25549
+ * a compression bomb from a mirror.
25550
+ * - Files are checked before use: schema_version, generated_at, and the exact ROW_COLS of row
25551
+ * tables, so no `__proto__` column can reach rowFromColumns.
25552
+ * - Parsed files are cached per pipeline run. meta.json is refetched after 300 s (raw and the site
25553
+ * cache for 300 s anyway); any other file is reused while its generated_at names meta's instant, and
25554
+ * otherwise refetched at most once per 300 s. When a refresh fails, the last good copy answers
25555
+ * and the answer's data.warning says so.
25556
+ * - Nothing runs between calls: no polling, and every timer is cleared when its call ends.
25335
25557
  */
25336
- var NOT_CHECKED_ORDER = [
25337
- "eco-down",
25338
- "ecosystem",
25339
- "no-purl",
25340
- "bad-purl",
25341
- "not-registry",
25342
- "dev-branch",
25343
- "go-stdlib"
25344
- ];
25345
- /** The fixed version the matching range names next above `version`, if any. */
25346
- function fixedIn(eco, version, ranges) {
25347
- const c = COMPARATORS[eco];
25348
- const v = c.parse(version);
25349
- if (v === null) return null;
25350
- for (const range of ranges) {
25351
- if (compileRanges(eco, [range])(version) !== true) continue;
25352
- let best = null;
25353
- for (const e of range) {
25354
- const p = parseEvent(e);
25355
- if (p?.op !== "<") continue;
25356
- const key = c.parse(p.v);
25357
- if (key !== null && c.cmp(key, v) > 0 && (best === null || c.cmp(key, best.key) < 0)) best = {
25358
- key,
25359
- text: p.v
25360
- };
25361
- }
25362
- if (best) return best.text;
25558
+ /** A failure the tools report to the agent as is (isError: true). */
25559
+ var DataError = class extends Error {
25560
+ reasons;
25561
+ constructor(message, reasons = []) {
25562
+ super(message);
25563
+ this.reasons = reasons;
25564
+ this.name = "DataError";
25363
25565
  }
25364
- return null;
25566
+ };
25567
+ /** The file is not on the data branch (HTTP 404). Final: no other base is tried. */
25568
+ var DataUnavailable = class extends DataError {};
25569
+ /** The file has another schema_version. Final, and never answered from a cached copy. */
25570
+ var SchemaMismatch = class extends DataError {};
25571
+ var BadData = class extends Error {};
25572
+ var DEFAULTS = {
25573
+ metaTtlMs: 3e5,
25574
+ attemptTimeoutMs: 4e3,
25575
+ callTimeoutMs: 1e4,
25576
+ maxBytes: 25165824,
25577
+ maxShards: 64,
25578
+ shardConcurrency: 6,
25579
+ skipMs: 6e5,
25580
+ now: Date.now
25581
+ };
25582
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
25583
+ var TIER_SET = new Set(TIERS);
25584
+ /** A short string: ids, types and sources are tens of characters. */
25585
+ var short = (v) => typeof v === "string" && v.length <= 200;
25586
+ /** Every EventItem field with its type, so the tool never trips over a mirror's file. */
25587
+ function isEvent(i) {
25588
+ return short(i.id) && short(i.type) && short(i.cve) && short(i.via) && typeof i.title === "string" && typeof i.detail === "string" && (i.url === null || typeof i.url === "string") && TIER_SET.has(i.tier_after) && (i.tier_before === null || TIER_SET.has(i.tier_before)) && Number.isFinite(i.score) && typeof i.backfill === "boolean";
25589
+ }
25590
+ function need(ok, why) {
25591
+ if (!ok) throw new BadData(why);
25592
+ }
25593
+ var parse$1 = {
25594
+ meta: (j) => {
25595
+ need(isObject(j.window) && Array.isArray(j.sources) && typeof j.knob_default === "number", "missing window, sources or knob_default");
25596
+ return j;
25597
+ },
25598
+ rows: (j) => {
25599
+ const cols = j.cols;
25600
+ need(Array.isArray(cols) && cols.length === ROW_COLS.length && ROW_COLS.every((c, i) => cols[i] === c), "columns differ from ROW_COLS");
25601
+ need(Array.isArray(j.rows) && j.rows.every((r) => Array.isArray(r) && r.length === ROW_COLS.length), "a row has the wrong length");
25602
+ const rows = rowsFromTable({
25603
+ cols: ROW_COLS,
25604
+ rows: j.rows
25605
+ });
25606
+ return {
25607
+ rows,
25608
+ hay: rows.map((r) => `${r.id} ${r.cna} ${r.v} ${r.p} ${r.t}`.toLowerCase())
25609
+ };
25610
+ },
25611
+ shard: (j) => {
25612
+ need(isObject(j.items), "items is not an object");
25613
+ return j;
25614
+ },
25615
+ kev: (j) => {
25616
+ need(Array.isArray(j.entries), "entries is not a list");
25617
+ return j;
25618
+ },
25619
+ woke: (j) => {
25620
+ need(Array.isArray(j.items) && isObject(j.tracking), "items or tracking missing");
25621
+ return j;
25622
+ },
25623
+ events: (j) => {
25624
+ need(Array.isArray(j.items) && Number.isInteger(j.days) && Number.isInteger(j.max_items) && Number.isFinite(Date.parse(j.generated_at)), "items, days, max_items or generated_at missing");
25625
+ need(j.items.every((i) => isObject(i) && typeof i.at === "string" && Number.isFinite(Date.parse(i.at)) && typeof i.vendor === "string" && typeof i.product === "string"), "an item has no valid at, vendor or product");
25626
+ need(j.items.every(isEvent), "an item has a field of the wrong type");
25627
+ return j;
25628
+ },
25629
+ /** packages.json and packages-older.json: the shape the matcher needs, with the exact row columns. */
25630
+ osIndex: (j) => {
25631
+ need(Array.isArray(j.releases) && Array.isArray(j.sources), "missing releases or sources");
25632
+ return j;
25633
+ },
25634
+ packages: (j) => {
25635
+ const checked = checkPackagesFile(j);
25636
+ need(typeof checked !== "string", typeof checked === "string" ? checked : "");
25637
+ return checked;
25638
+ },
25639
+ receipts: (j) => {
25640
+ need(isObject(j.forward) && Array.isArray(j.forward.items), "forward log missing");
25641
+ return j;
25642
+ }
25643
+ };
25644
+ var host = (url) => new URL(url).host;
25645
+ function why(e) {
25646
+ if (e instanceof AttemptTimeout) return e.message;
25647
+ if (e instanceof BadData) return `not valid data: ${e.message}`;
25648
+ const cause = e?.cause;
25649
+ return cause?.code ?? cause?.message ?? (e instanceof Error ? e.message : String(e));
25650
+ }
25651
+ var AttemptTimeout = class extends Error {};
25652
+ var Deadline = class extends Error {};
25653
+ /** A promise that rejects with the signal's reason once it aborts, and a way to stop listening. */
25654
+ function whenAborted(signal) {
25655
+ let off = () => {};
25656
+ const promise = new Promise((_, reject) => {
25657
+ if (signal.aborted) return reject(signal.reason);
25658
+ const on = () => reject(signal.reason);
25659
+ signal.addEventListener("abort", on, { once: true });
25660
+ off = () => signal.removeEventListener("abort", on);
25661
+ });
25662
+ promise.catch(() => {});
25663
+ return {
25664
+ promise,
25665
+ off
25666
+ };
25365
25667
  }
25366
- var isAffect = (a) => Array.isArray(a) && typeof a[0] === "string" && typeof a[1] === "string" && Array.isArray(a[2]);
25367
- var GO_MAJOR = /^v[0-9]+$/;
25368
25668
  /**
25369
- * Go paths an advisory names that may belong to a module in the file: the same path in other
25370
- * letter case, and paths inside the module. A path belongs to the longest module of the file that
25371
- * is a prefix of it (Go's rule), never across a /vN major-version element, which starts another
25372
- * module. Prefixes compare in any letter case, so a lowercased package URL of a module owns the
25373
- * paths inside it too. Built once per check from the file's own Go modules.
25669
+ * Reads a body up to `max` decoded bytes. Every read races `stop`, so an abort ends the read even
25670
+ * when it does not reach the stream itself; `progress` runs before each read (the stall timer).
25374
25671
  */
25375
- function goLookups(go, modules) {
25376
- const lower = /* @__PURE__ */ new Map();
25377
- const inside = /* @__PURE__ */ new Map();
25378
- const add = (m, k, v) => {
25379
- const list = m.get(k);
25380
- if (list) list.push(v);
25381
- else m.set(k, [v]);
25382
- };
25383
- const byLower = /* @__PURE__ */ new Map();
25384
- for (const m of modules) add(byLower, m.toLowerCase(), m);
25385
- for (const [key, list] of go) {
25386
- if (!Array.isArray(list)) continue;
25387
- add(lower, key.toLowerCase(), {
25388
- key,
25389
- list,
25390
- reason: "name-case"
25391
- });
25392
- if (byLower.has(key.toLowerCase())) continue;
25393
- const parts = key.split("/");
25394
- for (let i = parts.length - 1; i > 0; i--) {
25395
- if (GO_MAJOR.test(parts[i])) break;
25396
- const owners = byLower.get(parts.slice(0, i).join("/").toLowerCase());
25397
- if (owners) {
25398
- for (const owner of owners) add(inside, owner, {
25399
- key,
25400
- list,
25401
- reason: "go-package"
25402
- });
25403
- break;
25404
- }
25672
+ async function readCapped(res, max, stop, progress) {
25673
+ if (Number(res.headers.get("content-length") ?? "") > max) throw new Error(`body over ${max} bytes`);
25674
+ if (!res.body) return "";
25675
+ const reader = res.body.getReader();
25676
+ const chunks = [];
25677
+ let n = 0;
25678
+ try {
25679
+ for (;;) {
25680
+ progress();
25681
+ const { done, value } = await Promise.race([reader.read(), stop]);
25682
+ if (done) break;
25683
+ n += value.byteLength;
25684
+ if (n > max) throw new Error(`body over ${max} bytes`);
25685
+ chunks.push(value);
25405
25686
  }
25687
+ } catch (e) {
25688
+ reader.cancel().catch(() => {});
25689
+ throw e;
25690
+ }
25691
+ return Buffer.concat(chunks, n).toString("utf8");
25692
+ }
25693
+ var DataClient = class {
25694
+ o;
25695
+ files = /* @__PURE__ */ new Map();
25696
+ /** Least recently inserted first; at most maxShards. */
25697
+ shardCache = /* @__PURE__ */ new Map();
25698
+ /** Fetches in progress, shared by concurrent calls, with the signal of the call that started each. */
25699
+ inflight = /* @__PURE__ */ new Map();
25700
+ skipUntil = /* @__PURE__ */ new Map();
25701
+ /** Each running call's deadline, for the messages that name it. */
25702
+ deadlines = /* @__PURE__ */ new WeakMap();
25703
+ deadlineOf(signal) {
25704
+ return this.deadlines.get(signal) ?? this.o.callTimeoutMs;
25705
+ }
25706
+ /** Requests sent, for tests and measurements. */
25707
+ requests = 0;
25708
+ constructor(opts) {
25709
+ this.o = {
25710
+ ...DEFAULTS,
25711
+ fetch: (input, init) => fetch(input, init),
25712
+ ...opts
25713
+ };
25714
+ if (this.o.bases.length === 0) throw new Error("DataClient needs at least one base URL");
25406
25715
  }
25407
- return {
25408
- lower,
25409
- inside
25410
- };
25411
- }
25412
- /** Check every package of `parsed` against the index. Pure: no I/O. */
25413
- function checkComponents(parsed, file) {
25414
- const rows = new Map(rowsFromTable(file.cves).map((r) => [r.id, r]));
25415
- const index = /* @__PURE__ */ new Map();
25416
- const ok = new Set(file.sources.filter((s) => s.ok).map((s) => s.ecosystem));
25417
- for (const eco of PACKAGE_ECOSYSTEMS) {
25418
- const pkgs = file.packages?.[eco];
25419
- if (ok.has(eco) && typeof pkgs === "object" && pkgs !== null) index.set(eco, new Map(Object.entries(pkgs)));
25716
+ get bases() {
25717
+ return this.o.bases;
25420
25718
  }
25421
- const distinct = /* @__PURE__ */ new Map();
25422
- for (const c of parsed.components) {
25423
- const k = [
25424
- c.eco ?? `~${c.type ?? ""}`,
25425
- c.eco ? packageKey(c.eco, c.name) : c.name,
25426
- c.version ?? "",
25427
- c.skip ?? c.noVersion ?? ""
25428
- ].join("\0");
25429
- if (!distinct.has(k)) distinct.set(k, c);
25719
+ now() {
25720
+ return this.o.now();
25430
25721
  }
25431
- const goIndex = index.get("Go");
25432
- const goModules = /* @__PURE__ */ new Set();
25433
- for (const c of distinct.values()) if (c.eco === "Go" && !c.skip) goModules.add(packageKey("Go", c.name));
25434
- const go = goIndex ? goLookups(goIndex, goModules) : null;
25435
- const notChecked = /* @__PURE__ */ new Map();
25436
- const skip = (reason, c, eco) => {
25437
- const k = `${reason}:${eco ?? ""}`;
25438
- let g = notChecked.get(k);
25439
- if (!g) notChecked.set(k, g = {
25440
- reason,
25441
- eco,
25442
- items: []
25443
- });
25444
- g.items.push(c);
25445
- };
25446
- const byCve = /* @__PURE__ */ new Map();
25447
- const clean = [];
25448
- const affectedKeys = /* @__PURE__ */ new Set();
25449
- const possibleKeys = /* @__PURE__ */ new Set();
25450
- for (const c of distinct.values()) {
25451
- if (c.skip || !c.eco) {
25452
- skip(c.skip ?? "ecosystem", c);
25453
- continue;
25722
+ get shardConcurrency() {
25723
+ return this.o.shardConcurrency;
25724
+ }
25725
+ /**
25726
+ * Runs one tool call under its deadline. When the call ends, anything it left in flight (a
25727
+ * shard fetch after another one failed) is aborted, so nothing keeps running between calls.
25728
+ */
25729
+ /** Run one tool call under a deadline: callTimeoutMs, or `timeoutMs` for a tool that reads larger files. */
25730
+ async run(fn, timeoutMs = this.o.callTimeoutMs) {
25731
+ const ac = new AbortController();
25732
+ this.deadlines.set(ac.signal, timeoutMs);
25733
+ const timer = setTimeout(() => ac.abort(new Deadline()), timeoutMs);
25734
+ try {
25735
+ return await fn(new DataCall(this, ac.signal));
25736
+ } finally {
25737
+ clearTimeout(timer);
25738
+ ac.abort(new Deadline());
25454
25739
  }
25455
- const eco = c.eco;
25456
- const pkgs = index.get(eco);
25457
- if (!pkgs) {
25458
- skip("eco-down", c, eco);
25459
- continue;
25740
+ }
25741
+ /** Bases in order, with the ones that recently answered 429 or 403, or timed out, moved to the back. */
25742
+ orderedBases() {
25743
+ const now = this.o.now();
25744
+ const skipped = (b) => (this.skipUntil.get(b) ?? 0) > now;
25745
+ return [...this.o.bases.filter((b) => !skipped(b)), ...this.o.bases.filter(skipped)];
25746
+ }
25747
+ /**
25748
+ * One GET within the call's deadline: response headers within attemptTimeoutMs, then a body that
25749
+ * never pauses for longer than that (a slow body that keeps arriving is fine). The attempt has its
25750
+ * own controller, aborted by a listener on the call's signal, and every await races it. Not
25751
+ * AbortSignal.any(): its composite signal can be garbage-collected during a long body read, and
25752
+ * then no abort reaches the read, which hung the call and every later call that joined its fetch.
25753
+ */
25754
+ async get(url, signal) {
25755
+ if (signal.aborted) throw signal.reason;
25756
+ const ac = new AbortController();
25757
+ const forward = () => ac.abort(signal.reason);
25758
+ signal.addEventListener("abort", forward, { once: true });
25759
+ const stop = whenAborted(ac.signal);
25760
+ const s = this.o.attemptTimeoutMs / 1e3;
25761
+ let timer;
25762
+ const arm = (why) => {
25763
+ clearTimeout(timer);
25764
+ timer = setTimeout(() => ac.abort(new AttemptTimeout(why)), this.o.attemptTimeoutMs);
25765
+ };
25766
+ arm(`timed out after ${s} s`);
25767
+ this.requests++;
25768
+ let res;
25769
+ try {
25770
+ res = await Promise.race([this.o.fetch(url, {
25771
+ signal: ac.signal,
25772
+ redirect: "error",
25773
+ headers: { accept: "application/json" }
25774
+ }), stop.promise]);
25775
+ if (!res.ok) return {
25776
+ status: res.status,
25777
+ body: ""
25778
+ };
25779
+ return {
25780
+ status: res.status,
25781
+ body: await readCapped(res, this.o.maxBytes, stop.promise, () => arm(`stalled for ${s} s`))
25782
+ };
25783
+ } catch (e) {
25784
+ throw ac.signal.aborted && !signal.aborted ? ac.signal.reason : e;
25785
+ } finally {
25786
+ clearTimeout(timer);
25787
+ signal.removeEventListener("abort", forward);
25788
+ stop.off();
25789
+ if (res?.body && !res.bodyUsed) res.body.cancel().catch(() => {});
25460
25790
  }
25461
- const key = packageKey(eco, c.name);
25462
- const found = pkgs.get(key);
25463
- const exact = Array.isArray(found) ? found : void 0;
25464
- const lookups = exact ? [{
25465
- key,
25466
- list: exact,
25467
- reason: null
25468
- }] : [];
25469
- if (eco === "Go" && go) {
25470
- if (!exact) lookups.push(...go.lower.get(key.toLowerCase()) ?? []);
25471
- lookups.push(...go.inside.get(key) ?? []);
25791
+ }
25792
+ async fetchFile(path, parser, signal) {
25793
+ const reasons = [];
25794
+ for (const base of this.orderedBases()) {
25795
+ const url = base + path;
25796
+ let json;
25797
+ try {
25798
+ const res = await this.get(url, signal);
25799
+ if (res.status === 404) throw new DataUnavailable(MCP_MSG.notPublished(path));
25800
+ if (res.status < 200 || res.status > 299) {
25801
+ if (res.status === 429 || res.status === 403) this.skipUntil.set(base, this.o.now() + this.o.skipMs);
25802
+ reasons.push(`${host(url)}: HTTP ${res.status} for ${path}`);
25803
+ continue;
25804
+ }
25805
+ json = JSON.parse(res.body);
25806
+ need(isObject(json), "not a JSON object");
25807
+ if (json.schema_version !== 1) throw new SchemaMismatch(MCP_MSG.schema(json.schema_version, 1));
25808
+ need(typeof json.generated_at === "string", "no generated_at");
25809
+ const now = this.o.now();
25810
+ return {
25811
+ value: parser(json),
25812
+ gen: json.generated_at,
25813
+ url,
25814
+ loadedAt: now,
25815
+ checkedAt: now,
25816
+ warning: null
25817
+ };
25818
+ } catch (e) {
25819
+ if (e instanceof DataError) throw e;
25820
+ if (signal.aborted) throw new DataError(MCP_MSG.deadline([...reasons, `${host(url)}: no answer within ${this.deadlineOf(signal) / 1e3} s for ${path}`]), reasons);
25821
+ if (e instanceof AttemptTimeout) this.skipUntil.set(base, this.o.now() + this.o.skipMs);
25822
+ reasons.push(`${host(url)}: ${e instanceof SyntaxError ? "not valid JSON" : why(e)} for ${path}`);
25823
+ }
25472
25824
  }
25473
- const named = new Set((exact ?? []).filter(isAffect).map((a) => a[0]));
25474
- const perCve = /* @__PURE__ */ new Map();
25475
- for (const via of lookups) for (const a of via.list) {
25476
- if (!isAffect(a)) continue;
25477
- const [cve, id, ranges, versions = []] = a;
25478
- if (via.reason && named.has(cve)) continue;
25479
- const verdict = matchAffect(eco, c.version, ranges, versions);
25480
- if (verdict === "not_affected") continue;
25481
- let e = perCve.get(cve);
25482
- if (e && e.via !== via) continue;
25483
- if (!e) perCve.set(cve, e = {
25484
- affected: [],
25485
- unchecked: [],
25486
- via
25487
- });
25488
- const listed = c.version !== null && versions.includes(c.version);
25489
- const hit = {
25490
- id,
25491
- ranges,
25492
- versions,
25493
- listed,
25494
- fixedIn: verdict === "affected" && c.version !== null && !listed ? fixedIn(eco, c.version, ranges) : null
25825
+ throw new DataError(MCP_MSG.allFailed(reasons), reasons);
25826
+ }
25827
+ /**
25828
+ * A cached file, refreshed when needed. `gen` is the current meta.generated_at (null for meta
25829
+ * itself, which only follows the TTL).
25830
+ */
25831
+ async load(path, parser, gen, signal) {
25832
+ const cache = path.startsWith("cve/") ? this.shardCache : this.files;
25833
+ const hit = cache.get(path);
25834
+ const now = this.o.now();
25835
+ if (hit && (gen !== null && Date.parse(hit.gen) === Date.parse(gen) || now - hit.checkedAt < this.o.metaTtlMs)) return hit;
25836
+ let f = this.inflight.get(path);
25837
+ if (!f) {
25838
+ const mine = {
25839
+ p: this.fetchFile(path, parser, signal),
25840
+ signal
25495
25841
  };
25496
- (verdict === "affected" ? e.affected : e.unchecked).push(hit);
25842
+ this.inflight.set(path, mine);
25843
+ mine.p.then((e) => {
25844
+ if (this.inflight.get(path) === mine) this.inflight.delete(path);
25845
+ cache.delete(path);
25846
+ cache.set(path, e);
25847
+ if (cache === this.shardCache) {
25848
+ for (const k of cache.keys()) if (cache.size > this.o.maxShards) cache.delete(k);
25849
+ }
25850
+ }, () => this.inflight.get(path) === mine && this.inflight.delete(path));
25851
+ f = mine;
25497
25852
  }
25498
- const id = `${eco}\u0000${key}\u0000${c.version ?? ""}`;
25499
- let any = false;
25500
- for (const [cve, e] of perCve) {
25501
- if (!rows.has(cve)) continue;
25502
- any = true;
25503
- const inRange = e.affected.length > 0;
25504
- const affected = inRange && e.via.reason === null;
25505
- const unchecked = affected ? null : e.via.reason ?? c.noVersion ?? (c.version !== null && COMPARATORS[eco].parse(c.version) === null ? "version" : "range");
25506
- let hits = byCve.get(cve);
25507
- if (!hits) byCve.set(cve, hits = []);
25508
- const hit = {
25509
- eco,
25510
- name: c.name,
25511
- version: c.version,
25512
- unchecked,
25513
- advisories: inRange ? e.affected : e.unchecked
25514
- };
25515
- if (e.via.reason) hit.named = e.via.key;
25516
- hits.push(hit);
25517
- (affected ? affectedKeys : possibleKeys).add(id);
25853
+ const joined = f.signal !== signal;
25854
+ const stop = joined ? whenAborted(signal) : null;
25855
+ try {
25856
+ return await (stop ? Promise.race([f.p, stop.promise]) : f.p);
25857
+ } catch (err) {
25858
+ if (joined && f.signal.aborted && !signal.aborted && !(err instanceof DataUnavailable) && !(err instanceof SchemaMismatch)) return this.load(path, parser, gen, signal);
25859
+ const e = joined && signal.aborted && !(err instanceof DataError) ? new DataError(MCP_MSG.deadline([`no answer within ${this.deadlineOf(signal) / 1e3} s for ${path}`])) : err;
25860
+ if (!hit || e instanceof DataUnavailable || e instanceof SchemaMismatch || !(e instanceof DataError)) throw e;
25861
+ hit.checkedAt = this.o.now();
25862
+ hit.warning = MCP_MSG.refreshFailed(e.reasons.length ? e.reasons : ["no answer in time"], new Date(hit.loadedAt).toISOString());
25863
+ return hit;
25864
+ } finally {
25865
+ stop?.off();
25518
25866
  }
25519
- if (!any) clean.push(c);
25520
25867
  }
25521
- const cves = [];
25522
- for (const [cve, packages] of byCve) {
25523
- const row = rows.get(cve);
25524
- if (row) cves.push({
25525
- row,
25526
- affected: packages.some((p) => p.unchecked === null),
25527
- packages
25868
+ };
25869
+ /** One tool call: its deadline, the files it read and the warnings they carried. */
25870
+ var DataCall = class {
25871
+ dc;
25872
+ signal;
25873
+ files = /* @__PURE__ */ new Map();
25874
+ warnings = /* @__PURE__ */ new Set();
25875
+ metaEntry = null;
25876
+ constructor(dc, signal) {
25877
+ this.dc = dc;
25878
+ this.signal = signal;
25879
+ }
25880
+ use(path, e) {
25881
+ this.files.set(path, {
25882
+ path: `v1/${path}`,
25883
+ url: e.url,
25884
+ generated_at: e.gen
25528
25885
  });
25886
+ if (e.warning) this.warnings.add(e.warning);
25887
+ return e.value;
25529
25888
  }
25530
- for (const k of affectedKeys) possibleKeys.delete(k);
25531
- const groups = [...notChecked.values()].sort((a, b) => NOT_CHECKED_ORDER.indexOf(a.reason) - NOT_CHECKED_ORDER.indexOf(b.reason) || (a.eco ?? "").localeCompare(b.eco ?? ""));
25532
- const skipped = groups.reduce((n, g) => n + g.items.length, 0);
25533
- return {
25534
- format: parsed.format,
25535
- total: parsed.components.length,
25536
- distinct: distinct.size,
25537
- checked: distinct.size - skipped,
25538
- indexCves: rows.size,
25539
- cves,
25540
- affectedPackages: affectedKeys.size,
25541
- possiblePackages: possibleKeys.size,
25542
- notChecked: groups,
25543
- clean,
25544
- notes: parsed.notes
25545
- };
25889
+ async meta() {
25890
+ this.metaEntry ??= await this.dc.load("meta.json", parse$1.meta, null, this.signal);
25891
+ return this.use("meta.json", this.metaEntry);
25892
+ }
25893
+ async file(path, parser) {
25894
+ const meta = await this.meta();
25895
+ return this.use(path, await this.dc.load(path, parser, meta.generated_at, this.signal));
25896
+ }
25897
+ /** The named shards (two hex digits each), fetched concurrently, a few at a time. */
25898
+ async shards(names) {
25899
+ const meta = await this.meta();
25900
+ const out = /* @__PURE__ */ new Map();
25901
+ const queue = [...new Set(names)];
25902
+ const entries = /* @__PURE__ */ new Map();
25903
+ const worker = async () => {
25904
+ for (let name = queue.shift(); name !== void 0; name = queue.shift()) entries.set(name, await this.dc.load(`cve/${name}.json`, parse$1.shard, meta.generated_at, this.signal));
25905
+ };
25906
+ await Promise.all(Array.from({ length: Math.min(this.dc.shardConcurrency, queue.length) }, worker));
25907
+ for (const name of [...new Set(names)]) {
25908
+ const e = entries.get(name);
25909
+ out.set(name, {
25910
+ shard: this.use(`cve/${name}.json`, e),
25911
+ url: e.url
25912
+ });
25913
+ }
25914
+ return out;
25915
+ }
25916
+ };
25917
+ /** CVERDICT_DATA_BASE: comma-separated base URLs. https only, or http on localhost for development. */
25918
+ function basesFromEnv(value) {
25919
+ if (!value?.trim()) return [...MCP_DATA_BASES];
25920
+ return value.split(",").map((s) => s.trim()).filter(Boolean).map((s) => {
25921
+ let u;
25922
+ try {
25923
+ u = new URL(s);
25924
+ } catch {
25925
+ throw new Error(`CVERDICT_DATA_BASE: not a URL: ${s}`);
25926
+ }
25927
+ const local = u.protocol === "http:" && [
25928
+ "localhost",
25929
+ "127.0.0.1",
25930
+ "[::1]"
25931
+ ].includes(u.hostname);
25932
+ if (u.protocol !== "https:" && !local) throw new Error(`CVERDICT_DATA_BASE: use https (or http on localhost): ${s}`);
25933
+ if (u.username || u.password || u.search || u.hash) throw new Error(`CVERDICT_DATA_BASE: no credentials, query or fragment: ${s}`);
25934
+ return u.href.endsWith("/") ? u.href : `${u.href}/`;
25935
+ });
25546
25936
  }
25547
- var GROUP_ORDER = [
25548
- "exploited",
25549
- "likely",
25550
- "watch",
25551
- "quiet",
25552
- "possible"
25937
+ function dataClientFromEnv(env) {
25938
+ return new DataClient({ bases: basesFromEnv(env.CVERDICT_DATA_BASE) });
25939
+ }
25940
+ var c = (id, family, polarity, points, source, short, explain) => ({
25941
+ id,
25942
+ family,
25943
+ polarity,
25944
+ points,
25945
+ source,
25946
+ short,
25947
+ explain
25948
+ });
25949
+ var CHIPS = [
25950
+ c("kev.listed", "E", "up", 75, "kev", "CISA KEV", "Listed in CISA Known Exploited Vulnerabilities (or the CISA-ADP KEV block in the CVE record)."),
25951
+ c("eukev.listed", "E", "up", 75, "eu-kev", "EU KEV", "Listed in ENISA’s EU Known Exploited Vulnerabilities catalog: ENISA or a national CSIRT of the EU CSIRTs Network reported exploitation. ENISA material, reproduced with acknowledgement."),
25952
+ c("circl.listed", "E", "up", 75, "circl-kev", "CIRCL KEV", "CIRCL (Computer Incident Response Center Luxembourg, the CERT for Luxembourg’s private sector) lists it as confirmed exploited in its own known-exploited catalog (CC0-1.0), with evidence beyond exploitation attempts."),
25953
+ c("ssvc.active", "E", "up", 75, "cisa-adp", "SSVC: active", "CISA Vulnrichment SSVC assessment says exploitation is active."),
25954
+ c("vendor.exploited", "E", "up", 75, "cvelist", "Vendor: exploited", "The CNA’s own CVSS v4 vector says the bug is being attacked (E:A). VulDB vectors are ignored."),
25955
+ c("vendor.itw", "E", "up", 75, "cvelist", "Vendor: in the wild", "The CNA description says the bug is exploited or “may have been exploited” in the wild."),
25956
+ c("kev.ransomware", "E", "up", 5, "kev", "Ransomware", "CISA marks known use in ransomware campaigns. The flag lags, so its absence means little."),
25957
+ c("x.metasploit", "X", "up", 34, "metasploit", "Metasploit", "A Metasploit module exists. Also forces at least the Likely tier."),
25958
+ c("x.nuclei", "X", "up", 30, "nuclei", "Nuclei template", "A ProjectDiscovery Nuclei template exists, so it can be scanned for at internet scale. Forces at least Likely."),
25959
+ c("x.exploitdb", "X", "up", 28, "exploitdb", "Exploit-DB", "An Exploit-DB entry references this CVE."),
25960
+ c("epss.high", "X", "up", 27, "epss", "EPSS ≥ 10%", "EPSS gives ≥ 10% probability of exploitation activity in the next 30 days (only trusted after 14 days)."),
25961
+ c("x.poc", "X", "up", 20, "poc-github", "PoC on GitHub", "At least one public proof-of-concept repo that passes basic vetting. Unverified code that may be malware."),
25962
+ c("ssvc.poc", "X", "up", 10, "cisa-adp", "SSVC: PoC", "CISA SSVC assessment says a public proof of concept exists."),
25963
+ c("vendor.functional", "X", "up", 24, "cvelist", "Vendor: working exploit", "The CNA’s CVSS v3 vector says functional or autonomous exploit code exists (E:F/E:H). That is weaponization, not proof of attacks: about a quarter of such CVEs reach KEV. VulDB vectors are ignored."),
25964
+ c("vendor.poc", "X", "up", 10, "cvelist", "Vendor: PoC", "The CNA’s CVSS vector says a proof of concept exists (E:P). VulDB vectors are ignored."),
25965
+ c("epss.mid", "X", "up", 8, "epss", "EPSS 1–10%", "EPSS between 1% and 10% (only trusted after 14 days)."),
25966
+ c("fast.lane", "X", "up", 12, "computed", "Fast lane", "Less than 14 days old, attack vector Network with no user interaction, CISA SSVC automatable with total impact (or CVSS 9.0 or more while SSVC is not in yet), on an internet-facing edge device or a product already in CISA KEV. Attack tools can now turn a public reproducer into an exploit within hours for some bugs, before exploit feeds see it, so this stands in for an exploit sign. It is not evidence of attacks. The strongest X chip counts, so a real exploit replaces it."),
25967
+ c("x.none", "X", "down", -14, "computed", "No exploit yet", "Two weeks after publication there is still no public exploit and EPSS is below 1%."),
25968
+ c("x.early", "X", "down", -3, "computed", "No exploit yet (early)", "Less than 14 days old and no exploit signal yet. Weak evidence, so a small penalty: severity, SSVC and KEV history alone stay under the default evidence bar. Not applied to internet-facing edge devices, and replaced by the fast lane when that fires."),
25969
+ c("x.too_new", "X", "unknown", 0, "computed", "Too new", "No exploit chip, but absence is not settled: a PoC repo is too new to vet, an exploit source could not be loaded this run, or the CVE is an internet-facing edge device under 14 days old."),
25970
+ c("sev.crit_net", "SEV", "up", 13, "cvelist", "Critical · network", "CVSS ≥ 9.0 and attack vector Network."),
25971
+ c("sev.crit", "SEV", "up", 6, "cvelist", "Critical", "CVSS ≥ 9.0, not network-reachable."),
25972
+ c("sev.high", "SEV", "up", 1, "cvelist", "High", "CVSS 7.0–8.9. Half of all new CVEs are High or Critical, so this barely moves the needle."),
25973
+ c("sev.low", "SEV", "down", -13, "cvelist", "Medium/Low", "CVSS below 7.0."),
25974
+ c("sev.none", "SEV", "unknown", 0, "computed", "No CVSS", "Neither the CNA nor CISA-ADP published a CVSS score."),
25975
+ c("ssvc.automatable", "SSVC", "up", 6, "cisa-adp", "Automatable", "CISA SSVC: steps 1–4 of the kill chain can be automated (wormable / mass-exploitable)."),
25976
+ c("ssvc.not_automatable", "SSVC", "down", -2, "cisa-adp", "Not automatable", "CISA SSVC: exploitation cannot be reliably automated."),
25977
+ c("ssvc.total", "SSVC", "up", 8, "cisa-adp", "Total impact", "CISA SSVC: full control of the affected component, or total information disclosure."),
25978
+ c("ssvc.partial", "SSVC", "down", -6, "cisa-adp", "Partial impact", "CISA SSVC: limited control or information exposure."),
25979
+ c("ssvc.missing", "SSVC", "unknown", 0, "computed", "No SSVC yet", "CISA has not published an SSVC assessment yet (usually arrives within a day)."),
25980
+ c("prior.product", "PRIOR", "up", 10, "kev", "Product in KEV", "Other CVEs in this exact product are already in CISA KEV. Attackers return to the same targets."),
25981
+ c("prior.vendor", "PRIOR", "up", 8, "kev", "Vendor in KEV", "Other products from this vendor are in CISA KEV."),
25982
+ c("prior.none", "PRIOR", "down", -6, "kev", "Never in KEV", "Nothing from this vendor has ever been listed in CISA KEV."),
25983
+ c("prior.unknown", "PRIOR", "unknown", 0, "computed", "KEV history unknown", "The record names no vendor, or the KEV catalog could not be loaded this run, so the KEV history check could not run."),
25984
+ c("noise.hobby", "NOISE", "down", -20, "cvelist", "Tutorial project", "Student/tutorial code (SourceCodester, code-projects, PHPGurukul, …) that is rarely deployed."),
25985
+ c("noise.disputed", "NOISE", "down", -15, "cvelist", "Disputed", "The CNA tagged this record as disputed."),
25986
+ c("noise.wordpress", "NOISE", "down", -10, "cvelist", "WordPress plugin", "A WordPress plugin or theme. These are about 15% of all volume, and most have small install bases."),
25987
+ c("noise.kernel", "NOISE", "down", -8, "cvelist", "Kernel bug-fix", "A Linux kernel CNA bug-fix CVE without total technical impact."),
25988
+ c("ai.credit", "INFO", "info", 0, "cvelist", "AI-credited", "The CNA credits an AI system or AI lab for the discovery. Information only: AI-found bugs are exploited at about the base rate."),
25989
+ c("batch", "INFO", "info", 0, "computed", "Batch release", "Published with 50+ other CVEs from the same CNA on the same day: a vendor patch day, or a bulk release by an aggregator CNA."),
25990
+ c("kev.due", "INFO", "info", 0, "kev", "KEV due", "Federal agencies must remediate by the KEV due date."),
25991
+ c("kev.forensic", "INFO", "info", 0, "kev", "Forensic triage", "CISA asks for forensic triage, not just patching (BOD 26-04)."),
25992
+ c("sev.adp", "INFO", "info", 0, "cisa-adp", "CVSS from CISA", "The CNA gave no CVSS score; the CISA-ADP score is used instead."),
25993
+ c("epss.cold", "INFO", "info", 0, "epss", "EPSS (cold)", "EPSS score shown for context only: the CVE is too new for EPSS to be meaningful."),
25994
+ c("poc.hype", "INFO", "info", 0, "poc-github", "PoC hype", "More than 50 PoC repos appeared within a week. That measures attention, not weaponization, and fake PoCs often carry malware."),
25995
+ c("poc.unvetted", "INFO", "info", 0, "poc-github", "Unvetted PoC", "Only brand-new, unstarred PoC repos exist. Not counted until they age or gain stars."),
25996
+ c("circl.suspected", "INFO", "info", 0, "circl-kev", "CIRCL: suspected", "CIRCL lists exploitation as suspected, not confirmed (CC0-1.0). Information only."),
25997
+ c("circl.attempts", "INFO", "info", 0, "circl-kev", "CIRCL: attempts", "CIRCL lists it as confirmed in its known-exploited catalog (CC0-1.0), but the only evidence is exploitation attempts, such as hits on a sinkhole. Attempts are not proof that an attack worked: information only."),
25998
+ c("honeypot.siberkapan", "INFO", "info", 0, "siberkapan", "Honeypot attempts", "SiberKapan’s honeypot and web sensors in Turkey saw exploitation attempts (CC-BY-4.0). Attempts are not proof that an attack worked, and one sensor network gives too little data to set points: information only."),
25999
+ c("edge.device", "INFO", "info", 0, "computed", "Edge device", "An internet-facing edge device: VPN, firewall, load balancer, email gateway, file transfer, webmail, remote support, SD-WAN or edge router (curated list in shared/edge.ts, explained in docs/SCORING.md). These are often attacked before any exploit is public, so the early no-exploit penalty does not apply."),
26000
+ c("tag.eol", "INFO", "info", 0, "cvelist", "Unsupported product", "The product was unsupported when the CVE was assigned: there may be no patch. Replace or mitigate.")
25553
26001
  ];
25554
- /** CVEs grouped by tier at `knob` (possibly affected ones apart), each group by score, then newest. */
25555
- function groupByTier(cves, knob) {
25556
- const out = new Map(GROUP_ORDER.map((g) => [g, []]));
25557
- for (const c of cves) out.get(c.affected ? tierFor(c.row.s, c.row.x === 1, c.row.w === 1, knob) : "possible").push(c);
25558
- for (const list of out.values()) list.sort((a, b) => b.row.s - a.row.s || b.row.pub.localeCompare(a.row.pub) || a.row.id.localeCompare(b.row.id));
25559
- return out;
26002
+ Object.fromEntries(CHIPS.map((d) => [d.id, d]));
26003
+ /** FNV-1a 32-bit hash of the upper-cased CVE ID. */
26004
+ function fnv1a(input) {
26005
+ let h = 2166136261;
26006
+ for (let i = 0; i < input.length; i++) {
26007
+ h ^= input.charCodeAt(i);
26008
+ h = Math.imul(h, 16777619);
26009
+ }
26010
+ return h >>> 0;
26011
+ }
26012
+ /** Shard name for a CVE ID: two lowercase hex digits, e.g. "3f". */
26013
+ function shardOf(cveId) {
26014
+ return (fnv1a(cveId.trim().toUpperCase()) % 256).toString(16).padStart(2, "0");
26015
+ }
26016
+ var CVE_ID_RE = /^CVE-\d{4}-\d{4,}$/;
26017
+ /**
26018
+ * Slug of a vendor or product name: NFKD, accents dropped, lower case, every run of other
26019
+ * characters becomes one hyphen, no hyphen at either end, at most SLUG_MAX characters. "" when
26020
+ * nothing is left (a name with no ASCII letters or digits).
26021
+ */
26022
+ function slugify(name) {
26023
+ return name.normalize("NFKD").replace(/\p{M}+/gu, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64).replace(/-+$/, "");
26024
+ }
26025
+ // shared/watch.ts
26026
+ var normalizeName = (s) => s.trim().toLowerCase().replace(/\s+/g, " ");
26027
+ /** True when a normalized name in `list` equals the vendor or the product. */
26028
+ function matchesName(list, vendor, product) {
26029
+ if (list.length === 0) return false;
26030
+ return vendor !== "" && list.includes(normalizeName(vendor)) || product !== "" && list.includes(normalizeName(product));
25560
26031
  }
25561
26032
  /** Why a file could not be read. `detail` quotes the file (the JSON error), so it is rendered as file text. */
25562
26033
  var ParseError = class extends Error {
@@ -25609,8 +26080,41 @@ function lines(text, notes) {
25609
26080
  if (long) notes.push(`Skipped ${long === 1 ? "a line" : `${long} lines`} longer than 64 KB.`);
25610
26081
  return out;
25611
26082
  }
26083
+ /** The qualifiers of a package URL, by lowercased key; the last of a repeated key wins. */
26084
+ function purlQualifiers(query) {
26085
+ const out = /* @__PURE__ */ new Map();
26086
+ for (const pair of query.split("&")) {
26087
+ const eq = pair.indexOf("=");
26088
+ if (eq > 0) out.set(pair.slice(0, eq).toLowerCase(), decode(pair.slice(eq + 1)));
26089
+ }
26090
+ return out;
26091
+ }
26092
+ /**
26093
+ * A Debian, Ubuntu or Alpine package: the source package (Syft's `upstream=name` or
26094
+ * `upstream=name@version`, or Trivy's SrcName) and the version to compare (the source version when
26095
+ * given, else the installed one, with the `epoch` qualifier put back when the version lacks it).
26096
+ */
26097
+ function osComponent(eco, binary, version, q, src) {
26098
+ const upstream = q.get("upstream") ?? "";
26099
+ const at = upstream.indexOf("@");
26100
+ const sourceName = str(src?.name) ?? str(at >= 0 ? upstream.slice(0, at) : upstream);
26101
+ const sourceVersion = str(src?.version) ?? (at >= 0 ? str(upstream.slice(at + 1)) : null);
26102
+ const epoch = q.get("epoch");
26103
+ let v = sourceVersion ?? version;
26104
+ if (v && eco !== "Alpine" && epoch && /^[1-9]\d{0,8}$/.test(epoch) && !v.includes(":")) v = `${epoch}:${v}`;
26105
+ const name = sourceName ?? binary;
26106
+ const c = {
26107
+ eco,
26108
+ name,
26109
+ version: v,
26110
+ release: osRelease(eco, q.get("distro"))
26111
+ };
26112
+ if (name !== binary) c.binary = binary;
26113
+ if (v === null) c.noVersion = "no-version";
26114
+ return c;
26115
+ }
25612
26116
  /** A package URL (`pkg:type/namespace/name@version?qualifiers#subpath`) as a component; null when malformed. */
25613
- function purlComponent(raw) {
26117
+ function purlComponent(raw, src = null) {
25614
26118
  const full = raw.trim();
25615
26119
  if (full.length > MAX_PURL || full.slice(0, 4).toLowerCase() !== "pkg:") return null;
25616
26120
  let s = full.slice(4);
@@ -25618,6 +26122,7 @@ function purlComponent(raw) {
25618
26122
  const hash = s.indexOf("#");
25619
26123
  if (hash >= 0) s = s.slice(0, hash);
25620
26124
  const query = s.indexOf("?");
26125
+ const qualifiers = query >= 0 ? s.slice(query + 1) : "";
25621
26126
  if (query >= 0) s = s.slice(0, query);
25622
26127
  const slash = s.indexOf("/");
25623
26128
  if (slash <= 0) return null;
@@ -25635,6 +26140,8 @@ function purlComponent(raw) {
25635
26140
  if (parts.length === 0) return null;
25636
26141
  const name = parts[parts.length - 1];
25637
26142
  const ns = parts.slice(0, -1);
26143
+ const os = osEcosystemOfPurl(type, ns[0] ?? null);
26144
+ if (os) return osComponent(os, name, version, purlQualifiers(qualifiers), src);
25638
26145
  const eco = ecosystemOfPurlType(type);
25639
26146
  if (!eco) return {
25640
26147
  eco: null,
@@ -25660,11 +26167,11 @@ function purlComponent(raw) {
25660
26167
  };
25661
26168
  }
25662
26169
  /** An SBOM entry: its package URL when there is one, otherwise "not checked" under its own name. */
25663
- function sbomEntry(purl, name, version) {
26170
+ function sbomEntry(purl, name, version, src = null) {
25664
26171
  const ver = str(version);
25665
26172
  const p = str(purl);
25666
26173
  if (p) {
25667
- const c = purlComponent(p);
26174
+ const c = purlComponent(p, src);
25668
26175
  if (c) {
25669
26176
  if (c.version === null && c.eco && ver) return {
25670
26177
  eco: c.eco,
@@ -25687,7 +26194,24 @@ function sbomEntry(purl, name, version) {
25687
26194
  skip: "no-purl"
25688
26195
  };
25689
26196
  }
25690
- function cyclonedxJson(doc) {
26197
+ /** Trivy's source package properties on a CycloneDX component (SrcName, SrcVersion, SrcRelease, SrcEpoch). */
26198
+ function trivySource(props) {
26199
+ if (!Array.isArray(props)) return null;
26200
+ const get = (k) => {
26201
+ const p = props.find((x) => isObj(x) && x.name === `aquasecurity:trivy:${k}`);
26202
+ return isObj(p) ? str(p.value) : null;
26203
+ };
26204
+ const name = get("SrcName");
26205
+ const version = get("SrcVersion");
26206
+ if (!name && !version) return null;
26207
+ const release = get("SrcRelease");
26208
+ const epoch = get("SrcEpoch");
26209
+ return {
26210
+ name,
26211
+ version: version ? `${epoch && epoch !== "0" ? `${epoch}:` : ""}${version}${release ? `-${release}` : ""}` : null
26212
+ };
26213
+ }
26214
+ function cyclonedxJson(doc, os) {
25691
26215
  const out = [];
25692
26216
  const meta = isObj(doc.metadata) ? doc.metadata : null;
25693
26217
  const stack = [doc.components, meta && isObj(meta.component) ? [meta.component] : null];
@@ -25698,16 +26222,33 @@ function cyclonedxJson(doc) {
25698
26222
  if (!isObj(c)) continue;
25699
26223
  const group = str(c.group);
25700
26224
  const name = str(c.name);
25701
- out.push(sbomEntry(c.purl, group && name ? `${group}/${name}` : name, c.version));
26225
+ if (str(c.type) === "operating-system") {
26226
+ const eco = name ? osEcosystemOfName(name) : null;
26227
+ if (eco && os) os.push({
26228
+ eco,
26229
+ release: osRelease(eco, str(c.version))
26230
+ });
26231
+ if (c.components) stack.push(c.components);
26232
+ continue;
26233
+ }
26234
+ out.push(sbomEntry(c.purl, group && name ? `${group}/${name}` : name, c.version, trivySource(c.properties)));
25702
26235
  if (c.components) stack.push(c.components);
25703
26236
  }
25704
26237
  }
25705
26238
  return out;
25706
26239
  }
25707
- function spdxJson(doc) {
26240
+ function spdxJson(doc, os) {
25708
26241
  const out = [];
25709
26242
  if (Array.isArray(doc.packages)) for (const p of doc.packages) {
25710
26243
  if (!isObj(p)) continue;
26244
+ if (str(p.primaryPackagePurpose) === "OPERATING-SYSTEM") {
26245
+ const eco = osEcosystemOfName(str(p.name) ?? "");
26246
+ if (eco && os) os.push({
26247
+ eco,
26248
+ release: osRelease(eco, str(p.versionInfo))
26249
+ });
26250
+ continue;
26251
+ }
25711
26252
  const ref = (Array.isArray(p.externalRefs) ? p.externalRefs : []).find((r) => isObj(r) && typeof r.referenceType === "string" && r.referenceType.toLowerCase() === "purl");
25712
26253
  out.push(sbomEntry(isObj(ref) ? ref.referenceLocator : null, p.name, p.versionInfo));
25713
26254
  }
@@ -26497,6 +27038,22 @@ function parseJson(text) {
26497
27038
  * ParseError when the format cannot be told or the file holds no packages. Names longer than
26498
27039
  * MAX_NAME are dropped (with a note); everything else is kept, including duplicates.
26499
27040
  */
27041
+ /**
27042
+ * Distro packages take their release from the package URL's `distro` qualifier, else from the
27043
+ * operating system the SBOM describes; one with neither is "not checked", never matched against a
27044
+ * guessed release.
27045
+ */
27046
+ function osReleases(components, os) {
27047
+ for (const c of components) {
27048
+ if (!c.eco || !isOsEcosystem(c.eco) || c.skip || c.release) continue;
27049
+ const found = os.find((o) => o.eco === c.eco && o.release)?.release ?? null;
27050
+ if (found) c.release = found;
27051
+ else {
27052
+ c.skip = "os-release";
27053
+ delete c.noVersion;
27054
+ }
27055
+ }
27056
+ }
26500
27057
  function parse(input, filename = "", forced = null) {
26501
27058
  const text = input.charCodeAt(0) === 65279 ? input.slice(1) : input;
26502
27059
  if (text.trim() === "") throw new ParseError("empty");
@@ -26516,11 +27073,13 @@ function parse(input, filename = "", forced = null) {
26516
27073
  if (format === null) throw new ParseError("unknown");
26517
27074
  const notes = [];
26518
27075
  let components;
27076
+ const sbomOs = [];
26519
27077
  const fromJson = JSON_PARSERS.get(format);
26520
27078
  if (fromJson) {
26521
27079
  doc ??= parseJson(text);
26522
- components = fromJson(isObj(doc) ? doc : {});
27080
+ components = fromJson(isObj(doc) ? doc : {}, sbomOs);
26523
27081
  } else components = (TEXT_PARSERS.get(format) ?? gradleLock)(text, notes);
27082
+ osReleases(components, sbomOs);
26524
27083
  const kept = components.filter((c) => c.name !== "" && c.name.length <= 512);
26525
27084
  if (kept.length < components.length) {
26526
27085
  const n = components.length - kept.length;
@@ -26535,7 +27094,7 @@ function parse(input, filename = "", forced = null) {
26535
27094
  }
26536
27095
  // cli/src/check.ts
26537
27096
  /**
26538
- * Checks files against packages.json with the Check Deps page's own parser and matcher, and turns
27097
+ * Checks files against packages.json with the Check page's own parser and matcher, and turns
26539
27098
  * the results into findings: one per (CVE, package, file), with the line the package is on.
26540
27099
  */
26541
27100
  /** The Check page reads files up to this size. */
@@ -26598,51 +27157,71 @@ function lowestFix(pkg) {
26598
27157
  }
26599
27158
  /** Group order for findings: Exploited first, possibly affected last; within a group by score, then CVE. */
26600
27159
  var compareFindings = (a, b) => RANK[b.group] - RANK[a.group] || b.row.s - a.row.s || a.row.id.localeCompare(b.row.id) || a.file.localeCompare(b.file) || a.pkg.name.localeCompare(b.pkg.name);
26601
- /** Check `files` (relative to `cwd`) at evidence bar `knob`. Reads files; no network. */
26602
- function checkFiles(files, cwd, index, knob = 50, older = {
26603
- olderIds: /* @__PURE__ */ new Set(),
26604
- olderError: null
26605
- }) {
26606
- const reports = [];
26607
- const findings = [];
26608
- const notes = [];
26609
- let packages = 0;
26610
- let checked = 0;
26611
- for (const path of files) {
27160
+ /** Read and parse `files` (relative to `cwd`). No network: the distro releases they name decide what to load next. */
27161
+ function readFiles(files, cwd) {
27162
+ return files.map((path) => {
26612
27163
  const abs = resolve(cwd, path);
26613
27164
  let text;
26614
27165
  try {
26615
- if (statSync(abs).size > 52428800) {
26616
- reports.push({
26617
- path,
26618
- format: null,
26619
- error: `larger than ${MAX_FILE_BYTES / 1024 / 1024} MB`,
26620
- result: null
26621
- });
26622
- continue;
26623
- }
27166
+ if (statSync(abs).size > 52428800) return {
27167
+ path,
27168
+ text: "",
27169
+ parsed: null,
27170
+ error: `larger than ${MAX_FILE_BYTES / 1024 / 1024} MB`
27171
+ };
26624
27172
  text = readFileSync(abs, "utf8");
26625
27173
  } catch (e) {
26626
- reports.push({
27174
+ return {
26627
27175
  path,
26628
- format: null,
26629
- error: `could not be read: ${e.message}`,
26630
- result: null
26631
- });
26632
- continue;
27176
+ text: "",
27177
+ parsed: null,
27178
+ error: `could not be read: ${e.message}`
27179
+ };
26633
27180
  }
26634
- let result;
26635
27181
  try {
26636
- result = checkComponents(parse(text, path), index);
27182
+ return {
27183
+ path,
27184
+ text,
27185
+ parsed: parse(text, path),
27186
+ error: null
27187
+ };
26637
27188
  } catch (e) {
27189
+ return {
27190
+ path,
27191
+ text,
27192
+ parsed: null,
27193
+ error: e instanceof ParseError ? e.message : `could not be read: ${e.message}`
27194
+ };
27195
+ }
27196
+ });
27197
+ }
27198
+ /**
27199
+ * Check `files` (paths relative to `cwd`, or files already read) at evidence bar `knob`. No network:
27200
+ * `os` says which distro releases `index` holds (loadOs in data.ts); without it distro packages are
27201
+ * not checked.
27202
+ */
27203
+ function checkFiles(files, cwd, index, knob = 50, older = {
27204
+ olderIds: /* @__PURE__ */ new Set(),
27205
+ olderError: null
27206
+ }, os = null) {
27207
+ const reports = [];
27208
+ const findings = [];
27209
+ const notes = [];
27210
+ let packages = 0;
27211
+ let checked = 0;
27212
+ const read = files.length > 0 && typeof files[0] === "string" ? readFiles(files, cwd) : files;
27213
+ for (const f of read) {
27214
+ const { path, text } = f;
27215
+ if (!f.parsed) {
26638
27216
  reports.push({
26639
27217
  path,
26640
27218
  format: null,
26641
- error: e instanceof ParseError ? e.message : `could not be read: ${e.message}`,
27219
+ error: f.error,
26642
27220
  result: null
26643
27221
  });
26644
27222
  continue;
26645
27223
  }
27224
+ const result = checkComponents(f.parsed, index, os);
26646
27225
  reports.push({
26647
27226
  path,
26648
27227
  format: result.format,
@@ -26658,12 +27237,13 @@ function checkFiles(files, cwd, index, knob = 50, older = {
26658
27237
  const line = lineFinder(text);
26659
27238
  for (const [group, hits] of groupByTier(result.cves, knob)) for (const hit of hits) for (const pkg of hit.packages) {
26660
27239
  const g = group !== "possible" && pkg.unchecked !== null ? "possible" : group;
27240
+ const named = pkg.binary ? pkg.binary.split(", ")[0] : pkg.name;
26661
27241
  findings.push({
26662
27242
  group: g,
26663
27243
  row: hit.row,
26664
27244
  pkg,
26665
27245
  file: path,
26666
- line: line(pkg.name, pkg.version),
27246
+ line: line(named, pkg.version),
26667
27247
  fixedIn: lowestFix(pkg),
26668
27248
  tracked: !older.olderIds.has(hit.row.id)
26669
27249
  });
@@ -26706,16 +27286,13 @@ function countByGroup(findings) {
26706
27286
  possible: out.possible.size
26707
27287
  };
26708
27288
  }
26709
- // cli/src/discover.ts
27289
+ // site/src/check/files.ts
26710
27290
  /**
26711
- * Finds the lockfiles and SBOMs to check under the paths given on the command line.
26712
- *
26713
- * A file named on the command line is always read (its format is told by its content if its name
26714
- * says nothing). A directory is walked for the file names the Check Deps page knows, plus common
26715
- * SBOM names, skipping dependency, build and VCS directories. The walk never follows symbolic
26716
- * links, so a link cannot lead it out of the repository or round in a loop.
27291
+ * Which files a dependency check reads, shared by the browser (a public GitHub repo, Check page) and
27292
+ * the command line (cli/src/discover.ts): the lockfile names the parser knows, common SBOM names,
27293
+ * and the folders never searched. Pure: no Node or DOM APIs.
26717
27294
  */
26718
- /** Directories never walked: installed dependencies, build output, virtualenvs, VCS metadata. */
27295
+ /** Directories never walked: installed dependencies, build output, virtualenvs, VCS metadata, test data. */
26719
27296
  var SKIP_DIRS = /* @__PURE__ */ new Set([
26720
27297
  ".git",
26721
27298
  ".hg",
@@ -26739,7 +27316,10 @@ var SKIP_DIRS = /* @__PURE__ */ new Set([
26739
27316
  "coverage",
26740
27317
  ".next",
26741
27318
  ".nuxt",
26742
- ".cache"
27319
+ ".cache",
27320
+ "testdata",
27321
+ "fixtures",
27322
+ "__fixtures__"
26743
27323
  ]);
26744
27324
  /** CycloneDX and SPDX files as tools usually name them. */
26745
27325
  var SBOM_NAME = /^(?:bom\.(?:json|xml)|sbom(?:[\w.-]{0,64})?\.json|[\w.-]{1,128}\.(?:cdx\.(?:json|xml)|spdx(?:\.json)?))$/i;
@@ -27356,10 +27936,39 @@ async function checkDependencies(call, a, now, root = process.cwd()) {
27356
27936
  }
27357
27937
  const trackedIds = new Set(rowsFromTable(tracked.cves).map((r) => r.id));
27358
27938
  const olderIds = new Set(older ? rowsFromTable(older.cves).map((r) => r.id).filter((id) => !trackedIds.has(id)) : []);
27359
- const report = checkFiles(found.files, root, mergePackageFiles(tracked, older), knob, {
27939
+ const read = readFiles(found.files, root);
27940
+ const needs = osNeeds(read.flatMap((f) => f.parsed?.components ?? []));
27941
+ let index = mergePackageFiles(tracked, older);
27942
+ let os = null;
27943
+ if (needs.length > 0) {
27944
+ const osIndex = await call.file("os/index.json", parse$1.osIndex).catch((e) => {
27945
+ if (e instanceof DataError) return null;
27946
+ throw e;
27947
+ });
27948
+ const plan = osPlan(osIndex, needs);
27949
+ const cover = {
27950
+ loaded: /* @__PURE__ */ new Set(),
27951
+ notFollowed: plan.notFollowed,
27952
+ failed: new Set(plan.failed)
27953
+ };
27954
+ os = cover;
27955
+ const files = [];
27956
+ for (const [tag, rel] of plan.files) try {
27957
+ files.push(await call.file(rel, parse$1.packages));
27958
+ cover.loaded.add(tag);
27959
+ } catch (e) {
27960
+ if (!(e instanceof DataError)) throw e;
27961
+ cover.failed.add(tag);
27962
+ }
27963
+ for (const n of needs) if (!osIndex) cover.failed.add(osTag(n.eco, n.release));
27964
+ const merged = mergeOsFiles(index, files);
27965
+ index = merged.file;
27966
+ for (const id of merged.noPage) olderIds.add(id);
27967
+ }
27968
+ const report = checkFiles(read, root, index, knob, {
27360
27969
  olderIds,
27361
27970
  olderError: olderMissing
27362
- });
27971
+ }, os);
27363
27972
  const counts = countByGroup(report.findings);
27364
27973
  const items = report.findings.filter((f) => a.include_quiet || f.group !== "quiet").sort((x, y) => groupRank[x.group] - groupRank[y.group]).map((f) => ({
27365
27974
  cve: f.row.id,
@@ -27383,7 +27992,7 @@ async function checkDependencies(call, a, now, root = process.cwd()) {
27383
27992
  title: cut(oneLine(f.row.t), TITLE_MAX)
27384
27993
  }));
27385
27994
  const data = await dataBlock(call, now);
27386
- const scope = `${olderMissing === null ? `Every CVE that one of ${report.coverage.advisories.toLocaleString("en-US")} OSV.dev advisories ties to a package version, in npm, PyPI, Maven, Go, crates.io, RubyGems, Packagist and NuGet` : "Tracked CVEs only"}. Not checked: advisories without a CVE ID (malware reports among them), other ecosystems (deb, rpm, apk, containers), and bugs no advisory names yet. Tracked CVEs (tracked: true) have a page and get_verdict knows them; older ones link to cve.org.`;
27995
+ const scope = `${olderMissing === null ? `Every CVE that one of ${report.coverage.advisories.toLocaleString("en-US")} OSV.dev advisories ties to a package version, in npm, PyPI, Maven, Go, crates.io, RubyGems, Packagist and NuGet, and Debian, Ubuntu and Alpine packages against their distro's security tracker` : "Tracked CVEs only"}. Not checked: advisories without a CVE ID (malware reports among them), other ecosystems (rpm and other distros), a distro release its tracker no longer follows, and bugs no advisory names yet. Tracked CVEs (tracked: true) have a page and get_verdict knows them; older ones link to cve.org.`;
27387
27996
  const build = (n) => ({
27388
27997
  data,
27389
27998
  knob,