oculon 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (255) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +344 -2
  3. package/dist/agent.d.ts +47 -0
  4. package/dist/agent.js +104 -0
  5. package/dist/cases.d.ts +68 -0
  6. package/dist/cases.js +158 -0
  7. package/dist/cli/main.d.ts +12 -0
  8. package/dist/cli/main.js +1999 -0
  9. package/dist/cli.d.ts +2 -0
  10. package/dist/cli.js +15 -0
  11. package/dist/core/context.d.ts +19 -0
  12. package/dist/core/context.js +19 -0
  13. package/dist/core/features.d.ts +22 -0
  14. package/dist/core/features.js +28 -0
  15. package/dist/core/graph.d.ts +38 -0
  16. package/dist/core/graph.js +81 -0
  17. package/dist/core/http.d.ts +42 -0
  18. package/dist/core/http.js +266 -0
  19. package/dist/core/keys.d.ts +8 -0
  20. package/dist/core/keys.js +22 -0
  21. package/dist/core/llm.d.ts +93 -0
  22. package/dist/core/llm.js +180 -0
  23. package/dist/core/merkle.d.ts +15 -0
  24. package/dist/core/merkle.js +46 -0
  25. package/dist/core/paths.d.ts +2 -0
  26. package/dist/core/paths.js +6 -0
  27. package/dist/core/png.d.ts +17 -0
  28. package/dist/core/png.js +101 -0
  29. package/dist/core/quota.d.ts +15 -0
  30. package/dist/core/quota.js +90 -0
  31. package/dist/core/stats.d.ts +24 -0
  32. package/dist/core/stats.js +67 -0
  33. package/dist/core/store.d.ts +20 -0
  34. package/dist/core/store.js +213 -0
  35. package/dist/core/text.d.ts +9 -0
  36. package/dist/core/text.js +30 -0
  37. package/dist/core/types.d.ts +38 -0
  38. package/dist/core/types.js +1 -0
  39. package/dist/index.d.ts +342 -0
  40. package/dist/index.js +495 -0
  41. package/dist/live.d.ts +53 -0
  42. package/dist/live.js +236 -0
  43. package/dist/mcp.d.ts +43 -0
  44. package/dist/mcp.js +651 -0
  45. package/dist/modules/airport.d.ts +60 -0
  46. package/dist/modules/airport.js +111 -0
  47. package/dist/modules/audit.d.ts +73 -0
  48. package/dist/modules/audit.js +211 -0
  49. package/dist/modules/bgp.d.ts +147 -0
  50. package/dist/modules/bgp.js +206 -0
  51. package/dist/modules/blackout.d.ts +41 -0
  52. package/dist/modules/blackout.js +98 -0
  53. package/dist/modules/brief.d.ts +26 -0
  54. package/dist/modules/brief.js +99 -0
  55. package/dist/modules/calendar.d.ts +27 -0
  56. package/dist/modules/calendar.js +145 -0
  57. package/dist/modules/calibrate.d.ts +46 -0
  58. package/dist/modules/calibrate.js +92 -0
  59. package/dist/modules/cloud.d.ts +32 -0
  60. package/dist/modules/cloud.js +94 -0
  61. package/dist/modules/condor.d.ts +66 -0
  62. package/dist/modules/condor.js +214 -0
  63. package/dist/modules/connect.d.ts +47 -0
  64. package/dist/modules/connect.js +114 -0
  65. package/dist/modules/contradictions.d.ts +27 -0
  66. package/dist/modules/contradictions.js +76 -0
  67. package/dist/modules/country.d.ts +82 -0
  68. package/dist/modules/country.js +136 -0
  69. package/dist/modules/cricket.d.ts +34 -0
  70. package/dist/modules/cricket.js +166 -0
  71. package/dist/modules/darkships.d.ts +219 -0
  72. package/dist/modules/darkships.js +400 -0
  73. package/dist/modules/defi.d.ts +237 -0
  74. package/dist/modules/defi.js +512 -0
  75. package/dist/modules/emailsec.d.ts +47 -0
  76. package/dist/modules/emailsec.js +146 -0
  77. package/dist/modules/exposure.d.ts +43 -0
  78. package/dist/modules/exposure.js +89 -0
  79. package/dist/modules/factcheck.d.ts +39 -0
  80. package/dist/modules/factcheck.js +127 -0
  81. package/dist/modules/falcon.d.ts +58 -0
  82. package/dist/modules/falcon.js +219 -0
  83. package/dist/modules/feedback.d.ts +24 -0
  84. package/dist/modules/feedback.js +37 -0
  85. package/dist/modules/fence.d.ts +52 -0
  86. package/dist/modules/fence.js +128 -0
  87. package/dist/modules/ferret.d.ts +47 -0
  88. package/dist/modules/ferret.js +220 -0
  89. package/dist/modules/filings.d.ts +86 -0
  90. package/dist/modules/filings.js +166 -0
  91. package/dist/modules/fires.d.ts +56 -0
  92. package/dist/modules/fires.js +150 -0
  93. package/dist/modules/hazards.d.ts +37 -0
  94. package/dist/modules/hazards.js +83 -0
  95. package/dist/modules/health.d.ts +24 -0
  96. package/dist/modules/health.js +82 -0
  97. package/dist/modules/heron.d.ts +68 -0
  98. package/dist/modules/heron.js +184 -0
  99. package/dist/modules/hound.d.ts +100 -0
  100. package/dist/modules/hound.js +301 -0
  101. package/dist/modules/impact.d.ts +39 -0
  102. package/dist/modules/impact.js +63 -0
  103. package/dist/modules/launches.d.ts +24 -0
  104. package/dist/modules/launches.js +61 -0
  105. package/dist/modules/listen.d.ts +48 -0
  106. package/dist/modules/listen.js +125 -0
  107. package/dist/modules/lynx.d.ts +43 -0
  108. package/dist/modules/lynx.js +127 -0
  109. package/dist/modules/magpie.d.ts +70 -0
  110. package/dist/modules/magpie.js +174 -0
  111. package/dist/modules/meerkat.d.ts +42 -0
  112. package/dist/modules/meerkat.js +293 -0
  113. package/dist/modules/monitor.d.ts +27 -0
  114. package/dist/modules/monitor.js +105 -0
  115. package/dist/modules/narratives.d.ts +33 -0
  116. package/dist/modules/narratives.js +136 -0
  117. package/dist/modules/owl.d.ts +71 -0
  118. package/dist/modules/owl.js +290 -0
  119. package/dist/modules/papers.d.ts +46 -0
  120. package/dist/modules/papers.js +135 -0
  121. package/dist/modules/personal.d.ts +54 -0
  122. package/dist/modules/personal.js +153 -0
  123. package/dist/modules/pulse.d.ts +19 -0
  124. package/dist/modules/pulse.js +59 -0
  125. package/dist/modules/raven.d.ts +80 -0
  126. package/dist/modules/raven.js +147 -0
  127. package/dist/modules/recall.d.ts +44 -0
  128. package/dist/modules/recall.js +123 -0
  129. package/dist/modules/regs.d.ts +88 -0
  130. package/dist/modules/regs.js +142 -0
  131. package/dist/modules/rewind.d.ts +22 -0
  132. package/dist/modules/rewind.js +68 -0
  133. package/dist/modules/sanctions.d.ts +62 -0
  134. package/dist/modules/sanctions.js +173 -0
  135. package/dist/modules/scam.d.ts +43 -0
  136. package/dist/modules/scam.js +111 -0
  137. package/dist/modules/scoop.d.ts +31 -0
  138. package/dist/modules/scoop.js +74 -0
  139. package/dist/modules/ships.d.ts +33 -0
  140. package/dist/modules/ships.js +113 -0
  141. package/dist/modules/sky.d.ts +47 -0
  142. package/dist/modules/sky.js +183 -0
  143. package/dist/modules/squawk.d.ts +46 -0
  144. package/dist/modules/squawk.js +106 -0
  145. package/dist/modules/tortoise.d.ts +40 -0
  146. package/dist/modules/tortoise.js +104 -0
  147. package/dist/modules/travel.d.ts +94 -0
  148. package/dist/modules/travel.js +241 -0
  149. package/dist/modules/urlcheck.d.ts +63 -0
  150. package/dist/modules/urlcheck.js +223 -0
  151. package/dist/modules/vulns.d.ts +142 -0
  152. package/dist/modules/vulns.js +276 -0
  153. package/dist/plugins.d.ts +41 -0
  154. package/dist/plugins.js +70 -0
  155. package/dist/report.d.ts +12 -0
  156. package/dist/report.js +90 -0
  157. package/dist/scheduler.d.ts +22 -0
  158. package/dist/scheduler.js +139 -0
  159. package/dist/sources/aircraft.d.ts +76 -0
  160. package/dist/sources/aircraft.js +107 -0
  161. package/dist/sources/airports.d.ts +28 -0
  162. package/dist/sources/airports.js +100 -0
  163. package/dist/sources/ais.d.ts +32 -0
  164. package/dist/sources/ais.js +111 -0
  165. package/dist/sources/apify.d.ts +28 -0
  166. package/dist/sources/apify.js +80 -0
  167. package/dist/sources/arxiv.d.ts +13 -0
  168. package/dist/sources/arxiv.js +27 -0
  169. package/dist/sources/certs.d.ts +12 -0
  170. package/dist/sources/certs.js +23 -0
  171. package/dist/sources/corp.d.ts +46 -0
  172. package/dist/sources/corp.js +60 -0
  173. package/dist/sources/earth.d.ts +39 -0
  174. package/dist/sources/earth.js +76 -0
  175. package/dist/sources/fda.d.ts +77 -0
  176. package/dist/sources/fda.js +121 -0
  177. package/dist/sources/finance.d.ts +181 -0
  178. package/dist/sources/finance.js +270 -0
  179. package/dist/sources/gdelt.d.ts +19 -0
  180. package/dist/sources/gdelt.js +33 -0
  181. package/dist/sources/github.d.ts +17 -0
  182. package/dist/sources/github.js +33 -0
  183. package/dist/sources/hackernews.d.ts +20 -0
  184. package/dist/sources/hackernews.js +37 -0
  185. package/dist/sources/labels.d.ts +21 -0
  186. package/dist/sources/labels.js +87 -0
  187. package/dist/sources/launch.d.ts +16 -0
  188. package/dist/sources/launch.js +41 -0
  189. package/dist/sources/ofac.d.ts +29 -0
  190. package/dist/sources/ofac.js +86 -0
  191. package/dist/sources/onchain.d.ts +77 -0
  192. package/dist/sources/onchain.js +189 -0
  193. package/dist/sources/opentimestamps.d.ts +44 -0
  194. package/dist/sources/opentimestamps.js +131 -0
  195. package/dist/sources/polymarket.d.ts +36 -0
  196. package/dist/sources/polymarket.js +70 -0
  197. package/dist/sources/predict.d.ts +18 -0
  198. package/dist/sources/predict.js +59 -0
  199. package/dist/sources/press.d.ts +30 -0
  200. package/dist/sources/press.js +111 -0
  201. package/dist/sources/resend.d.ts +14 -0
  202. package/dist/sources/resend.js +29 -0
  203. package/dist/sources/robinhood.d.ts +109 -0
  204. package/dist/sources/robinhood.js +129 -0
  205. package/dist/sources/sec.d.ts +67 -0
  206. package/dist/sources/sec.js +129 -0
  207. package/dist/sources/sentinel.d.ts +13 -0
  208. package/dist/sources/sentinel.js +63 -0
  209. package/dist/sources/signatures.d.ts +14 -0
  210. package/dist/sources/signatures.js +103 -0
  211. package/dist/sources/social.d.ts +22 -0
  212. package/dist/sources/social.js +56 -0
  213. package/dist/sources/space.d.ts +160 -0
  214. package/dist/sources/space.js +230 -0
  215. package/dist/sources/usgs.d.ts +17 -0
  216. package/dist/sources/usgs.js +24 -0
  217. package/dist/sources/wayback.d.ts +10 -0
  218. package/dist/sources/wayback.js +28 -0
  219. package/dist/sources/websec.d.ts +19 -0
  220. package/dist/sources/websec.js +40 -0
  221. package/dist/sources/wikidata.d.ts +11 -0
  222. package/dist/sources/wikidata.js +30 -0
  223. package/dist/sources/wikimedia.d.ts +28 -0
  224. package/dist/sources/wikimedia.js +52 -0
  225. package/dist/telegram.d.ts +104 -0
  226. package/dist/telegram.js +927 -0
  227. package/dist/web/assets/favicon-32.png +0 -0
  228. package/dist/web/assets/fx.js +178 -0
  229. package/dist/web/assets/icon-192.png +0 -0
  230. package/dist/web/assets/icon-512.png +0 -0
  231. package/dist/web/assets/icon-maskable-512.png +0 -0
  232. package/dist/web/assets/night-americas.jpg +0 -0
  233. package/dist/web/assets/night-emea.jpg +0 -0
  234. package/dist/web/assets/og.png +0 -0
  235. package/dist/web/assets/redsea-bm.jpg +0 -0
  236. package/dist/web/docs.html +263 -0
  237. package/dist/web/index.html +1828 -0
  238. package/dist/web/insights.d.ts +100 -0
  239. package/dist/web/insights.js +134 -0
  240. package/dist/web/landing.html +1143 -0
  241. package/dist/web/legal.html +176 -0
  242. package/dist/web/manifest.webmanifest +20 -0
  243. package/dist/web/mcp.html +104 -0
  244. package/dist/web/mcphttp.d.ts +10 -0
  245. package/dist/web/mcphttp.js +67 -0
  246. package/dist/web/openapi.d.ts +1 -0
  247. package/dist/web/openapi.js +51 -0
  248. package/dist/web/public.d.ts +45 -0
  249. package/dist/web/public.js +135 -0
  250. package/dist/web/server.d.ts +69 -0
  251. package/dist/web/server.js +750 -0
  252. package/dist/web/share.d.ts +35 -0
  253. package/dist/web/share.js +132 -0
  254. package/dist/web/sw.js +28 -0
  255. package/package.json +60 -4
@@ -0,0 +1,223 @@
1
+ import { key } from '../core/keys.js';
2
+ import { clamp } from '../core/stats.js';
3
+ import { signalId } from '../core/text.js';
4
+ import { safeBrowsing } from '../sources/websec.js';
5
+ const DAY = 86_400_000;
6
+ const TWO_LEVEL = /^(co|com|net|org|gov|ac|edu|or|ne|go|mil|nic)$/;
7
+ const RISKY_TLDS = new Set(['zip', 'mov', 'xyz', 'top', 'click', 'country', 'gq', 'tk', 'ml', 'cf', 'ga', 'work', 'support', 'rest', 'fit', 'loan', 'cam', 'quest', 'cfd', 'sbs', 'icu', 'buzz', 'monster']);
8
+ const BRANDS = ['paypal', 'apple', 'icloud', 'microsoft', 'office365', 'outlook', 'google', 'gmail', 'amazon', 'netflix', 'facebook', 'instagram', 'whatsapp', 'metamask', 'binance', 'coinbase', 'kraken', 'ledger', 'trezor', 'wellsfargo', 'chase', 'bankofamerica', 'hsbc', 'dhl', 'fedex', 'usps', 'steam', 'discord', 'telegram', 'docusign', 'dropbox', 'adobe', 'linkedin', 'twitter', 'opensea', 'uniswap'];
9
+ /** Normalizes input ("example.com/x", "https://...") to a URL. */
10
+ export function normalizeUrl(input) {
11
+ const s = input.trim();
12
+ if (!s)
13
+ throw new Error('missing URL');
14
+ try {
15
+ return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(s) ? s : `http://${s}`);
16
+ }
17
+ catch {
18
+ throw new Error(`not a URL: ${input}`);
19
+ }
20
+ }
21
+ /** Registrable domain by a simple rule: last two labels, or three under common second levels (co.uk, com.au). */
22
+ export function apexOf(host) {
23
+ const parts = host.toLowerCase().replace(/\.$/, '').split('.');
24
+ if (parts.length <= 2 || /^\d+$/.test(parts.at(-1)))
25
+ return parts.join('.');
26
+ const n = parts.at(-1).length === 2 && TWO_LEVEL.test(parts.at(-2)) ? 3 : 2;
27
+ return parts.slice(-n).join('.');
28
+ }
29
+ /** Warning signs visible in the URL itself. */
30
+ export function urlHeuristics(u) {
31
+ const out = [];
32
+ const host = u.hostname.toLowerCase();
33
+ const apex = apexOf(host);
34
+ const tld = host.split('.').at(-1) ?? '';
35
+ if (/^\d{1,3}(\.\d{1,3}){3}$/.test(host) || host.includes(':'))
36
+ out.push('the host is a raw IP address');
37
+ if (host.split('.').some((l) => l.startsWith('xn--')))
38
+ out.push('the host uses punycode (look-alike characters)');
39
+ if (RISKY_TLDS.has(tld))
40
+ out.push(`.${tld} is a top-level domain often used for abuse`);
41
+ const apexName = apex.split('.')[0] ?? '';
42
+ const brand = BRANDS.find((b) => host.replace(/[-.]/g, '').includes(b) && apexName !== b);
43
+ if (brand)
44
+ out.push(`mentions "${brand}" but is not on ${brand}'s own domain`);
45
+ if (u.username || u.href.includes('@'))
46
+ out.push('contains "@", which can hide the real destination');
47
+ if (host.split('.').length >= 5)
48
+ out.push('unusually deep subdomain chain');
49
+ if (u.href.length > 200)
50
+ out.push('very long URL');
51
+ if ((host.match(/-/g) ?? []).length >= 3)
52
+ out.push('many hyphens in the host name');
53
+ return out;
54
+ }
55
+ /** POST a form and cache the JSON answer (URLhaus takes form bodies). */
56
+ async function postForm(ctx, url, form, headers, source, ttlSec) {
57
+ const body = new URLSearchParams(form).toString();
58
+ const cacheKey = `post:${url}:${body}`;
59
+ const cached = ctx.store.cacheGet(cacheKey);
60
+ if (cached && Date.now() - cached.fetchedAt < ttlSec * 1000)
61
+ return { data: JSON.parse(cached.body), prov: { source, url, status: 'CACHED', fetchedAt: new Date(cached.fetchedAt).toISOString() } };
62
+ const r = await ctx.http.postBytes(url, new TextEncoder().encode(body), { source, headers: { 'content-type': 'application/x-www-form-urlencoded', ...headers }, timeoutMs: 30_000 });
63
+ if (!r.data)
64
+ return { data: null, prov: r.prov };
65
+ try {
66
+ const text = r.data.toString('utf8');
67
+ const data = JSON.parse(text);
68
+ ctx.store.cachePut(cacheKey, text);
69
+ return { data, prov: r.prov };
70
+ }
71
+ catch {
72
+ return { data: null, prov: { ...r.prov, status: 'ERROR', note: 'invalid JSON' } };
73
+ }
74
+ }
75
+ const URLHAUS = 'https://urlhaus-api.abuse.ch/v1';
76
+ async function urlhaus(ctx, url, host) {
77
+ const k = key('ABUSECH_AUTH_KEY');
78
+ if (!k)
79
+ return { data: null, prov: [{ source: 'urlhaus', url: URLHAUS, status: 'UNAVAILABLE', fetchedAt: new Date().toISOString(), note: 'set ABUSECH_AUTH_KEY (free at auth.abuse.ch)' }] };
80
+ const h = { 'Auth-Key': k };
81
+ const [u, hs] = await Promise.all([
82
+ postForm(ctx, `${URLHAUS}/url/`, { url }, h, 'urlhaus', 3600),
83
+ postForm(ctx, `${URLHAUS}/host/`, { host }, h, 'urlhaus', 3600),
84
+ ]);
85
+ const urlHit = u.data?.query_status === 'ok' ? { status: u.data.url_status ?? 'unknown', threat: u.data.threat ?? null, tags: u.data.tags ?? [], dateAdded: u.data.date_added ?? null, reference: u.data.urlhaus_reference ?? null } : null;
86
+ const hostHit = hs.data?.query_status === 'ok' ? { urls: Number(hs.data.url_count ?? hs.data.urls?.length ?? 0), online: (hs.data.urls ?? []).filter((x) => x.url_status === 'online').length, firstSeen: hs.data.firstseen ?? null } : null;
87
+ return { data: u.data || hs.data ? { url: urlHit, host: hostHit } : null, prov: [u.prov, hs.prov] };
88
+ }
89
+ async function rdap(ctx, domain) {
90
+ const r = await ctx.http.get(`https://rdap.org/domain/${encodeURIComponent(domain)}`, {
91
+ source: 'rdap',
92
+ ttlSec: 7 * 86_400,
93
+ timeoutMs: 20_000,
94
+ keep: (d) => ({ events: d.events ?? [], entities: (d.entities ?? []).filter((e) => e.roles?.includes('registrar')).map((e) => ({ roles: e.roles, vcardArray: e.vcardArray })) }),
95
+ });
96
+ if (!r.data)
97
+ return { data: null, prov: r.prov };
98
+ const ev = (a) => r.data.events?.find((e) => e.eventAction === a)?.eventDate ?? null;
99
+ const registered = ev('registration');
100
+ const card = r.data.entities?.[0]?.vcardArray?.[1] ?? [];
101
+ const registrar = String(card.find((f) => f[0] === 'fn')?.[3] ?? '') || null;
102
+ return { data: { registered, ageDays: registered ? Math.floor((ctx.now().getTime() - Date.parse(registered)) / DAY) : null, expires: ev('expiration'), registrar }, prov: r.prov };
103
+ }
104
+ async function scanHistory(ctx, host) {
105
+ const k = key('URLSCAN_API_KEY');
106
+ const r = await ctx.http.get(`https://urlscan.io/api/v1/search/?q=${encodeURIComponent(`page.domain:"${host}"`)}&size=50`, {
107
+ source: 'urlscan',
108
+ ttlSec: 3 * 3600,
109
+ ...(k ? { headers: { 'api-key': k } } : {}),
110
+ keep: (d) => (d.results ?? []).map((x) => ({ task: { time: x.task?.time, url: x.task?.url, tags: x.task?.tags }, page: { title: x.page?.title, ip: x.page?.ip, country: x.page?.country, server: x.page?.server, url: x.page?.url }, _id: x._id })),
111
+ });
112
+ if (!r.data)
113
+ return { data: null, prov: r.prov };
114
+ const hits = r.data;
115
+ const times = hits.map((h) => h.task?.time ?? '').filter(Boolean).sort();
116
+ const uniq = (xs, n = 5) => [...new Set(xs.filter((x) => Boolean(x)))].slice(0, n);
117
+ return {
118
+ data: {
119
+ count: hits.length,
120
+ firstSeen: times[0] ?? null,
121
+ lastSeen: times.at(-1) ?? null,
122
+ titles: uniq(hits.map((h) => h.page?.title?.trim()), 3),
123
+ tags: uniq(hits.flatMap((h) => h.task?.tags ?? []), 8),
124
+ ips: uniq(hits.map((h) => h.page?.ip)),
125
+ countries: uniq(hits.map((h) => h.page?.country)),
126
+ servers: uniq(hits.map((h) => h.page?.server)),
127
+ latest: hits[0]?._id ? `https://urlscan.io/result/${hits[0]._id}/` : null,
128
+ },
129
+ prov: r.prov,
130
+ };
131
+ }
132
+ const BAD_TAG = /phish|malware|scam|fraud|crypto.?drain|fake|credential|spam/i;
133
+ export async function urlCheck(ctx, input) {
134
+ const u = normalizeUrl(input);
135
+ const url = u.href;
136
+ const host = u.hostname.toLowerCase();
137
+ const domain = apexOf(host);
138
+ const isIp = /^\d{1,3}(\.\d{1,3}){3}$/.test(host);
139
+ const [sb, haus, who, scans] = await Promise.all([
140
+ safeBrowsing(ctx, [url, `${u.protocol}//${host}/`]),
141
+ urlhaus(ctx, url, host),
142
+ isIp ? Promise.resolve({ data: null, prov: { source: 'rdap', url: '', status: 'UNAVAILABLE', fetchedAt: ctx.now().toISOString(), note: 'IP address, no domain registration' } }) : rdap(ctx, domain),
143
+ scanHistory(ctx, host),
144
+ ]);
145
+ const provenance = [sb.prov, ...haus.prov, who.prov, scans.prov];
146
+ const heuristics = urlHeuristics(u);
147
+ const reasons = [];
148
+ let risk = 0;
149
+ const threats = sb.data ? [...new Set(sb.data.map((m) => m.threat.toLowerCase().replace(/_/g, ' ')))] : [];
150
+ if (threats.length) {
151
+ risk = 100;
152
+ reasons.push(`Google Safe Browsing flags it: ${threats.join(', ')}`);
153
+ }
154
+ const hu = haus.data?.url;
155
+ if (hu) {
156
+ risk = Math.max(risk, hu.status === 'online' ? 100 : 80);
157
+ reasons.push(`URLhaus lists this URL as ${hu.threat ?? 'malicious'} (${hu.status}${hu.tags.length ? `, ${hu.tags.join(', ')}` : ''})`);
158
+ }
159
+ const age = who.data?.ageDays;
160
+ const hh = haus.data?.host;
161
+ // Big, old platforms (GitHub, cloud storage) host files their users upload; malware among them says little
162
+ // about the platform itself, so host-level hits count fully only for young or small hosts.
163
+ const sharedHost = hh != null && hh.urls >= 50 && age != null && age > 5 * 365;
164
+ let hostHit = false;
165
+ if (hh && hh.urls > 0) {
166
+ if (sharedHost) {
167
+ risk += 5;
168
+ reasons.push(`the host serves user uploads; URLhaus has ${hh.urls} malware URLs on it, but not this one`);
169
+ }
170
+ else {
171
+ hostHit = hh.online > 0;
172
+ risk = Math.max(risk, hh.online ? 85 : 55);
173
+ reasons.push(`URLhaus has ${hh.urls} malware URL${hh.urls === 1 ? '' : 's'} on this host${hh.online ? `, ${hh.online} still online` : ''}`);
174
+ }
175
+ }
176
+ // Tags starting with "@" name the submitter (a feed or user), not a finding.
177
+ const badTags = (scans.data?.tags ?? []).filter((t) => !t.startsWith('@') && BAD_TAG.test(t));
178
+ if (badTags.length) {
179
+ risk = Math.max(risk, 70);
180
+ reasons.push(`urlscan.io scans of this host are tagged: ${badTags.join(', ')}`);
181
+ }
182
+ if (age != null && age < 30) {
183
+ risk = Math.max(risk, 45) + 10;
184
+ reasons.push(`the domain was registered ${age} day${age === 1 ? '' : 's'} ago`);
185
+ }
186
+ else if (age != null && age < 180) {
187
+ risk += 10;
188
+ reasons.push(`the domain is young (${age} days)`);
189
+ }
190
+ for (const h of heuristics)
191
+ risk += /not on .* own domain|punycode/.test(h) ? 35 : /top-level domain|raw IP|"@"/.test(h) ? 15 : 10;
192
+ reasons.push(...heuristics);
193
+ // Only when the link was given with http:// (a bare domain gets http:// added here).
194
+ if (/^http:\/\//i.test(input.trim()) && !threats.length && !hu)
195
+ reasons.push('no HTTPS in the link as given');
196
+ risk = clamp(Math.round(risk), 0, 100);
197
+ const verdict = threats.length || hu || hostHit ? 'malicious' : risk >= 40 ? 'suspicious' : 'no known threats';
198
+ if (verdict === 'no known threats' && age != null && age > 365)
199
+ reasons.push(`the domain is ${Math.floor(age / 365)} year${age >= 730 ? 's' : ''} old`);
200
+ const nowIso = ctx.now().toISOString();
201
+ const signals = [];
202
+ if (verdict === 'malicious') {
203
+ const s = {
204
+ id: signalId('urlcheck', url, nowIso.slice(0, 10)),
205
+ module: 'urlcheck',
206
+ title: `Malicious link: ${host}`,
207
+ score: clamp(risk, 60, 95),
208
+ entity: ctx.graph.upsert('domain', domain),
209
+ evidence: reasons.slice(0, 4).map((text) => ({ source: threats.length ? 'safe-browsing' : 'urlhaus', text, ...(hu?.reference ? { url: hu.reference } : {}) })),
210
+ createdAt: nowIso,
211
+ };
212
+ ctx.graph.saveSignal(s);
213
+ signals.push(s);
214
+ }
215
+ return {
216
+ module: 'urlcheck',
217
+ input,
218
+ generatedAt: nowIso,
219
+ result: { url, host, domain, verdict, risk, reasons, safeBrowsing: sb.data ? { threats } : null, urlhaus: haus.data, domainInfo: who.data, scans: scans.data, heuristics },
220
+ signals,
221
+ provenance,
222
+ };
223
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Vulnerabilities (no keys; GITHUB_TOKEN optional for a higher GitHub rate limit):
3
+ * CISA Known Exploited Vulnerabilities catalog: what attackers are exploiting right now, with ransomware use and
4
+ * federal remediation due dates. `kevSet` lets other modules flag exposed CVEs that are actively exploited.
5
+ * NVD CVE API 2.0: CVSS, CWE, affected products (CPE) and references; also newly published critical CVEs.
6
+ * FIRST EPSS: probability of exploitation in the next 30 days, with a 30-day trend.
7
+ * OSV.dev: affected open-source packages and fixed versions; package queries.
8
+ * GitHub Advisory Database: reviewed advisories with vulnerable version ranges; new critical advisories.
9
+ */
10
+ import type { Ctx } from '../core/context.js';
11
+ import type { ModuleResult, Provenance, Sourced } from '../core/types.js';
12
+ export interface KevEntry {
13
+ cveID: string;
14
+ vendorProject: string;
15
+ product: string;
16
+ vulnerabilityName: string;
17
+ dateAdded: string;
18
+ shortDescription: string;
19
+ dueDate: string;
20
+ knownRansomwareCampaignUse: string;
21
+ cwes: string[];
22
+ }
23
+ export interface KevCatalog {
24
+ version: string;
25
+ released: string;
26
+ count: number;
27
+ vulnerabilities: KevEntry[];
28
+ }
29
+ /** The CISA KEV catalog, slimmed (no long required-action text) and cached for 6 hours. */
30
+ export declare function kevCatalog(ctx: Ctx): Promise<Sourced<KevCatalog>>;
31
+ /** Upper-case CVE ids in the KEV catalog (empty set if the catalog is unavailable). */
32
+ export declare function kevSet(ctx: Ctx): Promise<Set<string>>;
33
+ export interface Epss {
34
+ score: number;
35
+ percentile: number;
36
+ date: string;
37
+ /** Change in score over the returned time series (about 30 days); null without history. */
38
+ change30d: number | null;
39
+ }
40
+ /** EPSS scores for up to 100 CVEs per request. */
41
+ export declare function epssScores(ctx: Ctx, ids: string[], series?: boolean): Promise<{
42
+ data: Map<string, Epss>;
43
+ prov: Provenance[];
44
+ }>;
45
+ export interface Advisory {
46
+ id: string;
47
+ cve: string | null;
48
+ summary: string;
49
+ severity: string;
50
+ cvss: number | null;
51
+ published: string;
52
+ packages: {
53
+ ecosystem: string;
54
+ name: string;
55
+ vulnerable: string;
56
+ patched: string | null;
57
+ }[];
58
+ url: string;
59
+ }
60
+ export interface RecentCve {
61
+ id: string;
62
+ published: string;
63
+ cvss: number | null;
64
+ description: string;
65
+ url: string;
66
+ }
67
+ export interface VulnsResult {
68
+ window: {
69
+ from: string;
70
+ to: string;
71
+ };
72
+ vendor: string | null;
73
+ catalog: {
74
+ version: string;
75
+ released: string;
76
+ count: number;
77
+ } | null;
78
+ kev: (KevEntry & {
79
+ epss: number | null;
80
+ daysToDue: number | null;
81
+ })[];
82
+ /** Newly published CVEs rated CRITICAL by NVD (window capped at 30 days). */
83
+ criticalCves: RecentCve[];
84
+ /** Newly published GitHub-reviewed critical advisories (open-source supply chain). */
85
+ advisories: Advisory[];
86
+ }
87
+ /** Newly added KEV entries (and fresh critical CVEs and advisories) in the last `days`, optionally for one vendor or product. */
88
+ export declare function vulns(ctx: Ctx, opts?: {
89
+ days?: number;
90
+ vendor?: string;
91
+ }): Promise<ModuleResult<VulnsResult>>;
92
+ export interface CveDetail {
93
+ id: string;
94
+ description: string;
95
+ published: string | null;
96
+ lastModified: string | null;
97
+ status: string | null;
98
+ cvss: {
99
+ version: string;
100
+ score: number;
101
+ severity: string;
102
+ vector: string;
103
+ } | null;
104
+ cwes: string[];
105
+ /** Vendor:product pairs from NVD CPE configurations (vulnerable only). */
106
+ products: string[];
107
+ references: {
108
+ url: string;
109
+ tags: string[];
110
+ }[];
111
+ kev: KevEntry | null;
112
+ epss: Epss | null;
113
+ packages: {
114
+ ecosystem: string;
115
+ name: string;
116
+ fixed: string[];
117
+ source: 'osv' | 'github';
118
+ }[];
119
+ advisories: Advisory[];
120
+ aliases: string[];
121
+ }
122
+ export declare const CVE_RE: RegExp;
123
+ /** One CVE in depth: NVD, EPSS (with trend), KEV membership, OSV affected packages and GitHub advisories. */
124
+ export declare function cve(ctx: Ctx, id: string): Promise<ModuleResult<CveDetail>>;
125
+ export interface PackageVuln {
126
+ id: string;
127
+ aliases: string[];
128
+ summary: string;
129
+ severity: string;
130
+ published: string;
131
+ modified: string;
132
+ fixed: string[];
133
+ exploited: boolean;
134
+ url: string;
135
+ }
136
+ /** Known vulnerabilities of one open-source package (optionally one version) from OSV.dev, flagged when exploited (KEV). */
137
+ export declare function packageVulns(ctx: Ctx, ecosystem: string, name: string, version?: string): Promise<ModuleResult<{
138
+ ecosystem: string;
139
+ name: string;
140
+ version: string | null;
141
+ vulns: PackageVuln[];
142
+ }>>;
@@ -0,0 +1,276 @@
1
+ import { key } from '../core/keys.js';
2
+ import { signalId } from '../core/text.js';
3
+ import { postJson } from '../sources/press.js';
4
+ const KEV_URL = 'https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json';
5
+ const NVD = 'https://services.nvd.nist.gov/rest/json/cves/2.0';
6
+ const DAY = 86_400_000;
7
+ /** The CISA KEV catalog, slimmed (no long required-action text) and cached for 6 hours. */
8
+ export async function kevCatalog(ctx) {
9
+ return ctx.http.get(KEV_URL, {
10
+ source: 'cisa-kev',
11
+ ttlSec: 6 * 3600,
12
+ timeoutMs: 60_000,
13
+ keep: (d) => ({
14
+ version: String(d.catalogVersion ?? ''),
15
+ released: String(d.dateReleased ?? ''),
16
+ count: Number(d.count ?? d.vulnerabilities?.length ?? 0),
17
+ vulnerabilities: (d.vulnerabilities ?? []).map((v) => ({
18
+ cveID: String(v.cveID ?? '').toUpperCase(),
19
+ vendorProject: String(v.vendorProject ?? ''),
20
+ product: String(v.product ?? ''),
21
+ vulnerabilityName: String(v.vulnerabilityName ?? ''),
22
+ dateAdded: String(v.dateAdded ?? ''),
23
+ shortDescription: String(v.shortDescription ?? '').slice(0, 300),
24
+ dueDate: String(v.dueDate ?? ''),
25
+ knownRansomwareCampaignUse: String(v.knownRansomwareCampaignUse ?? 'Unknown'),
26
+ cwes: Array.isArray(v.cwes) ? v.cwes : [],
27
+ })),
28
+ }),
29
+ });
30
+ }
31
+ /** Upper-case CVE ids in the KEV catalog (empty set if the catalog is unavailable). */
32
+ export async function kevSet(ctx) {
33
+ const r = await kevCatalog(ctx);
34
+ return new Set((r.data?.vulnerabilities ?? []).map((v) => v.cveID.toUpperCase()));
35
+ }
36
+ /** EPSS scores for up to 100 CVEs per request. */
37
+ export async function epssScores(ctx, ids, series = false) {
38
+ const out = new Map();
39
+ const prov = [];
40
+ const uniq = [...new Set(ids.map((i) => i.toUpperCase()))];
41
+ for (let i = 0; i < uniq.length; i += 50) {
42
+ const batch = uniq.slice(i, i + 50);
43
+ const r = await ctx.http.get(`https://api.first.org/data/v1/epss?cve=${batch.join(',')}${series ? '&scope=time-series' : ''}`, { source: 'epss', ttlSec: 12 * 3600 });
44
+ prov.push(r.prov);
45
+ for (const row of r.data?.data ?? []) {
46
+ const score = Number(row.epss);
47
+ const ts = row['time-series'] ?? [];
48
+ const oldest = ts.length ? Number(ts[ts.length - 1].epss) : NaN;
49
+ out.set(row.cve.toUpperCase(), { score, percentile: Number(row.percentile), date: row.date, change30d: Number.isFinite(oldest) ? Math.round((score - oldest) * 1e5) / 1e5 : null });
50
+ }
51
+ }
52
+ return { data: out, prov };
53
+ }
54
+ function ghHeaders() {
55
+ const t = key('GITHUB_TOKEN');
56
+ return { accept: 'application/vnd.github+json', 'x-github-api-version': '2022-11-28', ...(t ? { authorization: `Bearer ${t}` } : {}) };
57
+ }
58
+ const slimGh = (list) => (Array.isArray(list) ? list : [])
59
+ .filter((a) => !a.withdrawn_at)
60
+ .map((a) => ({
61
+ id: a.ghsa_id,
62
+ cve: a.cve_id ?? null,
63
+ summary: (a.summary ?? '').slice(0, 200),
64
+ severity: a.severity ?? 'unknown',
65
+ cvss: a.cvss?.score ?? null,
66
+ published: a.published_at,
67
+ packages: (a.vulnerabilities ?? []).slice(0, 12).map((v) => ({ ecosystem: v.package?.ecosystem ?? '', name: v.package?.name ?? '', vulnerable: v.vulnerable_version_range ?? '', patched: v.first_patched_version ?? null })),
68
+ url: a.html_url,
69
+ }));
70
+ const isoDay = (d) => d.toISOString().slice(0, 10);
71
+ const nvdDate = (d) => d.toISOString().slice(0, 23);
72
+ /** Newly added KEV entries (and fresh critical CVEs and advisories) in the last `days`, optionally for one vendor or product. */
73
+ export async function vulns(ctx, opts = {}) {
74
+ const now = ctx.now();
75
+ const days = Math.max(1, Math.min(opts.days ?? 7, 365));
76
+ const from = new Date(now.getTime() - days * DAY);
77
+ const vendor = opts.vendor?.trim() || null;
78
+ const vq = vendor?.toLowerCase();
79
+ const provenance = [];
80
+ const cat = await kevCatalog(ctx);
81
+ provenance.push(cat.prov);
82
+ const kevAll = (cat.data?.vulnerabilities ?? [])
83
+ .filter((v) => v.dateAdded >= isoDay(from))
84
+ .filter((v) => !vq || `${v.vendorProject} ${v.product} ${v.vulnerabilityName}`.toLowerCase().includes(vq))
85
+ .sort((a, b) => b.dateAdded.localeCompare(a.dateAdded) || a.cveID.localeCompare(b.cveID));
86
+ const ep = kevAll.length ? await epssScores(ctx, kevAll.slice(0, 100).map((v) => v.cveID)) : { data: new Map(), prov: [] };
87
+ provenance.push(...ep.prov);
88
+ const kev = kevAll.map((v) => ({
89
+ ...v,
90
+ epss: ep.data.get(v.cveID)?.score ?? null,
91
+ daysToDue: v.dueDate ? Math.ceil((Date.parse(`${v.dueDate}T23:59:59Z`) - now.getTime()) / DAY) : null,
92
+ }));
93
+ // NVD: publication window may not exceed 120 days; keep it to 30 to stay within the keyless rate limit.
94
+ const nvdFrom = new Date(now.getTime() - Math.min(days, 30) * DAY);
95
+ const nvd = await ctx.http.get(`${NVD}?pubStartDate=${nvdDate(nvdFrom)}&pubEndDate=${nvdDate(now)}&cvssV3Severity=CRITICAL&resultsPerPage=200${vendor ? `&keywordSearch=${encodeURIComponent(vendor)}` : ''}`, { source: 'nvd', ttlSec: 3 * 3600, timeoutMs: 60_000, keep: (d) => ({ vulnerabilities: (d.vulnerabilities ?? []).map((v) => ({ cve: { id: v.cve.id, published: v.cve.published, descriptions: v.cve.descriptions?.filter((x) => x.lang === 'en').map((x) => ({ lang: x.lang, value: x.value.slice(0, 300) })), metrics: { cvssMetricV31: v.cve.metrics?.cvssMetricV31?.slice(0, 1) } } })) }) });
96
+ provenance.push(nvd.prov);
97
+ const criticalCves = (nvd.data?.vulnerabilities ?? [])
98
+ .map(({ cve: c }) => ({ id: c.id, published: c.published, cvss: c.metrics?.cvssMetricV31?.[0]?.cvssData.baseScore ?? null, description: (c.descriptions?.find((x) => x.lang === 'en')?.value ?? '').slice(0, 300), url: `https://nvd.nist.gov/vuln/detail/${c.id}` }))
99
+ .sort((a, b) => b.published.localeCompare(a.published));
100
+ const gh = await ctx.http.get(`https://api.github.com/advisories?type=reviewed&severity=critical&per_page=100&sort=published&direction=desc&published=${encodeURIComponent(`>=${isoDay(from)}`)}`, { source: 'github-advisories', ttlSec: 3 * 3600, headers: ghHeaders(), keep: slimGh });
101
+ provenance.push(gh.prov);
102
+ const advisories = (gh.data ?? []).filter((a) => !vq || `${a.summary} ${a.packages.map((p) => p.name).join(' ')}`.toLowerCase().includes(vq));
103
+ const signals = [];
104
+ for (const v of kev.slice(0, 10)) {
105
+ const ransomware = v.knownRansomwareCampaignUse.toLowerCase() === 'known';
106
+ const dueSoon = v.daysToDue !== null && v.daysToDue <= 7;
107
+ const score = Math.min(95, 68 + (ransomware ? 14 : 0) + (dueSoon ? 8 : 0) + (v.epss !== null && v.epss >= 0.5 ? 5 : 0));
108
+ signals.push({
109
+ id: signalId('vulns', 'kev', v.cveID),
110
+ module: 'vulns',
111
+ title: `Actively exploited: ${v.cveID} ${v.vendorProject} ${v.product}${ransomware ? ' (used by ransomware)' : ''}`,
112
+ score,
113
+ entity: v.vendorProject,
114
+ evidence: [{ source: 'cisa-kev', text: `Added to CISA KEV ${v.dateAdded}, federal due date ${v.dueDate}${v.epss !== null ? `, EPSS ${v.epss.toFixed(3)}` : ''}: ${v.shortDescription.slice(0, 200)}`, url: `https://nvd.nist.gov/vuln/detail/${v.cveID}` }],
115
+ createdAt: now.toISOString(),
116
+ });
117
+ }
118
+ for (const a of advisories.filter((x) => now.getTime() - Date.parse(x.published) <= 2 * DAY).slice(0, 3)) {
119
+ const pkg = a.packages[0];
120
+ signals.push({
121
+ id: signalId('vulns', 'ghsa', a.id),
122
+ module: 'vulns',
123
+ title: `Critical open-source advisory: ${a.summary}`,
124
+ score: 58,
125
+ ...(pkg?.name ? { entity: pkg.name } : {}),
126
+ evidence: [{ source: 'github-advisories', text: `${a.id}${a.cve ? ` / ${a.cve}` : ''}${pkg ? `, ${pkg.ecosystem} ${pkg.name} ${pkg.vulnerable}${pkg.patched ? `, fixed in ${pkg.patched}` : ', no fix yet'}` : ''}`, url: a.url }],
127
+ createdAt: now.toISOString(),
128
+ });
129
+ }
130
+ for (const s of signals)
131
+ ctx.graph.saveSignal(s);
132
+ return {
133
+ module: 'vulns',
134
+ input: vendor ? `${vendor}, last ${days}d` : `last ${days}d`,
135
+ generatedAt: now.toISOString(),
136
+ result: { window: { from: from.toISOString(), to: now.toISOString() }, vendor, catalog: cat.data ? { version: cat.data.version, released: cat.data.released, count: cat.data.count } : null, kev, criticalCves, advisories },
137
+ signals,
138
+ provenance,
139
+ };
140
+ }
141
+ export const CVE_RE = /^CVE-\d{4}-\d{4,}$/i;
142
+ /** One CVE in depth: NVD, EPSS (with trend), KEV membership, OSV affected packages and GitHub advisories. */
143
+ export async function cve(ctx, id) {
144
+ const now = ctx.now();
145
+ const cid = id.trim().toUpperCase();
146
+ if (!CVE_RE.test(cid))
147
+ throw new Error(`not a CVE id: ${id} (expected CVE-YYYY-NNNN)`);
148
+ const provenance = [];
149
+ const nvd = await ctx.http.get(`${NVD}?cveId=${cid}`, {
150
+ source: 'nvd',
151
+ ttlSec: 24 * 3600,
152
+ timeoutMs: 60_000,
153
+ keep: (d) => ({ vulnerabilities: (d.vulnerabilities ?? []).map((v) => ({ cve: { ...v.cve, references: v.cve.references?.slice(0, 25).map((r) => ({ url: r.url, tags: r.tags })), configurations: v.cve.configurations?.slice(0, 20) } })) }),
154
+ });
155
+ provenance.push(nvd.prov);
156
+ const c = nvd.data?.vulnerabilities?.[0]?.cve;
157
+ const metric = c ? ['cvssMetricV40', 'cvssMetricV31', 'cvssMetricV30', 'cvssMetricV2'].map((k) => c.metrics?.[k]?.find((m) => m.type === 'Primary') ?? c.metrics?.[k]?.[0]).find(Boolean) : undefined;
158
+ const products = new Set();
159
+ for (const conf of c?.configurations ?? [])
160
+ for (const n of conf.nodes)
161
+ for (const m of n.cpeMatch)
162
+ if (m.vulnerable) {
163
+ const p = m.criteria.split(':');
164
+ if (p[3] && p[4])
165
+ products.add(`${p[3]}:${p[4]}`);
166
+ }
167
+ const [ep, kevs] = await Promise.all([epssScores(ctx, [cid], true), kevCatalog(ctx)]);
168
+ provenance.push(...ep.prov, kevs.prov);
169
+ const kev = kevs.data?.vulnerabilities.find((v) => v.cveID === cid) ?? null;
170
+ const osv = await ctx.http.get(`https://api.osv.dev/v1/vulns/${cid}`, {
171
+ source: 'osv',
172
+ ttlSec: 12 * 3600,
173
+ keep: (d) => ({ aliases: d.aliases, affected: (d.affected ?? []).filter((a) => a.package?.name).slice(0, 40).map((a) => ({ package: { ecosystem: a.package.ecosystem, name: a.package.name }, ranges: a.ranges?.filter((r) => r.type !== 'GIT').map((r) => ({ type: r.type, events: r.events.filter((e) => 'fixed' in e) })) })) }),
174
+ });
175
+ provenance.push(osv.prov);
176
+ const gh = await ctx.http.get(`https://api.github.com/advisories?cve_id=${cid}`, { source: 'github-advisories', ttlSec: 12 * 3600, headers: ghHeaders(), keep: slimGh });
177
+ provenance.push(gh.prov);
178
+ const advisories = gh.data ?? [];
179
+ const packages = [];
180
+ const seen = new Set();
181
+ for (const a of osv.data?.affected ?? []) {
182
+ const k = `${a.package?.ecosystem}:${a.package?.name}`.toLowerCase();
183
+ if (seen.has(k))
184
+ continue;
185
+ seen.add(k);
186
+ packages.push({ ecosystem: a.package?.ecosystem ?? '', name: a.package?.name ?? '', fixed: [...new Set((a.ranges ?? []).flatMap((r) => r.events.map((e) => e.fixed).filter(Boolean)))], source: 'osv' });
187
+ }
188
+ for (const a of advisories)
189
+ for (const p of a.packages) {
190
+ const k = `${p.ecosystem}:${p.name}`.toLowerCase();
191
+ if (seen.has(k))
192
+ continue;
193
+ seen.add(k);
194
+ packages.push({ ecosystem: p.ecosystem, name: p.name, fixed: p.patched ? [p.patched] : [], source: 'github' });
195
+ }
196
+ const epss = ep.data.get(cid) ?? null;
197
+ const detail = {
198
+ id: cid,
199
+ description: c?.descriptions?.find((d) => d.lang === 'en')?.value ?? kev?.shortDescription ?? '',
200
+ published: c?.published ?? null,
201
+ lastModified: c?.lastModified ?? null,
202
+ status: c?.vulnStatus ?? null,
203
+ cvss: metric ? { version: metric.cvssData.version, score: metric.cvssData.baseScore, severity: metric.cvssData.baseSeverity ?? '', vector: metric.cvssData.vectorString } : null,
204
+ cwes: [...new Set((c?.weaknesses ?? []).flatMap((w) => w.description.map((d) => d.value)).filter((v) => /^CWE-\d+$/.test(v)))],
205
+ products: [...products].slice(0, 30),
206
+ references: (c?.references ?? []).slice(0, 15).map((r) => ({ url: r.url, tags: r.tags ?? [] })),
207
+ kev,
208
+ epss,
209
+ packages,
210
+ advisories,
211
+ aliases: [...new Set([...(osv.data?.aliases ?? []), ...advisories.map((a) => a.id)])],
212
+ };
213
+ const signals = [];
214
+ const url = `https://nvd.nist.gov/vuln/detail/${cid}`;
215
+ if (kev) {
216
+ signals.push({ id: signalId('vulns', 'kev', cid), module: 'vulns', title: `Actively exploited: ${cid} ${kev.vendorProject} ${kev.product}`, score: kev.knownRansomwareCampaignUse.toLowerCase() === 'known' ? 82 : 72, entity: kev.vendorProject, evidence: [{ source: 'cisa-kev', text: `In CISA KEV since ${kev.dateAdded}, due ${kev.dueDate}, ransomware use: ${kev.knownRansomwareCampaignUse}`, url }], createdAt: now.toISOString() });
217
+ }
218
+ if (epss && epss.change30d !== null && epss.change30d >= 0.2) {
219
+ signals.push({ id: signalId('vulns', 'epss-jump', cid, epss.date), module: 'vulns', title: `Exploitation likelihood rising: ${cid} EPSS ${epss.score.toFixed(3)}`, score: 64, evidence: [{ source: 'epss', text: `EPSS up ${epss.change30d.toFixed(3)} over about 30 days (percentile ${epss.percentile.toFixed(3)})`, url: `https://api.first.org/data/v1/epss?cve=${cid}` }], createdAt: now.toISOString() });
220
+ }
221
+ for (const s of signals)
222
+ ctx.graph.saveSignal(s);
223
+ return { module: 'vulns', input: cid, generatedAt: now.toISOString(), result: detail, signals, provenance };
224
+ }
225
+ /** Known vulnerabilities of one open-source package (optionally one version) from OSV.dev, flagged when exploited (KEV). */
226
+ export async function packageVulns(ctx, ecosystem, name, version) {
227
+ const now = ctx.now();
228
+ const provenance = [];
229
+ const all = [];
230
+ let pageToken;
231
+ for (let page = 0; page < 3; page++) {
232
+ const body = { package: { name, ecosystem }, ...(version ? { version } : {}), ...(pageToken ? { page_token: pageToken } : {}) };
233
+ const r = await postJson(ctx, 'https://api.osv.dev/v1/query', body, {}, 'osv', 6 * 3600);
234
+ provenance.push(r.prov);
235
+ all.push(...(r.data?.vulns ?? []));
236
+ pageToken = r.data?.next_page_token;
237
+ if (!pageToken)
238
+ break;
239
+ }
240
+ const kev = await kevSet(ctx);
241
+ const lname = name.toLowerCase();
242
+ const list = all
243
+ .filter((v) => !v.withdrawn)
244
+ .map((v) => {
245
+ const aliases = (v.aliases ?? []).filter((a) => a !== v.id);
246
+ const ids = [v.id, ...aliases].map((x) => x.toUpperCase());
247
+ const mine = (v.affected ?? []).filter((a) => a.package?.name?.toLowerCase() === lname);
248
+ return {
249
+ id: v.id,
250
+ aliases,
251
+ summary: (v.summary ?? v.details ?? '').slice(0, 200),
252
+ severity: v.database_specific?.severity ?? v.severity?.[0]?.score ?? 'unknown',
253
+ published: v.published ?? '',
254
+ modified: v.modified ?? '',
255
+ fixed: [...new Set(mine.flatMap((a) => (a.ranges ?? []).flatMap((r) => r.events.map((e) => e.fixed).filter(Boolean))))],
256
+ exploited: ids.some((x) => kev.has(x)),
257
+ url: `https://osv.dev/vulnerability/${v.id}`,
258
+ };
259
+ })
260
+ .sort((a, b) => Number(b.exploited) - Number(a.exploited) || b.published.localeCompare(a.published));
261
+ const signals = list
262
+ .filter((v) => v.exploited)
263
+ .slice(0, 5)
264
+ .map((v) => ({
265
+ id: signalId('vulns', 'pkg', ecosystem, name, version ?? '', v.id),
266
+ module: 'vulns',
267
+ title: `${ecosystem} ${name}${version ? ` ${version}` : ''} has an actively exploited vulnerability: ${v.aliases.find((a) => CVE_RE.test(a)) ?? v.id}`,
268
+ score: version ? 76 : 66,
269
+ entity: name,
270
+ evidence: [{ source: 'osv', text: `${v.summary}${v.fixed.length ? `; fixed in ${v.fixed.join(', ')}` : ''}; listed in CISA KEV`, url: v.url }],
271
+ createdAt: now.toISOString(),
272
+ }));
273
+ for (const s of signals)
274
+ ctx.graph.saveSignal(s);
275
+ return { module: 'vulns', input: `${ecosystem}/${name}${version ? `@${version}` : ''}`, generatedAt: now.toISOString(), result: { ecosystem, name, version: version ?? null, vulns: list }, signals, provenance };
276
+ }