import { databaseBackgroundWork } from "./database-background-work.js" import { OTHER_SERVICE, resolveFlowBrand } from "./traffic-flow-brands.js" import { db } from "../db/index.js" import { evobgpSettings } from "../db/schema.js" import { withActiveDatabaseRequest } from "../modules/mcp/database-request-lease.js" import { ipInCidrV4, parseCidrV4 } from "./traffic-flow-ip.js" import type { FlowIpMeta } from "./traffic-flow-ripe.js" import { applicationName } from "./traffic-flow-apps.js" import type { FlowServiceBasis } from "@mmapp/contracts/traffic-flow" export interface FlowClassification { service: string category: string basis: FlowServiceBasis } interface CatalogCidr { cidr: string purpose: string prefixLen: number } const CATALOG_TTL_MS = 10 * 60_000 let cidrs: CatalogCidr[] = [] let asnPurpose = new Map() let fetchedAt = 0 let catalogFetchEnabled = true let inflight: Promise | null = null export function disableCatalogFetchForTests(): void { catalogFetchEnabled = false } export const resetFlowCatalogForTests = invalidateFlowClassificationCache export function invalidateFlowClassificationCache(): void { cidrs = [] asnPurpose = new Map() fetchedAt = 0 inflight = null } export function seedFlowCatalogForTests(input: { cidrs?: Array<{ cidr: string; purpose: string }> asns?: Array<{ asn: number; purpose: string }> }): void { cidrs = (input.cidrs ?? []) .map((c) => ({ cidr: c.cidr, purpose: c.purpose, prefixLen: parseCidrV4(c.cidr)?.prefixLen ?? 0 })) .sort((a, b) => b.prefixLen - a.prefixLen) asnPurpose = new Map((input.asns ?? []).map((a) => [a.asn, a.purpose])) fetchedAt = Date.now() } export function categoryFromPurpose(purpose: string, proto: number, dstPort: number, srcPort: number): string { const p = purpose.trim().toLowerCase() if (/игры|gaming|steam|epic|riot|playstation|roblox|ubisoft/.test(p)) return "Игры" if (/видео|стриминг|streaming|youtube|netflix|twitch|video|spotify|instagram/.test(p)) return "Видео / стриминг" if (/cdn|cloudflare|akamai|fastly|hetzner|ovh|apple/.test(p)) return "CDN" if (/мессенджер|telegram/.test(p)) return "Мессенджеры" if (/голос|voip|discord|zoom/.test(p)) return "Голос" if (p === "ии" || /openai|chatgpt|\bai\b/.test(p)) return "ИИ" if (/quad9|opendns/.test(p)) return "DNS" if (/веб|web|google|github|paypal|vk|linkedin/.test(p)) return "Веб" const app = applicationName(proto, dstPort, srcPort) if (app === "DNS" || app === "SSH" || app === "BGP") return app if (app === "GRE" || app === "ESP" || app === "WireGuard") return "Туннель" return OTHER_SERVICE } function matchCidr(ip: string,rows=cidrs): CatalogCidr | null { for (const row of rows) { if (ipInCidrV4(ip, row.cidr)) return row } return null } function servicePurpose(value: string | undefined): string | undefined { const purpose = value?.trim() return purpose && !/^(main|default|other|прочее)$/i.test(purpose) ? purpose : undefined } export function classifyFlowDst( dst: string, proto: number, dstPort: number, srcPort: number, ripe: FlowIpMeta | null, opts?: { ignoreTunnelProto?: boolean;catalog?:{cidrs:CatalogCidr[];asnPurpose:Map} }, ): FlowClassification { if (!opts?.ignoreTunnelProto) { if (proto === 47) return { service: "GRE", category: "Туннель", basis: "port" } if (proto === 50) return { service: "ESP", category: "Туннель", basis: "port" } } const app = applicationName(proto, dstPort, srcPort) if ((proto === 6 || proto === 17) && (dstPort === 53 || dstPort === 853)) return { service: "DNS", category: "DNS", basis: "port" } if (app === "WireGuard") return { service: "WireGuard", category: "Туннель", basis: "port" } const prefixPurpose = servicePurpose(matchCidr(dst,opts?.catalog?.cidrs)?.purpose) const holder = ripe?.holder ?? "" const brand = resolveFlowBrand(dst, ripe?.asn ?? 0, holder, proto, dstPort, srcPort) if (prefixPurpose && prefixPurpose.toLowerCase() !== brand?.operator?.toLowerCase()) { return { service: prefixPurpose, category: categoryFromPurpose(prefixPurpose, proto, dstPort, srcPort), basis: "catalog" } } if (brand) return { service: brand.service, category: brand.category, basis: brand.heuristic ? "heuristic" : "network" } const asnName = ripe?.asn ? servicePurpose((opts?.catalog?.asnPurpose??asnPurpose).get(ripe.asn)) : undefined const category = categoryFromPurpose(asnName || "", proto, dstPort, srcPort) const basis = asnName ? "catalog" : category !== OTHER_SERVICE ? "port" : "unknown" return { service: asnName || OTHER_SERVICE, category, basis } } /** Copies already-observed data only; never fetches the EvoBGP catalog. */ export function captureFlowClassificationCatalog() { if(cidrs.length>100000||asnPurpose.size>100000)throw Error("Flow classification snapshot exceeds bound") return {cidrs:cidrs.map(row=>({...row})),asnPurpose:new Map(asnPurpose)} } async function fetchCatalog(): Promise { if (!catalogFetchEnabled) return if (Date.now() - fetchedAt < CATALOG_TTL_MS) return if (inflight) return inflight inflight = (async () => { try { const readSettings = async () => db.select().from(evobgpSettings).limit(1) const [row] = await (withActiveDatabaseRequest(readSettings) ?? readSettings()) if (!row?.enabled) return const root = String(row.baseUrl ?? "").replace(/\/+$/, "") const token = String(row.apiKey ?? "").replace(/^Bearer\s+/i, "").trim() if (!root || !token) return const ac = new AbortController() const t = setTimeout(() => ac.abort(), 20_000) try { const res = await fetch(`${root}/v1/router-lists/catalog`, { headers: { Authorization: `Bearer ${token}`, Accept: "application/json" }, signal: ac.signal, }) if (!res.ok) return const catalog = await res.json() as { modules?: { items?: Array<{ id: string; name: string }> } ip_ranges?: { items?: Array<{ module_id: string; entry: { prefix: string } }> } asns?: { items?: Array<{ module_id: string; entry: { asn: number } }> } } const mods = new Map((catalog.modules?.items ?? []).map((m) => [m.id, m.name])) const next: CatalogCidr[] = [] for (const item of catalog.ip_ranges?.items ?? []) { const prefix = String(item.entry?.prefix ?? "").trim() const purpose = mods.get(item.module_id) ?? "" const parsed = parseCidrV4(prefix) if (!prefix || !parsed) continue next.push({ cidr: prefix, purpose, prefixLen: parsed.prefixLen }) } next.sort((a, b) => b.prefixLen - a.prefixLen) const nextAsn = new Map() for (const item of catalog.asns?.items ?? []) { const purpose = mods.get(item.module_id) const asn = Number(item.entry?.asn) if (purpose && Number.isFinite(asn) && asn > 0) nextAsn.set(asn, purpose) } cidrs = next asnPurpose = nextAsn fetchedAt = Date.now() } finally { clearTimeout(t) } } catch { /* catalog optional */ } finally { inflight = null } })() return inflight } /** Background refresh — analytics never awaits the HTTP. */ export function refreshFlowCatalogInBackground(): void { void databaseBackgroundWork.track(fetchCatalog()) }