Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b896e469a7 | ||
|
|
c44bcd8f59 | ||
|
|
ed7b1e0350 | ||
|
|
4097e1a6fc | ||
|
|
7cf17c7283 |
No files matched your search
+129
-88
@@ -26,7 +26,8 @@ import {
|
||||
type ServerStatus,
|
||||
type ServerType,
|
||||
} from "@/lib/data"
|
||||
import {validateNetworkMapSnapshot,networkMapFlowSchema,validateNetworkMapDns,type NetworkMapServerRow} from "@/lib/network-map-response"
|
||||
import {validateNetworkMapSnapshot,networkMapFlowSchema,recentMapFlowSchema,validateNetworkMapDns,type NetworkMapServerRow} from "@/lib/network-map-response"
|
||||
import { getFlowMapHops } from "@/shared/api/traffic-flow"
|
||||
import { useDataSource } from "@/lib/data-source"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
import {
|
||||
@@ -196,6 +197,30 @@ function makeApiFetch(backendUrl: string) {
|
||||
}
|
||||
}
|
||||
|
||||
function useServiceSnapshot(base: string | null, range: "1m" | "5m", userId: string | undefined, refresh: number) {
|
||||
const key = JSON.stringify([base, range, userId])
|
||||
const [snapshot, setSnapshot] = useState<{ key: string; refresh: number; data?: ReturnType<typeof networkMapFlowSchema.parse>; at?: string; error?: string }>()
|
||||
useEffect(() => {
|
||||
if (base === null) return
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
const poll = async () => {
|
||||
try {
|
||||
const raw = await getFlowMapHops(base, { range, userId }, { signal: controller.signal })
|
||||
const data = (range === "1m" ? recentMapFlowSchema : networkMapFlowSchema).parse(raw)
|
||||
if (!controller.signal.aborted) setSnapshot({ key, refresh, data, at: new Date().toISOString() })
|
||||
} catch {
|
||||
if (!controller.signal.aborted) setSnapshot(last => ({ ...(last?.key === key ? last : undefined), key, refresh, error: "Не удалось обновить данные IPFIX" }))
|
||||
} finally {
|
||||
if (!controller.signal.aborted) timer = setTimeout(poll, range === "1m" ? 4000 : 15_000)
|
||||
}
|
||||
}
|
||||
queueMicrotask(() => { if (!controller.signal.aborted) void poll() })
|
||||
return () => { controller.abort(); clearTimeout(timer) }
|
||||
}, [base, range, userId, refresh, key])
|
||||
return base !== null && snapshot?.key === key ? snapshot : undefined
|
||||
}
|
||||
|
||||
function fmtMB(mb: number | null): string {
|
||||
if(mb==null)return "—"
|
||||
if (mb >= 1024) return `${(mb / 1024).toFixed(mb >= 10240 ? 0 : 1)} ГБ`
|
||||
@@ -559,6 +584,12 @@ function ServerNode({ n, isSel, isVis, isDragged, hideCatalogLatency, rates, onC
|
||||
)
|
||||
}
|
||||
|
||||
function serviceMapSubtitle(service: FlowMapService): string {
|
||||
const top = service.trafficTypes?.[0]
|
||||
if (service.category !== "Прочее" || !top || top.bytes * 2 <= service.bytes) return service.category
|
||||
return top.application ? shortName(`≈ ${top.application} · ${top.transport}`, 25) : top.transport
|
||||
}
|
||||
|
||||
function ServiceNode({
|
||||
label,
|
||||
share,
|
||||
@@ -913,7 +944,7 @@ function NetworkMapContent() {
|
||||
const [showSmallServices, setShowSmallServices] = useState(false)
|
||||
const [inspectedEvent, setInspectedEvent] = useState<MapEventRow | null>(null)
|
||||
const [flowRefresh,setFlowRefresh]=useState(0)
|
||||
const access = useMapAccess(useLiveData ? backendUrl : null, hasIxNodes, flowRefresh, Boolean(pickedUserId))
|
||||
const access = useMapAccess(useLiveData ? backendUrl : null, hasIxNodes, flowRefresh, pickedUserId)
|
||||
useEffect(() => {
|
||||
if (!useLiveData || !hasIxNodes) return
|
||||
const controller = new AbortController()
|
||||
@@ -946,11 +977,11 @@ function NetworkMapContent() {
|
||||
const [flowReadAt,setFlowReadAt]=useState<string|null>(null)
|
||||
const [flowListener,setFlowListener]=useState(false)
|
||||
const [flowLoading,setFlowLoading]=useState(false)
|
||||
const [userFlow, setUserFlow] = useState<{ key: string; data?: ReturnType<typeof networkMapFlowSchema.parse>; error?: string }>()
|
||||
const [bottomTab, setBottomTab] = useState<MapBottomTab>("flows")
|
||||
const [analysisOpen, setAnalysisOpen] = useState(false)
|
||||
const [summaryOpen, setSummaryOpen] = useState(false)
|
||||
const [filteredServiceId, setFilteredServiceId] = useState<string | null>(null)
|
||||
const [filterService, setFilterService] = useState<Pick<FlowMapService, "id" | "label"> | null>(null)
|
||||
const filteredServiceId = filterService?.id ?? null
|
||||
const [mapEvents, setMapEvents] = useState<EventItem[] | null>(null)
|
||||
const [eventsError, setEventsError] = useState<string | null>(null)
|
||||
const [eventsAt, setEventsAt] = useState(() => Date.now())
|
||||
@@ -1127,7 +1158,7 @@ function NetworkMapContent() {
|
||||
function setDestMode(mode: DestMode) {
|
||||
updateUrl({dest:mode==="services"?null:mode,service:null})
|
||||
setSelectedService(null)
|
||||
setFilteredServiceId(null)
|
||||
setFilterService(null)
|
||||
setExpandedCountryId(null)
|
||||
setHighlightedPath(null)
|
||||
try { sessionStorage.setItem(DEST_MODE_KEY, mode) } catch { /* private mode */ }
|
||||
@@ -1202,6 +1233,7 @@ function NetworkMapContent() {
|
||||
const [showAnimDots, setShowAnimDots] = useState(true)
|
||||
const [showMinimap, setShowMinimap] = useState(true)
|
||||
const [showHints, setShowHints] = useState(false)
|
||||
const [showAuxLinks, setShowAuxLinks] = useState(true)
|
||||
const [showLayers, setShowLayers] = useState(false)
|
||||
const [showUsers, setShowUsers] = useState(true)
|
||||
|
||||
@@ -1235,7 +1267,7 @@ function NetworkMapContent() {
|
||||
setFlowLoading(true)
|
||||
ac?.abort()
|
||||
ac = new AbortController()
|
||||
apiFetch<unknown>("/api/traffic/flow/map-hops?range=1m", { signal: ac.signal })
|
||||
apiFetch<unknown>("/api/traffic/flow/map-hops?range=5m", { signal: ac.signal })
|
||||
.then((raw) => {
|
||||
if (cancelled||request!==epoch) return
|
||||
const res=networkMapFlowSchema.parse(raw)
|
||||
@@ -1320,33 +1352,25 @@ function NetworkMapContent() {
|
||||
const usersInTopology = [...(ixOnly ? [] : access.users), ...access.linux].filter(user => user.bindings.some(binding => topologyIds.has(binding.node)))
|
||||
const pickedUser = usersInTopology.find(user => user.id === pickedUserId)
|
||||
const scopeUser = pickedUser && !pickedUser.linux ? pickedUser.id : undefined
|
||||
const scopeKey = JSON.stringify([backendUrl, scopeUser, flowRefresh])
|
||||
const userSnapshot = useLiveData && scopeUser && userFlow?.key === scopeKey ? userFlow : undefined
|
||||
useEffect(() => {
|
||||
if (!useLiveData || !scopeUser || !showServices) return
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
async function refresh() {
|
||||
try {
|
||||
const raw = await apiFetch<unknown>(`/api/traffic/flow/map-hops?${new URLSearchParams({range:"1m",userId:scopeUser!})}`, {signal:controller.signal})
|
||||
const data = networkMapFlowSchema.parse(raw)
|
||||
if (!controller.signal.aborted) setUserFlow({ key: scopeKey, data })
|
||||
} catch {
|
||||
if (!controller.signal.aborted) setUserFlow(last => ({ key: scopeKey, data: last?.key === scopeKey ? last.data : undefined, error: "Снимок потоков пользователя недоступен" }))
|
||||
} finally {
|
||||
if (!controller.signal.aborted) timer = setTimeout(() => { void refresh() }, 15_000)
|
||||
}
|
||||
}
|
||||
void refresh()
|
||||
return () => { controller.abort(); clearTimeout(timer) }
|
||||
}, [useLiveData, scopeUser, showServices, scopeKey, apiFetch])
|
||||
const rawPaths = destMode === "countries" ? mapCountryPaths : mapServicePaths
|
||||
const filterPaths = filteredServiceId?.includes("|") ? mapCountryServiceGroups.find(group => group.countryId === filteredServiceId.split("|")[0])?.paths ?? [] : rawPaths
|
||||
const liveServiceView = useLiveData && destMode === "services"
|
||||
const requestRecent = liveServiceView && (showServices || showNetflow) && (!pickedUserId || Boolean(scopeUser))
|
||||
const recent = useServiceSnapshot(requestRecent ? backendUrl : null, "1m", scopeUser, flowRefresh)
|
||||
const history = useServiceSnapshot(liveServiceView && scopeUser && (selectedService || linkedService) ? backendUrl : null, "5m", scopeUser, flowRefresh)
|
||||
const destinationWindowSec = liveServiceView ? recent?.data?.windowSec ?? 60 : mapWindowSec
|
||||
const destinationWindow = liveServiceView && !recent?.data ? "—" : formatMapFlowWindow(destinationWindowSec)
|
||||
const destinationReadAt = liveServiceView ? recent?.at ?? null : flowReadAt
|
||||
const destinationListener = liveServiceView ? recent?.data?.live : flowListener
|
||||
const destinationTotalBytes = liveServiceView ? recent?.data?.totalBytes : mapTotalBytes
|
||||
const destinationNamedBytes = liveServiceView ? recent?.data?.namedBytes : mapNamedBytes
|
||||
const initialDestNodes = liveServiceView ? recent?.data?.services ?? [] : destMode === "countries" ? mapCountries : mapServices
|
||||
const initialDestEdges = liveServiceView ? recent?.data?.serviceEdges ?? [] : destMode === "countries" ? mapCountryEdges : mapServiceEdges
|
||||
const rawPaths = liveServiceView ? recent?.data?.servicePaths ?? [] : destMode === "countries" ? mapCountryPaths : mapServicePaths
|
||||
const filterPaths = filteredServiceId?.includes("|") ? mapCountryServiceGroups.find(group => group.countryId === filteredServiceId.split("|")[0])?.paths ?? [] : scopeUser ? mapServicePaths : rawPaths
|
||||
const topologyPaths = rawPaths.filter(path => topologyIds.has(path.enId || path.viaId))
|
||||
const servicePaths = filteredServiceId ? filterPaths.filter(path => topologyIds.has(path.enId || path.viaId) && path.serviceId === filteredServiceId) : []
|
||||
const userIdsForService = new Set(servicePaths.map(path => path.clientId))
|
||||
const pickerUsers = filteredServiceId ? usersInTopology.filter(user => !user.linux && userIdsForService.has(user.id)) : usersInTopology
|
||||
const pickedPaths = pickedUser && !pickedUser.linux ? (userSnapshot?.data?.servicePaths ?? topologyPaths).filter(path => path.clientId === pickedUser.id && topologyIds.has(path.enId || path.viaId)) : []
|
||||
const pickedPaths = pickedUser && !pickedUser.linux ? topologyPaths.filter(path => path.clientId === pickedUser.id) : []
|
||||
const accessGroups = new Map<string, typeof usersInTopology>()
|
||||
for (const user of showUsers ? (pickedUser ? [pickedUser] : pickerUsers) : []) {
|
||||
const bindings = new Set(user.bindings.map(binding => binding.node))
|
||||
@@ -1354,11 +1378,11 @@ function NetworkMapContent() {
|
||||
}
|
||||
const focusedNodeIds = new Set([...(pickedUser?.bindings.map(binding => binding.node) ?? accessGroups.keys()), ...pickedPaths.flatMap(path => [path.viaId, path.enId])])
|
||||
const serviceNodeIds = new Set([...accessGroups.keys(), ...servicePaths.flatMap(path => [path.viaId, path.enId]),
|
||||
...(destMode === "countries" ? mapCountryEdges : mapServiceEdges).filter(edge => edge.toId === filteredServiceId).map(edge => edge.fromId)])
|
||||
...initialDestEdges.filter(edge => edge.toId === filteredServiceId).map(edge => edge.fromId)])
|
||||
const onMap = (id: string) => topologyIds.has(id) && (pickedUserId ? focusedNodeIds.has(id) && Boolean(pickedUser) : !filteredServiceId || !serviceNodeIds.size || serviceNodeIds.has(id))
|
||||
const userDetailsOpen = Boolean(pickedUser && inspectUser && !selected && !selectedGreStored && !selectedService && !params.has("service"))
|
||||
function changeMapView(ix: boolean) {
|
||||
setSelectedGreEdge(null); setSelectedService(null); setHighlightedPath(null); setFilteredServiceId(null)
|
||||
setSelectedGreEdge(null); setSelectedService(null); setHighlightedPath(null); setFilterService(null)
|
||||
setExpandedCountryId(null); setShowSmallServices(false)
|
||||
updateUrl({ filter: ix ? "ix-node" : null, server: null, wan: null, user: null, service: null, q: null, dest: null })
|
||||
}
|
||||
@@ -1535,14 +1559,15 @@ function NetworkMapContent() {
|
||||
return m
|
||||
}, [homeRouters, mapHops, showNetflow])
|
||||
|
||||
const initialDestNodes = destMode === "countries" ? mapCountries : mapServices
|
||||
const initialDestEdges = destMode === "countries" ? mapCountryEdges : mapServiceEdges
|
||||
const scoped = pickedUserId && !pickedUser ? { services: [], edges: [], paths: [] } : userSnapshot?.data
|
||||
? scopeMapDestinations(userSnapshot.data.services, userSnapshot.data.serviceEdges, userSnapshot.data.servicePaths, id => topologyIds.has(id))
|
||||
: pickedUser || ixOnly || splitIx && isolatedIx.size > 0
|
||||
? scopeMapDestinations(initialDestNodes, initialDestEdges, pickedUser?.linux ? [] : rawPaths, id => topologyIds.has(id), pickedUser?.id, !ixOnly && !pickedUser)
|
||||
: { services: initialDestNodes, edges: initialDestEdges, paths: rawPaths }
|
||||
const { services: destNodes, edges: destEdges, paths: destPaths } = scoped
|
||||
function inMapScope(services: FlowMapService[], edges: FlowMapServiceEdge[], paths: FlowMapServicePath[]) {
|
||||
if (pickedUserId && !pickedUser) return { services: [], edges: [], paths: [], shareOfVisible: false }
|
||||
const localUser = liveServiceView && scopeUser ? undefined : pickedUser?.id
|
||||
return localUser || ixOnly || splitIx && isolatedIx.size > 0
|
||||
? scopeMapDestinations(services, edges, pickedUser?.linux ? [] : paths, id => topologyIds.has(id), localUser, !ixOnly && !pickedUser)
|
||||
: { services, edges, paths, shareOfVisible: false }
|
||||
}
|
||||
const { services: destNodes, edges: destEdges, paths: destPaths, shareOfVisible } = inMapScope(initialDestNodes, initialDestEdges, rawPaths)
|
||||
const destinationShareLabel = shareOfVisible ? "трафика показанных назначений" : "трафика окна"
|
||||
const countryGroup = destMode === "countries" ? mapCountryServiceGroups.find(group => group.countryId === expandedCountryId) : undefined
|
||||
const expandedCountryGroup = countryGroup && splitIx && isolatedIx.size > 0 ? (() => {
|
||||
const paths = countryGroup.paths.filter(path => topologyIds.has(path.enId || path.viaId))
|
||||
@@ -1550,10 +1575,17 @@ function NetworkMapContent() {
|
||||
const result = scopeMapDestinations(countryGroup.services, edges, paths, () => true)
|
||||
return { countryId: countryGroup.countryId, ...result }
|
||||
})() : countryGroup
|
||||
const countryShareOfVisible = Boolean(expandedCountryGroup && "shareOfVisible" in expandedCountryGroup && expandedCountryGroup.shareOfVisible)
|
||||
const nestedServices = useMemo(() => expandedCountryGroup?.services ?? [], [expandedCountryGroup])
|
||||
const activeServiceId = selectedService?.id ?? linkedService
|
||||
const selectedNestedService = nestedServices.find(service => service.id === activeServiceId)
|
||||
const activeService = destNodes.find(service => service.id === activeServiceId) ?? selectedNestedService ?? null
|
||||
const historyWindowSec = scopeUser ? history?.data?.windowSec : mapWindowSec
|
||||
const networkHistory = flowReadAt && !flowError ? {services: mapServices, serviceEdges: mapServiceEdges, servicePaths: mapServicePaths} : undefined
|
||||
const serviceHistory = scopeUser ? (history?.error ? undefined : history?.data) : networkHistory
|
||||
const archivedService = liveServiceView && activeService && serviceHistory
|
||||
? inMapScope(serviceHistory.services, serviceHistory.serviceEdges, serviceHistory.servicePaths).services.find(row => row.id === activeService.id)
|
||||
: undefined
|
||||
const liveSelectedService = activeService
|
||||
const expandedCountry = destNodes.find(service => service.id === expandedCountryId)
|
||||
const minorServices = destMode === "services" ? destNodes.filter(service => service.share <= 0.1) : []
|
||||
@@ -1586,14 +1618,16 @@ function NetworkMapContent() {
|
||||
|
||||
const autoServicePos = placeServiceNodes(
|
||||
[...mainServices.map((s) => s.id), ...(hasMinorServices ? ["minor-services"] : [])],
|
||||
mapServers
|
||||
nodes
|
||||
.filter((s) => s.type === "exit-node")
|
||||
.map((s) => nodePosById[s.id])
|
||||
.filter((p): p is { x: number; y: number } => Boolean(p)),
|
||||
)
|
||||
// Раскрытая страна: колонка стран уходит влево, правый x занимает столбец её сервисов.
|
||||
const countryColShift = expandedCountryGroup ? SERVICE_COL_W : 0
|
||||
const autoDestPos = Object.fromEntries(Object.entries(autoServicePos).map(([id, p]) => [id, { x: p.x - countryColShift - compactLanes, y: p.y }]))
|
||||
const emptyExitShift = destMode === "services" && nodes.some(node => node.type === "jump-host")
|
||||
&& !nodes.some(node => node.type === "exit-node" || node.type === "ix-node") ? 100 : 0
|
||||
const autoDestPos = Object.fromEntries(Object.entries(autoServicePos).map(([id, p]) => [id, { x: p.x - countryColShift - compactLanes - emptyExitShift, y: p.y }]))
|
||||
const minorPosition = autoDestPos["minor-services"]
|
||||
if (minorPosition && showSmallServices) for (const [index, service] of groupedServices.entries()) {
|
||||
autoDestPos[service.id] = { x: minorPosition.x, y: minorPosition.y + (index + 1) * (MAP_SERVICE_NODE_H + 10) }
|
||||
@@ -1725,7 +1759,7 @@ function NetworkMapContent() {
|
||||
const {pan:{x:fitX,y:fitY},zoom:fitZoom}=fitNetworkMapCamera([...nodes,...homeRouters.filter(router => onMap(router.id)).flatMap(router => effectiveSatPos[router.id] ?? []),...(showUsers && usersInTopology.length ? [accessPosition] : []),...(minorPosition ? [minorPosition] : []),...Object.values(servicePosById).map(p=>({x:p.x+(expandedCountryGroup?MAP_SERVICE_COMPACT_W:MAP_SERVICE_NODE_W)/2-100,y:p.y})),...Object.values(nestedPosById).map(p=>({x:p.x+MAP_SERVICE_COMPACT_W/2-100,y:p.y}))],fitWidth,viewportHeight,overlayReserve)
|
||||
function fitView(){setPan({x:fitX,y:fitY});setZoom(fitZoom)}
|
||||
useEffect(()=>{if(initialFit.current||!canvasMeasured||!mapServers.length)return;initialFit.current=true;queueMicrotask(()=>{setPan({x:fitX,y:fitY});setZoom(fitZoom)})},[canvasMeasured,mapServers.length,fitX,fitY,fitZoom])
|
||||
const viewKey = `${ixOnly}:${pickedUser?.id ?? ""}:${filteredServiceId ?? ""}:${showSmallServices}:${splitIx}:${fitWidth !== W}:${Boolean(userSnapshot?.data)}:${showUsers && usersInTopology.length > 0}:${Math.round(canvasPx.w)}x${Math.round(canvasPx.h)}`
|
||||
const viewKey = `${ixOnly}:${pickedUser?.id ?? ""}:${filteredServiceId ?? ""}:${showSmallServices}:${splitIx}:${fitWidth !== W}:${Boolean(recent?.data)}:${showUsers && usersInTopology.length > 0}:${Math.round(canvasPx.w)}x${Math.round(canvasPx.h)}`
|
||||
const lastViewKey = useRef(viewKey)
|
||||
const lastUserView = useRef(pickedUser?.id)
|
||||
useEffect(() => {
|
||||
@@ -2113,7 +2147,7 @@ function NetworkMapContent() {
|
||||
name: `${lead.e.fromServer.name} → ${lead.e.toServer.name}`,
|
||||
}]
|
||||
})
|
||||
const wanLinks = visibleWanJhEdges.flatMap((edge) => {
|
||||
const wanLinks = (showAuxLinks ? visibleWanJhEdges : []).flatMap((edge) => {
|
||||
const jh = nodeById[edge.jhId], sat = effectiveSatPos[edge.homeId]?.[edge.wanIdx]
|
||||
if (!jh || !sat || !onMap(edge.homeId)) return []
|
||||
const key = wanJhEdgeMapKey(edge)
|
||||
@@ -2141,10 +2175,10 @@ function NetworkMapContent() {
|
||||
if (!target || !isVisible(target)) return []
|
||||
const bindings = pickedUser?.bindings.filter(binding => binding.node === id) ?? []
|
||||
const rate = accessRate(bindings, access.rates)
|
||||
const text = pickedUser ? showNetflow ? rate.label : "" : `${users.length} чел.`
|
||||
const text = pickedUser ? showNetflow && rate.measured ? rate.label : "" : `${users.length} чел.`
|
||||
const link = mapLinkPath(accessPosition, MAP_CARD_W / 2, target, MAP_CARD_W / 2)
|
||||
return [{ id: `access:${id}`, link, texts: [text], name: `${pickedUser?.name ?? "Пользователи"} → ${target.name}`, opacity: bindings.length && bindings.every(binding => binding.enabled === false) ? 0.48 : 1,
|
||||
tone: "fg" as const, hint: pickedUser ? `${rate.measured}/${rate.total} замеров · ${bindings.map(binding => binding.kind).join(", ")}` : "Привязки из каталога пользователей",
|
||||
tone: "fg" as const, hint: pickedUser ? `RouterOS · RX ${fmtRate(rate.measured ? rate.rx : null)} · TX ${fmtRate(rate.measured ? rate.tx : null)} · ${rate.measured}/${rate.total} замеров` : "Привязки из каталога пользователей",
|
||||
open: () => { if (pickedUser) { setSelected(null); setSelectedGreEdge(null); setSelectedService(null); setInspectUser(true) } else setUserPicker(true) },
|
||||
}]
|
||||
})
|
||||
@@ -2164,11 +2198,13 @@ function NetworkMapContent() {
|
||||
const from = nodeById[edge.fromId], to = servicePosById[edge.toId]
|
||||
if (!from || !to) return []
|
||||
const direct = edge.observedOnly || from.type === "jump-host" || from.type === "home-router"
|
||||
const detour = direct ? mapObservationRoute({ x: from.x + MAP_CARD_W / 2, y: from.y }, { x: to.x - destHalfW, y: to.y }, mapObstacles, observationTracks) : null
|
||||
if (direct && !showAuxLinks) return []
|
||||
const link = mapLinkPath(from, MAP_CARD_W / 2, to, destHalfW)
|
||||
const detour = direct ? mapObservationRoute(link, mapObstacles, observationTracks) : null
|
||||
if (detour) observationTracks.push(detour.track)
|
||||
return [{ edge, direct, detour, link: mapLinkPath(from, MAP_CARD_W / 2, to, destHalfW) }]
|
||||
return [{ edge, direct, detour, link }]
|
||||
})
|
||||
const observationMarkers = destRibbons.flatMap(({ edge, detour }) => edge.observedOnly && detour ? [{ x: detour.marker.x - 17, y: detour.marker.y - 7, w: 34, h: 14 }] : [])
|
||||
const observationMarkers = destRibbons.flatMap(({ edge, detour }) => edge.observedOnly && detour?.marker ? [{ x: detour.marker.x - 17, y: detour.marker.y - 7, w: 34, h: 14 }] : [])
|
||||
const linkLabels = placeMapLinkLabels([...accessLinks.filter(link => link.texts[0]), ...greLabels, ...wanLabels], [...mapObstacles, ...observationMarkers])
|
||||
const nestedRibbons = mapRibbons((expandedCountryGroup?.edges ?? []).flatMap((edge) => {
|
||||
const from = servicePosById[edge.fromId], to = nestedPosById[edge.toId]
|
||||
@@ -2186,7 +2222,6 @@ function NetworkMapContent() {
|
||||
return { id: e.id, ts: eventsAt - (m ? Number(m[1]) * unitMs[m[2]] : 0), ...eventTone(e.sev === "destructive" ? "critical" : e.sev), title: e.title, message: e.message }
|
||||
})
|
||||
).filter(e => Number.isFinite(e.ts)).sort((a, b) => b.ts - a.ts)
|
||||
const filterService = initialDestNodes.find(service => service.id === filteredServiceId) ?? (liveSelectedService?.id === filteredServiceId ? liveSelectedService : null)
|
||||
const tablePaths = filterService ? (selectedNestedService ? expandedCountryGroup?.paths ?? [] : destPaths).filter(p => p.serviceId === filterService.id) : destPaths
|
||||
const flowRows = [...tablePaths].sort((a, b) => b.bps - a.bps).slice(0, 100).map(p => ({
|
||||
id: servicePathKey(p),
|
||||
@@ -2226,9 +2261,9 @@ function NetworkMapContent() {
|
||||
const recentIncidents = eventRows.filter(event => (event.tone === "er" || event.tone === "wn") && event.ts >= eventsAt - 86_400_000)
|
||||
const mapHeadSub = (
|
||||
<>
|
||||
<span title={readAt ? `Снимок API ${new Date(readAt).toLocaleTimeString("ru-RU")}` : undefined}>{useLiveData ? (readAt ? "Текущий срез" : "Данные карты неизвестны") : "Демонстрационные данные"}</span>
|
||||
<span title={readAt ? `Снимок API ${new Date(readAt).toLocaleTimeString("ru-RU")}` : undefined}>{useLiveData ? (readAt ? "Снимок сети" : "Данные карты неизвестны") : "Демонстрационные данные"}</span>
|
||||
{" · "}<span>{nodes.length} {ruPlural(nodes.length, "узел", "узла", "узлов")} · {mapLinkCount} {ruPlural(mapLinkCount, "связь", "связи", "связей")}</span>
|
||||
{useLiveData && (showNetflow || showServices) && <>{" · "}{flowReadAt ? <span title={`NetFlow · ${mapWindow}${mapWindowSec >= 120 && mapWindowSec < 300 ? " из 5 запрошенных" : ""} · ответ ${new Date(flowReadAt).toLocaleTimeString("ru-RU")} · ${flowListener ? "приёмник включён" : "приёмник выключен"}`}>IPFIX · {mapWindow}{!flowListener ? " · приёмник выключен" : ""}</span> : <span>Данные NetFlow неизвестны</span>}</>}
|
||||
{useLiveData && (showNetflow || showServices) && <>{" · "}{destinationReadAt ? <span title={`NetFlow · ${destinationWindow}${!liveServiceView && destinationWindowSec < 300 ? " из 5 запрошенных" : ""} · средняя скорость по принятым записям IPFIX · ответ ${new Date(destinationReadAt).toLocaleTimeString("ru-RU")}`}>IPFIX · среднее за {destinationWindow}{!destinationListener ? " · приёмник выключен" : ""}</span> : <span>Данные NetFlow неизвестны</span>}</>}
|
||||
</>
|
||||
)
|
||||
// Подсказки поиска макета: узлы и назначения текущего снимка.
|
||||
@@ -2238,8 +2273,10 @@ function NetworkMapContent() {
|
||||
...(showServices ? destNodes : []).filter((d) => !sq || destDisplayLabel(d, destMode).toLowerCase().includes(sq)).map((d) => ({ key: "d:" + d.id, label: destDisplayLabel(d, destMode), sub: `${destMode === "countries" ? "Страна" : d.category || "Сервис"} · ${formatNetflowRate({ bps: d.bps })}`, dot: "var(--chart-4)", pick: () => selectService(d) })),
|
||||
].slice(0, 8) : []
|
||||
const statusFilterLabel = ({ online: "Онлайн", degraded: "Внимание", offline: "Оффлайн", unknown: "Неизвестно", "jump-host": "JumpHost", "exit-node": "Exit Node", "home-router": "Home Router" } as Record<string, string>)[filter]
|
||||
const bottomStat = `Окно ${mapWindow}${flowReadAt ? " · " + new Date(flowReadAt).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }) : ""}${filterService && bottomTab === "flows" ? " · фильтр: " + filterService.label : selected || selectedService || selectedGreEdge ? " · строки выбранного объекта подсвечены" : ""}`
|
||||
const refreshBusy = dataLoading || flowLoading && (showNetflow || showServices) || Boolean(useLiveData && scopeUser && showServices && !userSnapshot)
|
||||
const bottomServiceTab = bottomTab === "flows" || bottomTab === "dest"
|
||||
const bottomReadAt = bottomServiceTab ? destinationReadAt : flowReadAt
|
||||
const bottomStat = `Окно ${bottomServiceTab ? destinationWindow : mapWindow}${bottomReadAt ? " · " + new Date(bottomReadAt).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }) : ""}${filterService && bottomTab === "flows" ? " · фильтр: " + filterService.label : selected || selectedService || selectedGreEdge ? " · строки выбранного объекта подсвечены" : ""}`
|
||||
const refreshBusy = dataLoading || flowLoading && (showNetflow || showServices) || requestRecent && recent?.refresh !== flowRefresh
|
||||
const inspectorOpen = detailsOpen
|
||||
function inspectEvent(event: MapEventRow) {
|
||||
setInspectedEvent(event)
|
||||
@@ -2410,7 +2447,7 @@ function NetworkMapContent() {
|
||||
<UsersIcon aria-hidden />{pickedUser?.name ?? (ixOnly ? "Linux-клиенты" : "Пользователи")}
|
||||
</Button>}
|
||||
{pickedUser && <Button type="button" variant="ghost" size="icon-sm" aria-label="Вся схема пользователей" onClick={returnToNetwork}><XIcon /></Button>}
|
||||
{filterService && <Button type="button" variant="outline" size="sm" aria-label={`Сбросить фильтр сервиса ${filterService.label}`} onClick={() => setFilteredServiceId(null)}>{filterService.label}<XIcon aria-hidden /></Button>}
|
||||
{filterService && <Button type="button" variant="outline" size="sm" aria-label={`Сбросить фильтр сервиса ${filterService.label}`} onClick={() => setFilterService(null)}>{filterService.label}<XIcon aria-hidden /></Button>}
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => setSummaryOpen(true)}>Сводка сети</Button>
|
||||
<Popover>
|
||||
<PopoverTrigger render={<Button type="button" variant="ghost" size="icon-sm" aria-label="Как читать карту" />}><CircleHelpIcon aria-hidden /></PopoverTrigger>
|
||||
@@ -2420,6 +2457,7 @@ function NetworkMapContent() {
|
||||
<li>Слева выберите пользователя. Карта покажет правее его узлы подключения, выход в интернет и сервисы.</li>
|
||||
<li>Откройте узел или линию. Справа появятся источник данных, состояние связи и доступные измерения.</li>
|
||||
<li>Метка IPFIX показывает, где замечен трафик. Дальнейший маршрут для такой линии требует подтверждения.</li>
|
||||
<li>На сервисах показана средняя скорость по сохранённым потокам IPFIX. RX/TX на узлах берутся из счётчиков RouterOS.</li>
|
||||
</ol>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
@@ -2433,6 +2471,7 @@ function NetworkMapContent() {
|
||||
{([
|
||||
{ key: "showPingBadges", label: "RTT на связях", val: showPingBadges, set: setShowPingBadges, hint: "P" },
|
||||
{ key: "showNetflow", label: "Трафик на линиях", val: showNetflow, set: setShowNetflow, hint: "" },
|
||||
{ key: "showAuxLinks", label: "Вспомогательные серые линии", val: showAuxLinks, set: setShowAuxLinks, hint: "" },
|
||||
{ key: "showServices", label: "Назначения", val: showServices, set: setShowServices, hint: "" },
|
||||
{ key: "showUsers", label: ixOnly ? "Linux-клиенты" : "Пользователи", val: showUsers, set: setShowUsers, hint: "" },
|
||||
{ key: "showAnimDots", label: "Анимация трафика", val: showAnimDots, set: setShowAnimDots, hint: "" },
|
||||
@@ -2461,12 +2500,12 @@ function NetworkMapContent() {
|
||||
<NetworkMapLegend compact={Boolean(selected || selectedGreEdge || selectedService || (nodes.length && !nodes.some(isVisible)))} />
|
||||
</FramePanel>
|
||||
|
||||
{(inspectedEvent || userSnapshot?.error) && <FramePanel className="flex flex-col gap-2" aria-label="Разбор события">
|
||||
{(inspectedEvent || recent?.error) && <FramePanel className="flex flex-col gap-2" aria-label="Разбор события">
|
||||
{inspectedEvent && <>
|
||||
<div className="flex items-start justify-between gap-2"><div className="min-w-0"><h2 className="text-sm font-semibold">{inspectedEvent.title}</h2><p className="text-xs text-muted-foreground">{new Date(inspectedEvent.ts).toLocaleString("ru-RU")} · {inspectedEvent.message}</p></div><Button variant="ghost" size="icon-xs" aria-label="Закрыть разбор" onClick={() => setInspectedEvent(null)}><XIcon /></Button></div>
|
||||
{inspectedEvent.serverId && <Link className={buttonVariants({variant:"outline",size:"xs",className:"self-start"})} href={nodeTrafficHref(inspectedEvent.serverId)}>Трафик узла</Link>}
|
||||
</>}
|
||||
{userSnapshot?.error && <p role="status" className="text-xs text-muted-foreground">{userSnapshot.error}. Показаны подтверждённые строки из доступного снимка.</p>}
|
||||
{recent?.error && <p role="status" className="text-xs text-muted-foreground">{recent.error}. {recent.data ? "Показан предыдущий снимок сервисов." : "Скорости сервисов пока недоступны."}</p>}
|
||||
</FramePanel>}
|
||||
|
||||
{/* Состояние данных: загрузка и ошибки снимка, NetFlow и DNS */}
|
||||
@@ -2507,22 +2546,22 @@ function NetworkMapContent() {
|
||||
{/* Background grid */}
|
||||
<rect data-map-background x={pan.x} y={pan.y} width={W/zoom} height={viewportHeight/zoom} fill="url(#map-dots)" />
|
||||
{([
|
||||
...(showUsers && usersInTopology.length ? [{ lane: { x0: accessPosition.x - 96 + compactLanes, x1: accessPosition.x + 96 + compactLanes }, label: pickedUser ? "ПОЛЬЗОВАТЕЛЬ" : "ПОДКЛЮЧЕНИЯ" }] : []),
|
||||
...(showUsers && usersInTopology.length ? [{ lane: { x0: accessPosition.x - 96 + compactLanes, x1: accessPosition.x + 96 + compactLanes }, label: "ПОДКЛЮЧЕНИЯ", tint: false }] : []),
|
||||
...(nodes.some(node => node.type === "home-router") ? [
|
||||
{ lane: MAP_LANES.home, label: `ДОМАШНИЕ РОУТЕРЫ · ${nodes.filter(node => node.type === "home-router").length}` },
|
||||
{ lane: MAP_LANES.wan, label: `АПЛИНКИ WAN · ${nodes.reduce((sum, router) => sum + (router.wanUplinks?.length ?? 0), 0)}` },
|
||||
{ lane: MAP_LANES.home, label: `ДОМАШНИЕ РОУТЕРЫ · ${nodes.filter(node => node.type === "home-router").length}`, tint: true },
|
||||
{ lane: MAP_LANES.wan, label: `АПЛИНКИ WAN · ${nodes.reduce((sum, router) => sum + (router.wanUplinks?.length ?? 0), 0)}`, tint: false },
|
||||
] : []),
|
||||
...(!ixOnly && nodes.some(node => node.type === "jump-host") ? [{ lane: MAP_LANES.jh, label: `УЗЛЫ ДОСТУПА · ${nodes.filter(server => server.type === "jump-host").length}` }] : []),
|
||||
...(nodes.some(node => node.type === "exit-node" || node.type === "ix-node") ? [{ lane: MAP_LANES.en, label: ixOnly ? `IX · ${nodes.length}` : `ИНТЕРНЕТ-ВЫХОДЫ · ${nodes.filter(server => server.type === "exit-node").length}${nodes.some(server => server.type === "ix-node") ? ` · IX · ${nodes.filter(server => server.type === "ix-node").length}` : ""}` }] : []),
|
||||
...(visibleMapServices.length ? [{ lane: MAP_LANES.dest, label: `${destMode === "countries" ? "СТРАНЫ" : "СЕРВИСЫ"} · ${visibleMapServices.length}` }] : []),
|
||||
]).map(({ lane, label }, i) => (
|
||||
<g key={label} aria-hidden="true" pointerEvents="none" transform={`translate(${-compactLanes},0)`}>
|
||||
<rect x={lane.x0} y={lanesTop} width={lane.x1 - lane.x0} height={lanesBottom - lanesTop} fill="var(--foreground)" fillOpacity={i % 2 ? 0.035 : 0} />
|
||||
...(!ixOnly && nodes.some(node => node.type === "jump-host") ? [{ lane: MAP_LANES.jh, label: `УЗЛЫ ДОСТУПА · ${nodes.filter(server => server.type === "jump-host").length}`, tint: true }] : []),
|
||||
...(nodes.some(node => node.type === "exit-node" || node.type === "ix-node") ? [{ lane: MAP_LANES.en, label: ixOnly ? `IX · ${nodes.length}` : `ИНТЕРНЕТ-ВЫХОДЫ · ${nodes.filter(server => server.type === "exit-node").length}${nodes.some(server => server.type === "ix-node") ? ` · IX · ${nodes.filter(server => server.type === "ix-node").length}` : ""}`, tint: false }] : []),
|
||||
...(visibleMapServices.length ? [{ lane: MAP_LANES.dest, label: `${destMode === "countries" ? "СТРАНЫ" : "СЕРВИСЫ"} · ${visibleMapServices.length}`, tint: true, shift: emptyExitShift }] : []),
|
||||
]).map(({ lane, label, tint, shift }) => (
|
||||
<g key={label} aria-hidden="true" pointerEvents="none" transform={`translate(${-compactLanes - (shift ?? 0)},0)`}>
|
||||
<rect x={lane.x0} y={lanesTop} width={lane.x1 - lane.x0} height={lanesBottom - lanesTop} fill="var(--foreground)" fillOpacity={tint ? 0.035 : 0} />
|
||||
<text x={(lane.x0 + lane.x1) / 2} y={lanesTop + 18} textAnchor="middle" fill="var(--muted-foreground)" fontSize="12" fontWeight="600" fontFamily="Geist,sans-serif">{label}</text>
|
||||
</g>
|
||||
))}
|
||||
|
||||
{accessLinks.map(({ id, link, name, open, opacity }) => <path key={id} d={link.d} fill="none" stroke="var(--chart-2)" strokeWidth={pickedUser ? 2.5 : 1.5} opacity={opacity * (pickedUser ? 0.9 : 0.6)} pointerEvents="stroke" onPointerDown={e => e.stopPropagation()} onClick={open}><title>{name}</title></path>)}
|
||||
{accessLinks.map(({ id, link, name, open, opacity }) => <path key={id} d={link.d} fill="none" stroke="var(--chart-2)" strokeWidth="1.5" opacity={opacity * 0.75} pointerEvents="stroke" onPointerDown={e => e.stopPropagation()} onClick={open}><title>{name}</title></path>)}
|
||||
{/* Наблюдаемые пути от выходов и экспортёров к сервисам. */}
|
||||
{destRibbons.map(({ edge, direct, detour, link }) => {
|
||||
const hop = destinationRate(edge)
|
||||
@@ -2530,7 +2569,7 @@ function NetworkMapContent() {
|
||||
const pathHit = Boolean(highlightedPath && (highlightedPath.enId || highlightedPath.viaId) === edge.fromId && selectedDestinationId === edge.toId)
|
||||
const hl = pathHit || (!highlightedPath && (activeService?.id === edge.toId || selected?.id === edge.fromId || expandedCountryId === edge.toId || filteredServiceId === edge.toId))
|
||||
const countryDim = !hl && Boolean(expandedCountryGroup) && edge.toId !== expandedCountryId
|
||||
const d = direct ? detour?.d : link.d
|
||||
const d = detour?.d ?? link.d
|
||||
const svc = visibleMapServices.find((s) => s.id === edge.toId)
|
||||
const enName = mapServers.find((s) => s.id === edge.fromId)?.name ?? edge.fromId
|
||||
const clientLabel = edge.clients?.map((c) => c.name).filter(Boolean).join(", ") || edge.clientName || "—"
|
||||
@@ -2543,14 +2582,13 @@ function NetworkMapContent() {
|
||||
<title>{edge.observedOnly
|
||||
? `Наблюдение IPFIX · ${enName} → ${destDisplayLabel(svc, destMode, edge.toId)}${rate} · выход не подтверждён`
|
||||
: `${clientLabel} → ${enName} → ${destDisplayLabel(svc, destMode, edge.toId)}${rate}`}</title>
|
||||
{d && <path data-map-route={direct ? "observation" : "service"} d={d} fill="none" stroke={direct ? "var(--muted-foreground)" : "var(--chart-4)"} strokeLinejoin="round" strokeWidth={hl ? 2.5 : 1.5} />}
|
||||
{d && <path d={d} fill="none" stroke="transparent" strokeWidth="12" />}
|
||||
{edge.observedOnly && detour && <g transform={`translate(${detour.marker.x},${detour.marker.y})`}>
|
||||
<path data-map-route={direct ? "observation" : "service"} d={d} fill="none" stroke={direct ? "var(--muted-foreground)" : "var(--chart-4)"} strokeLinejoin="round" strokeWidth={hl ? 2.5 : 1.5} />
|
||||
<path d={d} fill="none" stroke="transparent" strokeWidth="12" />
|
||||
{edge.observedOnly && detour?.marker && <g transform={`translate(${detour.marker.x},${detour.marker.y})`}>
|
||||
<rect x="-17" y="-7" width="34" height="14" rx="7" fill="var(--card)" stroke="var(--muted-foreground)" />
|
||||
<text textAnchor="middle" y="3.5" fill="var(--foreground)" fontSize="9">IPFIX</text>
|
||||
</g>}
|
||||
{!d && <circle cx={link.x2 - 5} cy={link.y2} r="4" fill="var(--muted-foreground)" />}
|
||||
{d && !direct && showAnimDots && !reducedMotion && hl && hopHasRate(hop) && (
|
||||
{!direct && showAnimDots && !reducedMotion && hl && hopHasRate(hop) && (
|
||||
<circle r="2.5" fill="var(--foreground)" opacity="0.7" pointerEvents="none">
|
||||
<animateMotion dur="2.6s" repeatCount="indefinite" path={d} />
|
||||
</circle>
|
||||
@@ -2612,7 +2650,7 @@ function NetworkMapContent() {
|
||||
</path>
|
||||
})}
|
||||
{/* ── Home Router → WAN satellite connectors ── */}
|
||||
{homeRouters.flatMap(router => {
|
||||
{showAuxLinks && homeRouters.flatMap(router => {
|
||||
const rNode = nodes.find(n => n.id === router.id)
|
||||
if (!rNode) return []
|
||||
return (router.wanUplinks ?? []).map((wan, wIdx) => {
|
||||
@@ -2653,7 +2691,7 @@ function NetworkMapContent() {
|
||||
onClick={() => setUserPicker(true)}
|
||||
onKeyDown={e => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); e.stopPropagation(); setUserPicker(true) } }}>
|
||||
<rect className="network-map-focus-ring" x={-MAP_CARD_W / 2 - 4} y={-MAP_CARD_H / 2 - 4} width={MAP_CARD_W + 8} height={MAP_CARD_H + 8} rx="14" fill="none" stroke="var(--ring)" strokeWidth="2" />
|
||||
<rect x={-MAP_CARD_W / 2} y={-MAP_CARD_H / 2} width={MAP_CARD_W} height={MAP_CARD_H} rx="12" fill="var(--card)" stroke={pickedUser ? "var(--chart-2)" : "var(--border)"} strokeWidth="1.5" />
|
||||
<rect x={-MAP_CARD_W / 2} y={-MAP_CARD_H / 2} width={MAP_CARD_W} height={MAP_CARD_H} rx="12" fill="var(--card)" stroke="var(--border)" strokeWidth="1.5" />
|
||||
<rect x="-70" y="-18" width="36" height="36" rx="8" fill="var(--chart-2)" fillOpacity=".18" />
|
||||
<UsersIcon x="-61" y="-9" width="18" height="18" color="var(--chart-2)" />
|
||||
<text x="-24" y="-3" fill="var(--foreground)" fontSize="12" fontWeight="600">{mapCardName(pickedUser?.name ?? (ixOnly ? "Linux-клиенты" : "Пользователи"), 92).text}</text>
|
||||
@@ -2710,7 +2748,7 @@ function NetworkMapContent() {
|
||||
})}
|
||||
|
||||
{minorPosition && <ServiceNode label={showSmallServices ? "Свернуть остальные" : `Остальные сервисы (${groupedServices.length})`} share={groupedServices.reduce((sum, service) => sum + service.share, 0)} category={showSmallServices ? `${groupedServices.length} в группе` : "Доля каждого ≤ 10%"}
|
||||
x={minorPosition.x} y={minorPosition.y} destMode="services" expanded={showSmallServices} isSel={false} isVis isDragged={false} onPointerDown={() => {}} onClick={() => setShowSmallServices(value => !value)} />}
|
||||
x={minorPosition.x} y={minorPosition.y} destMode="services" shareLabel={destinationShareLabel} expanded={showSmallServices} isSel={false} isVis isDragged={false} onPointerDown={() => {}} onClick={() => setShowSmallServices(value => !value)} />}
|
||||
{visibleMapServices.map((svc) => {
|
||||
const pos = servicePosById[svc.id]
|
||||
if (!pos) return null
|
||||
@@ -2719,7 +2757,8 @@ function NetworkMapContent() {
|
||||
key={svc.id}
|
||||
label={destDisplayLabel(svc, destMode)}
|
||||
share={svc.share}
|
||||
category={destMode === "countries" ? "Страна" : svc.category}
|
||||
shareLabel={destinationShareLabel}
|
||||
category={destMode === "countries" ? "Страна" : serviceMapSubtitle(svc)}
|
||||
rate={formatNetflowRate({ bytes: svc.bytes, bps: svc.bps, bpsFwd: svc.bps, bpsRev: 0 })}
|
||||
compact={Boolean(expandedCountryGroup)}
|
||||
x={pos.x}
|
||||
@@ -2761,7 +2800,7 @@ function NetworkMapContent() {
|
||||
isVis
|
||||
isDragged={draggedSvcId === svc.id}
|
||||
destMode="services"
|
||||
shareLabel="трафика страны"
|
||||
shareLabel={countryShareOfVisible ? "трафика показанных сервисов страны" : "трафика страны"}
|
||||
onPointerDown={(e) => onServicePointerDown(e, svc.id, pos.x, pos.y)}
|
||||
onClick={() => {
|
||||
if (suppressClickRef.current) { suppressClickRef.current = false; return }
|
||||
@@ -2854,7 +2893,7 @@ function NetworkMapContent() {
|
||||
<FramePanel className="flex min-h-0 flex-1 flex-col overflow-hidden p-0">
|
||||
{inspectorOpen && (
|
||||
<div role="complementary" aria-label="Детали объекта карты" className="flex flex-1 flex-col overflow-hidden bg-card w-full min-h-0 min-w-0">
|
||||
{userDetailsOpen && pickedUser ? <MapUserDetails user={pickedUser} groups={pickedBindings} paths={destPaths} services={destNodes} rates={access.rates} windowLabel={mapWindow}
|
||||
{userDetailsOpen && pickedUser ? <MapUserDetails user={pickedUser} groups={pickedBindings} paths={destPaths} services={destNodes} rates={access.rates} userRate={access.userRate} windowLabel={destinationWindow}
|
||||
onClose={() => { setInspectUser(false); returnToMapControl() }} onService={selectService} nodeName={id => nodeById[id]?.name ?? id}
|
||||
trafficHref={pickedUser.linux ? "/ix" : `/traffic?${new URLSearchParams({user:pickedUser.id,from:"map"})}`} /> : selectedGreEdge ? (
|
||||
<>
|
||||
@@ -3063,17 +3102,19 @@ function NetworkMapContent() {
|
||||
</div>
|
||||
</>
|
||||
) : activeService && (destMode === "services" || selectedNestedService) ? (
|
||||
<ServiceInspector key={activeService.id} service={activeService}
|
||||
<ServiceInspector key={JSON.stringify([pickedUserId, ixOnly, activeService.id])} service={activeService}
|
||||
paths={selectedDestPaths}
|
||||
exits={selectedNestedService ? [] : selectedDestEdges}
|
||||
exitName={id => mapServers.find(s => s.id === id)?.name ?? id}
|
||||
country={selectedNestedService ? expandedCountry?.label : undefined}
|
||||
base={useLiveData ? backendUrl : null} refresh={flowRefresh} windowLabel={mapWindow} flowAt={flowReadAt} stale={Boolean(flowError)}
|
||||
shareOfVisible={selectedNestedService ? countryShareOfVisible : shareOfVisible}
|
||||
base={useLiveData ? backendUrl : null} refresh={flowRefresh} windowLabel={destinationWindow} flowAt={destinationReadAt} stale={Boolean(liveServiceView ? recent?.error : flowError)}
|
||||
history={liveServiceView ? {service: archivedService, window: formatMapFlowWindow(historyWindowSec ?? 300)} : undefined}
|
||||
activePath={highlightedPath} onPath={togglePathHighlight}
|
||||
onClose={() => { setSelectedService(null); updateUrl({service:null}); returnToMapControl() }}
|
||||
userId={pickedUser?.id} ix={ixOnly} topology={ixOnly || splitIx && isolatedIx.size > 0 ? topologyIds : undefined}
|
||||
filtered={filterService?.id === activeService.id} onFilter={() => {
|
||||
setFilteredServiceId(filterService?.id === activeService.id ? null : activeService.id)
|
||||
setFilterService(filterService?.id === activeService.id ? null : {id: activeService.id, label: activeService.label})
|
||||
setBottomTab("flows")
|
||||
setAnalysisOpen(true)
|
||||
}}
|
||||
@@ -3106,23 +3147,23 @@ function NetworkMapContent() {
|
||||
<div className="flex-1 min-h-0 overflow-y-auto px-4 py-4 flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-0">
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">Доля окна</span>
|
||||
<span className="text-xs text-muted-foreground">Доля {destinationShareLabel}</span>
|
||||
<span className="text-xs font-mono font-medium text-cyan-400">{serviceSharePct(liveSelectedService.share)}</span>
|
||||
</div>
|
||||
{mapTotalBytes > 0 && (
|
||||
{destinationTotalBytes !== undefined && destinationTotalBytes > 0 && destinationNamedBytes !== undefined && (
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">Распознаны сервисы</span>
|
||||
<span className="text-xs font-mono font-medium text-cyan-400">
|
||||
{formatNetflowRate({
|
||||
bytes: mapNamedBytes,
|
||||
bps: (mapNamedBytes * 8) / Math.max(1, mapWindowSec),
|
||||
bytes: destinationNamedBytes,
|
||||
bps: (destinationNamedBytes * 8) / destinationWindowSec,
|
||||
bpsFwd: 0,
|
||||
bpsRev: 0,
|
||||
})}
|
||||
{" из "}
|
||||
{formatNetflowRate({
|
||||
bytes: mapTotalBytes,
|
||||
bps: (mapTotalBytes * 8) / Math.max(1, mapWindowSec),
|
||||
bytes: destinationTotalBytes,
|
||||
bps: (destinationTotalBytes * 8) / destinationWindowSec,
|
||||
bpsFwd: 0,
|
||||
bpsRev: 0,
|
||||
})}
|
||||
@@ -3153,7 +3194,7 @@ function NetworkMapContent() {
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<InspectorUsers users={serviceUsers(liveSelectedService, selectedDestPaths)} windowLabel={mapWindow} />
|
||||
<InspectorUsers users={serviceUsers(liveSelectedService, selectedDestPaths)} windowLabel={destinationWindow} />
|
||||
{expandedCountryGroup && liveSelectedService.id === expandedCountryGroup.countryId && (
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground mb-2">Сервисы в стране</p>
|
||||
|
||||
+29
-13
@@ -955,17 +955,32 @@ function TrafficContent({ view, user, server, service, country, exporters: mapEx
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLive || groupMode === "flows") return
|
||||
let cancelled = false
|
||||
const loadLiveTraffic = async (targetRange: Range) => {
|
||||
const key = JSON.stringify([isLive, backendUrl, targetRange, groupMode, trafficRetry])
|
||||
const controller = new AbortController()
|
||||
const init = { signal: controller.signal }
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
const q = encodeURIComponent(range === "30d" ? "24h" : range)
|
||||
async function refreshUsers() {
|
||||
try {
|
||||
const { users } = await apiFetch<{ users: UserTraffic[] }>(`/api/traffic/users?range=${q}`, init)
|
||||
if (!controller.signal.aborted) {
|
||||
setLiveUsers(users.map(toLiveUser))
|
||||
const receivedAt = Date.now()
|
||||
setTrafficState(state => state?.key === trafficKey ? {...state, receivedAt} : state)
|
||||
}
|
||||
} catch {
|
||||
// Keep the last valid observation until its own expiry.
|
||||
} finally {
|
||||
if (!controller.signal.aborted) timer = setTimeout(() => { void refreshUsers() }, 15_000)
|
||||
}
|
||||
}
|
||||
const loadLiveTraffic = async () => {
|
||||
try {
|
||||
const q = encodeURIComponent(targetRange === "30d" ? "24h" : targetRange)
|
||||
const [srvRes, usersRes, ifacesRes] = await Promise.all([
|
||||
apiFetch<{ servers: LiveTrafficServer[]; peaks?: { rx: number | null; tx: number | null } }>(`/api/traffic/servers?range=${q}`),
|
||||
apiFetch<{ users: UserTraffic[] }>(`/api/traffic/users?range=${q}`),
|
||||
apiFetch<{ interfaces: BoundIfaceTraffic[] }>(`/api/traffic/bound-interfaces?range=${q}`),
|
||||
apiFetch<{ servers: LiveTrafficServer[]; peaks?: { rx: number | null; tx: number | null } }>(`/api/traffic/servers?range=${q}`, init),
|
||||
apiFetch<{ users: UserTraffic[] }>(`/api/traffic/users?range=${q}`, init),
|
||||
apiFetch<{ interfaces: BoundIfaceTraffic[] }>(`/api/traffic/bound-interfaces?range=${q}`, init),
|
||||
])
|
||||
if (cancelled) return
|
||||
if (controller.signal.aborted) return
|
||||
const liveIfaces = ifacesRes.interfaces.map(toLiveBound)
|
||||
const mapped: ServerTraffic[] = srvRes.servers.map((s) => {
|
||||
const base = toLiveServer(s)
|
||||
@@ -976,7 +991,8 @@ function TrafficContent({ view, user, server, service, country, exporters: mapEx
|
||||
setLiveServerOwner(JSON.stringify([isLive, backendUrl]))
|
||||
setLiveUsers(mappedUsers)
|
||||
setLiveBoundIfaces(liveIfaces)
|
||||
setTrafficState({ key, status: "ready", receivedAt: Date.now(), peaks: srvRes.peaks })
|
||||
setTrafficState({ key: trafficKey, status: "ready", receivedAt: Date.now(), peaks: srvRes.peaks })
|
||||
if (groupMode === "users") timer = setTimeout(() => { void refreshUsers() }, 15_000)
|
||||
setSelectedId((prev) => {
|
||||
if (groupMode === view && prev === linkedId) return prev
|
||||
if (groupMode === "users") return mappedUsers.some((x) => x.id === prev) ? prev : (mappedUsers[0]?.id ?? "")
|
||||
@@ -984,12 +1000,12 @@ function TrafficContent({ view, user, server, service, country, exporters: mapEx
|
||||
return mapped.some((x) => x.id === prev) ? prev : (mapped[0]?.id ?? "")
|
||||
})
|
||||
} catch (e) {
|
||||
if (!cancelled) setTrafficState({ key, status: "error", error: e instanceof Error ? e.message : "Не удалось загрузить трафик" })
|
||||
if (!controller.signal.aborted) setTrafficState({ key: trafficKey, status: "error", error: e instanceof Error ? e.message : "Не удалось загрузить трафик" })
|
||||
}
|
||||
}
|
||||
void loadLiveTraffic(range)
|
||||
return () => { cancelled = true }
|
||||
}, [apiFetch, isLive, groupMode, backendUrl, trafficRetry, range, view, linkedId])
|
||||
void loadLiveTraffic()
|
||||
return () => { controller.abort(); clearTimeout(timer) }
|
||||
}, [apiFetch, isLive, groupMode, backendUrl, trafficKey, range, view, linkedId])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLive || groupMode !== "flows" || range === "30d") return
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
"test:mcp:module-completion": "tsx src/services/ipsec-server-init-model.test.ts && tsx src/modules/mcp/ipsec-server-init-actions.test.ts && tsx src/services/wireguard-revision-restore.test.ts && tsx src/modules/mcp/vrf-ticket-runtime.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-pool-dependencies.test.ts && tsx src/services/vrf-production-transition.test.ts && tsx src/services/vrf-production-action-binding.test.ts && tsx src/services/ipsec-revision-restore-model.test.ts && tsx src/modules/mcp/ipsec-revision-actions.test.ts && tsx src/modules/mcp/service-native-progress.test.ts && tsx src/services/ipsec-revision-restore.test.ts && tsx src/services/ipsec-revision-secret.test.ts",
|
||||
"test:mcp:module-completion:pg": "node scripts/test-mcp-postgres.mjs --module-completion --restore",
|
||||
"test:mcp:pg": "node scripts/test-mcp-postgres.mjs",
|
||||
"test:mcp:network-diagnostics": "node --experimental-test-module-mocks --import tsx --test src/modules/mcp/incident-actions.test.ts src/modules/mcp/network-diagnostic-actions.test.ts src/modules/mcp/resilience-actions.test.ts",
|
||||
"test:mcp:network-diagnostics:pg": "node scripts/test-mcp-postgres.mjs --network-diagnostics",
|
||||
"test:mcp:pg:sharded": "node scripts/test-mcp-postgres-sharded.mjs",
|
||||
"test:mcp:users-bindings:pg": "node scripts/test-mcp-postgres.mjs --users-bindings",
|
||||
"test:mcp:bridge-vlan:pg": "node scripts/test-mcp-postgres.mjs --bridge-vlan-configuration",
|
||||
@@ -46,7 +48,7 @@
|
||||
"test:probes": "npm run test:speed-workflow && tsx src/services/manual-data-collection-execution.test.ts && tsx src/routes/manual-data-collection.test.ts && tsx src/services/network-host-resolution.test.ts && tsx src/routes/probes.test.ts && tsx src/routes/probes.cancel.test.ts && tsx src/services/ping-measurement.test.ts && tsx src/services/uptime-probe-observations.test.ts && tsx src/services/ping-measurement-sql.test.ts",
|
||||
"test:exec": "tsx src/services/mikrotik-logs.test.ts && tsx src/services/terminal-diagnostics.test.ts && tsx src/routes/exec.test.ts && tsx src/plugins/auth.exec.test.ts",
|
||||
"test:auth": "tsx --test src/modules/mcp/routing-manual-inverse-history.test.ts && tsx src/db/application-writer-profile-registry-structure.test.ts && tsx src/db/application-writer-profile-registry-read.test.ts && tsx src/db/application-writer-profile-registry-read-parity.test.ts && tsx src/db/application-writer-profile-format.test.ts && tsx src/plugins/auth-path.test.ts && tsx src/lib/permissions.test.ts && tsx src/plugins/auth-provenance.test.ts && tsx src/services/bandwidth-rest-speed-original.test.ts && tsx src/plugins/auth.smoke.test.ts && tsx src/plugins/auth.ospf-optimizer.test.ts && npm run test:mcp",
|
||||
"test:mcp": "node scripts/vrf-production-profile.test.mjs && node src/services/vrf-production-peer-telemetry.test.mjs && node src/services/vrf-execution-diagnostic.test.mjs && node src/services/vrf-transition-refusal.test.mjs && node src/services/vrf-production-gre-cycle.test.mjs && tsx src/services/vrf-production-gre-link-local.test.ts && tsx src/services/vrf-production-bridge-delete.test.ts && tsx src/services/vrf-production-transition.test.ts && tsx --test src/services/routeros-snapshot-read.test.ts src/services/bridge-vlan-configuration.test.ts src/modules/mcp/bridge-vlan-projection.test.ts src/modules/mcp/vrf-preparation-diagnostic.test.ts && tsx --test src/services/server-poll-error-provenance.test.ts && tsx --test src/modules/mcp/plan-expiry.test.ts src/modules/mcp/result-budget.test.ts src/modules/mcp/result-delivery.test.ts src/modules/mcp/wire-admission.test.ts src/modules/mcp/flow-envelope-allowance.test.ts src/modules/mcp/sdk-terminal-budget.test.ts src/modules/mcp/inflight-owner.test.ts && npm run test:database-source-binding && tsx --test src/modules/mcp/integration-fixture-expiry.test.ts && npm run test:mcp:operation-origin && npm run test:mcp:service-context && npm run test:mcp:operation-locks && tsx --test src/modules/mcp/routing-community-public.test.ts src/modules/mcp/management-transport.test.ts src/modules/mcp/routing-community-context-model.test.ts src/modules/mcp/routing-community-context-native.test.ts ../packages/contracts/src/mcp-routing.test.ts && tsx src/modules/mcp/human-artifact-receipts.test.ts && tsx src/modules/mcp/chr-overlay-readiness.test.ts && tsx src/modules/mcp/chr-recovery-source.test.ts && tsx src/modules/mcp/chr-native-failure.test.ts && tsx src/modules/mcp/ospf-owner-graph.test.ts && tsx src/modules/mcp/routing-measurement-address.test.ts && tsx src/modules/mcp/routing-observation-source.test.ts && tsx src/services/traffic-flow-talkers-model.test.ts && tsx src/services/bgp-prefix-model.test.ts && tsx src/services/vrf-members.test.ts && tsx src/services/routing-gateway-reference.test.ts && tsx src/services/bgp-export-model.test.ts && tsx src/services/traffic-history-model.test.ts && tsx src/services/internet-path-snapshot.test.ts && tsx src/services/internet-path-observation.test.ts && tsx src/modules/mcp/coverage.test.ts && tsx src/modules/mcp/policy.test.ts && tsx src/modules/mcp/events-batch-model.test.ts && tsx src/modules/mcp/operation-revisions.test.ts && tsx src/modules/mcp/native-create-identity.test.ts && tsx src/modules/mcp/ros-step-verification.test.ts && tsx src/modules/mcp/ros-prefix.test.ts && tsx src/modules/mcp/native-conservation-http.test.ts && tsx src/modules/mcp/security.test.ts && tsx src/modules/mcp/state-file-publish.test.ts && tsx src/modules/mcp/routing-model.test.ts && tsx src/modules/mcp/routing-observations-model.test.ts && tsx src/modules/mcp/ospf-health.test.ts && tsx src/modules/mcp/ecmp-preflight.test.ts && tsx src/modules/mcp/recursive-recovery.test.ts && tsx src/modules/mcp/control-path-model.test.ts && tsx src/modules/mcp/routing-community-scoped-model.test.ts && tsx src/modules/mcp/routing-community-scoped-native.test.ts && tsx src/modules/mcp/path-verification.test.ts && tsx src/modules/mcp/database-maintenance.test.ts && tsx src/routes/mcp.test.ts && tsx ../lib/auth-mcp.test.ts && tsx --test src/modules/mcp/routing-controller-fence.test.ts && tsx src/test/chr-vrf-companion-proof.test.ts && tsx src/test/chr-vrf-companion-telemetry.test.ts && tsx src/test/chr-vrf-companion-address-space.test.ts && tsx src/modules/mcp/flow-facts-rebuild-actions.test.ts && tsx src/modules/mcp/ipsec-peer-create-dependencies.test.ts && tsx src/services/ipsec-certificate-update-model.test.ts && tsx src/modules/mcp/ipsec-native-dispatch.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/vrf-production-admission.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/vrf-production-read.test.ts && tsx --test src/services/vrf-production-wireguard-alias.test.ts && tsx src/modules/mcp/ipsec-user-create-actions.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts && tsx src/services/vrf-production-ticket-store.test.ts && npm run test:mcp:routing-baseline",
|
||||
"test:mcp": "node scripts/vrf-production-profile.test.mjs && node src/services/vrf-production-peer-telemetry.test.mjs && node src/services/vrf-execution-diagnostic.test.mjs && node src/services/vrf-transition-refusal.test.mjs && node src/services/vrf-production-gre-cycle.test.mjs && tsx src/services/vrf-production-gre-link-local.test.ts && tsx src/services/vrf-production-bridge-delete.test.ts && tsx src/services/vrf-production-transition.test.ts && tsx --test src/services/routeros-snapshot-read.test.ts src/services/bridge-vlan-configuration.test.ts src/modules/mcp/bridge-vlan-projection.test.ts src/modules/mcp/vrf-preparation-diagnostic.test.ts && tsx --test src/services/server-poll-error-provenance.test.ts && tsx --test src/modules/mcp/plan-expiry.test.ts src/modules/mcp/result-budget.test.ts src/modules/mcp/result-delivery.test.ts src/modules/mcp/wire-admission.test.ts src/modules/mcp/flow-envelope-allowance.test.ts src/modules/mcp/sdk-terminal-budget.test.ts src/modules/mcp/inflight-owner.test.ts && npm run test:database-source-binding && tsx --test src/modules/mcp/integration-fixture-expiry.test.ts && npm run test:mcp:operation-origin && npm run test:mcp:service-context && npm run test:mcp:operation-locks && tsx --test src/modules/mcp/routing-community-public.test.ts src/modules/mcp/management-transport.test.ts src/modules/mcp/routing-community-context-model.test.ts src/modules/mcp/routing-community-context-native.test.ts ../packages/contracts/src/mcp-routing.test.ts && tsx src/modules/mcp/human-artifact-receipts.test.ts && tsx src/modules/mcp/chr-overlay-readiness.test.ts && tsx src/modules/mcp/chr-recovery-source.test.ts && tsx src/modules/mcp/chr-native-failure.test.ts && tsx src/modules/mcp/ospf-owner-graph.test.ts && tsx src/modules/mcp/routing-measurement-address.test.ts && tsx src/modules/mcp/routing-observation-source.test.ts && tsx src/services/traffic-flow-talkers-model.test.ts && tsx src/services/bgp-prefix-model.test.ts && tsx src/services/vrf-members.test.ts && tsx src/services/routing-gateway-reference.test.ts && tsx src/services/bgp-export-model.test.ts && tsx src/services/traffic-history-model.test.ts && tsx src/services/internet-path-snapshot.test.ts && tsx src/services/internet-path-observation.test.ts && tsx src/modules/mcp/coverage.test.ts && tsx src/modules/mcp/policy.test.ts && tsx src/modules/mcp/events-batch-model.test.ts && tsx src/modules/mcp/operation-revisions.test.ts && tsx src/modules/mcp/native-create-identity.test.ts && tsx src/modules/mcp/ros-step-verification.test.ts && tsx src/modules/mcp/ros-prefix.test.ts && tsx src/modules/mcp/native-conservation-http.test.ts && tsx src/modules/mcp/security.test.ts && tsx src/modules/mcp/state-file-publish.test.ts && tsx src/modules/mcp/routing-model.test.ts && tsx src/modules/mcp/routing-observations-model.test.ts && tsx src/modules/mcp/ospf-health.test.ts && tsx src/modules/mcp/ecmp-preflight.test.ts && tsx src/modules/mcp/recursive-recovery.test.ts && tsx src/modules/mcp/control-path-model.test.ts && tsx src/modules/mcp/routing-community-scoped-model.test.ts && tsx src/modules/mcp/routing-community-scoped-native.test.ts && tsx src/modules/mcp/path-verification.test.ts && tsx src/modules/mcp/database-maintenance.test.ts && tsx src/routes/mcp.test.ts && tsx ../lib/auth-mcp.test.ts && tsx --test src/modules/mcp/routing-controller-fence.test.ts && tsx src/test/chr-vrf-companion-proof.test.ts && tsx src/test/chr-vrf-companion-telemetry.test.ts && tsx src/test/chr-vrf-companion-address-space.test.ts && tsx src/modules/mcp/flow-facts-rebuild-actions.test.ts && tsx src/modules/mcp/ipsec-peer-create-dependencies.test.ts && tsx src/services/ipsec-certificate-update-model.test.ts && tsx src/modules/mcp/ipsec-native-dispatch.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/vrf-production-admission.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/vrf-production-read.test.ts && tsx --test src/services/vrf-production-wireguard-alias.test.ts && tsx src/modules/mcp/ipsec-user-create-actions.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts && tsx src/services/vrf-production-ticket-store.test.ts && npm run test:mcp:routing-baseline && npm run test:mcp:network-diagnostics",
|
||||
"test:wireguard": "tsx src/services/mikrotik-response-bounds.test.ts && tsx --test src/services/wireguard-dependency-read.test.ts && tsx src/services/wireguard-interface-update.test.ts && tsx src/services/wireguard-peer-update.test.ts && npx tsx src/services/wireguard-config.test.ts && npx tsx src/services/wireguard-ipv6.test.ts && npx tsx --test src/services/wireguard-import.test.ts src/services/wireguard-import-apply.test.ts src/services/wireguard-import-revision.test.ts src/services/wireguard-delete.test.ts && npx tsx src/routes/wireguard-import.test.ts && tsx src/services/wireguard-interface-create.test.ts && tsx src/services/wireguard-peer-create.test.ts && tsx src/services/wireguard-import-plan.test.ts && tsx src/services/wireguard-import-execution.test.ts && tsx src/modules/mcp/wireguard-import-actions.test.ts && tsx --test src/services/wireguard-export.test.ts",
|
||||
"test:traffic-rate": "tsx src/services/traffic-rate.test.ts && tsx src/services/traffic-observation.test.ts && tsx src/services/traffic-freshness.test.ts && tsx src/services/traffic-live.test.ts && tsx src/services/traffic-observation-sql.test.ts && tsx src/services/traffic-history-sql.test.ts && tsx src/services/traffic-live-sql.test.ts && tsx src/services/traffic-volume-sql.test.ts && tsx src/services/traffic-binding-status.test.ts && tsx src/services/traffic-status-sql.test.ts && tsx src/services/traffic-gap.test.ts && tsx src/services/traffic-identity.test.ts && tsx src/services/traffic-membership.test.ts && tsx src/services/traffic-aggregate-peak.test.ts && tsx src/services/traffic-users-cache.test.ts && tsx src/services/traffic-collection-lock.test.ts && tsx src/services/traffic-concurrency-sql.test.ts",
|
||||
"test:traffic-flow": "tsx --test src/services/traffic-flow-heartbeat.test.ts src/services/traffic-flow-heartbeat-wiring.test.ts src/services/traffic-flow-heartbeat-receiver.test.ts src/services/traffic-flow-ingest-quality.test.ts src/services/traffic-flow-quality-contract.test.ts && tsx src/services/traffic-flow-catalog-read.test.ts && tsx src/routes/traffic-flow-query.test.ts && tsx src/services/traffic-flow-month.test.ts && tsx src/services/traffic-flow-parse.test.ts && tsx src/services/traffic-flow-ipv6-pipeline.test.ts && tsx src/services/traffic-flow-map-exporter.test.ts && tsx src/services/traffic-flow-ifaces.test.ts && tsx src/services/traffic-flow-ifindex.test.ts && tsx src/services/traffic-flow-dedup.test.ts && tsx src/services/traffic-flow-planes.test.ts && tsx src/services/traffic-flow-ip.test.ts && tsx src/services/traffic-flow-dest.test.ts && tsx src/services/traffic-flow-classify.test.ts && tsx src/services/traffic-flow-ripe.test.ts && tsx src/services/traffic-flow-brands.test.ts && tsx src/services/traffic-flow-ingest.test.ts && tsx src/services/traffic-flow-analytics.test.ts && tsx src/services/traffic-flow-map-hops.test.ts && tsx src/services/traffic-flow-purge.test.ts && tsx src/services/geoip-download.test.ts && tsx src/services/traffic-flow-geoip.test.ts && tsx src/services/traffic-flow-fact-accumulator.test.ts && tsx src/services/traffic-flow-facts.test.ts && tsx src/services/traffic-flow-facts-filter.test.ts && tsx src/services/traffic-flow-facts-rebuild.test.ts && tsx src/services/statistics-aggregate.test.ts && tsx src/services/geoip-manual-update.test.ts && tsx src/services/traffic-flow-overlay-model.test.ts && npm run test:traffic-flow:ownership && tsx src/services/traffic-flow-worker-platform.test.ts && tsx src/services/traffic-flow-template-cache.test.ts && tsx --test src/services/traffic-flow-template-lifetime.test.ts && tsx src/services/traffic-flow-protocol-scope.test.ts && npm run test:traffic-flow:read-budget && npm run test:traffic-flow:resource-profile",
|
||||
|
||||
@@ -178,6 +178,8 @@ if (usersBindings && (process.argv.length !== 3 || process.argv[2] !== '--users-
|
||||
const bridgeVlanConfiguration = process.argv.includes('--bridge-vlan-configuration')
|
||||
if (bridgeVlanConfiguration && process.argv.slice(2).some(arg => arg !== '--bridge-vlan-configuration')) throw new Error('Bridge VLAN acceptance requires its own disposable cluster')
|
||||
const applicationAdapters = process.argv.includes('--application-adapters')
|
||||
const networkDiagnostics = process.argv.includes('--network-diagnostics')
|
||||
if (networkDiagnostics && process.argv.length !== 3) throw new Error('Network diagnostics require their own disposable cluster')
|
||||
const scopedRoutingDiagnostics = process.argv.includes('--scoped-routing-diagnostics')
|
||||
const interfaceEventsCompatibility = process.argv.includes('--interface-events-compatibility')
|
||||
const eventsOnly = process.argv.includes('--events-only')
|
||||
@@ -262,7 +264,7 @@ try {
|
||||
await postgres.start()
|
||||
const binaries = await import(`@embedded-postgres/${process.platform === 'win32' ? 'windows' : process.platform}-${process.arch}`)
|
||||
const testPath = [process.env.MMAPP_PG_CLIENT_BIN, dirname(binaries.postgres), process.env.PATH ?? process.env.Path ?? ''].filter(Boolean).join(delimiter)
|
||||
if (!profilesOnly && (restoreQuarantineOnly || process.argv.includes('--restore') || process.env.MMAPP_PG_CLIENT_BIN)) {
|
||||
if (!profilesOnly && !networkDiagnostics && (restoreQuarantineOnly || process.argv.includes('--restore') || process.env.MMAPP_PG_CLIENT_BIN)) {
|
||||
for (const command of ['pg_dump', 'pg_restore']) await new Promise((resolve, reject) => {
|
||||
execFile(command, ['--version'], { env: { ...process.env, PATH: testPath }, windowsHide: true, timeout: 5000, maxBuffer: 4096 }, error => {
|
||||
if (error) reject(new Error(`Restore acceptance requires working ${command}; set MMAPP_PG_CLIENT_BIN to the PostgreSQL client bin directory`))
|
||||
@@ -274,8 +276,9 @@ try {
|
||||
if (regressionOnly) console.log('Selected regression only: primary integration and terminal restore are not run')
|
||||
if (profilesOnly) console.log('Profiles-only regression matrix: primary integration NOT RUN; terminal restore NOT RUN; full acceptance is not claimed')
|
||||
const result = regressionOnly || profilesOnly ? 0 : await new Promise((resolve, reject) => {
|
||||
const child = spawn(process.execPath, pollMemory ? ['--max-old-space-size=192', '--max-semi-space-size=16', fileURLToPath(new URL('../dist-mcp-memory/services/server-poll-memory.owned.test.js', import.meta.url))] : ['--import', 'tsx', ...(flowActiveRebuild ? ['--import', new URL('../src/services/traffic-flow-active-rebuild-preload.mjs', import.meta.url).href] : []), acceptanceShard ? 'src/modules/mcp/acceptance-shard.test.ts' : usersBindings ? 'src/modules/mcp/users-bindings-owned.test.ts' : bridgeVlanConfiguration ? 'src/modules/mcp/bridge-vlan-configuration-http.test.ts' : protocolLimits ? 'src/modules/mcp/protocol-limits.owned.test.ts' : principalSecuritySource ? 'src/modules/mcp/principal-security-source.owned.test.ts' : pollJournalSnapshot ? 'src/services/server-poll-journal-snapshot.owned.test.ts' : pollTerminalArchive ? 'src/services/server-poll-terminal-archive.owned.test.ts' : pollArchiveSchema ? 'src/db/server-poll-terminal-archives.sql.test.ts' : telemetrySettingsConfiguration ? 'src/modules/mcp/telemetry-settings-configuration.owned.test.ts' : routingReservationSchema ? 'src/db/routing-reservation-schema.owned.test.ts' : routingForwardRounds ? 'src/modules/mcp/routing-network-forward-rounds.owned.test.ts' : flowActiveServices ? 'src/services/traffic-flow-active-services.owned.test.ts' : flowActiveRebuild ? 'src/services/traffic-flow-active-rebuild.owned.test.ts' : flowQuality ? 'src/services/traffic-flow-quality.owned.test.ts' : flowWorkerIpc ? 'src/services/traffic-flow-worker-ipc.owned.test.ts' : manualUptime ? 'src/modules/mcp/manual-uptime-http.test.ts' : manualPingGroup ? 'src/modules/mcp/manual-ping-group-http.test.ts' : manualTraffic ? 'src/modules/mcp/manual-traffic-http.test.ts' : manualApiPing ? 'src/modules/mcp/manual-api-ping-http.test.ts' : simpleSpeedChr ? 'src/modules/mcp/simple-speed-chr.test.ts' : simpleSpeed ? 'src/modules/mcp/simple-speed-http.test.ts' : externalPeerMetadata ? 'src/services/bandwidth-external-peer-metadata.sql.test.ts' : operatorPeerMetadata ? 'src/services/bandwidth-operator-metadata.sql.test.ts' : publicRegistryMetadata ? 'src/services/bandwidth-public-registry.sql.test.ts' : operatorDockerSql ? 'src/services/bandwidth-operator-docker-stop.sql.test.ts' : probeOperationRetirement ? 'src/services/server-probe-operation-retirement.owned.test.ts' : ordinaryOperationRetirement ? 'src/modules/mcp/ordinary-operation-retirement.owned.test.ts' : pollOperationRetirement ? 'src/services/server-poll-operation-retirement.owned.test.ts' : mcpOperationOrigin ? 'src/modules/mcp/operation-execution-origin.sql.test.ts' : mcpSpeedOriginal ? 'src/modules/mcp/speed-bandwidth-original.sql.test.ts' : routerConfigurationGuard ? 'src/services/router-configuration-guard.sql.test.ts' : scheduledSpeedOriginal ? 'src/services/bandwidth-scheduled-speed-original.sql.test.ts' : bandwidthSpeedWorkflow ? 'src/services/bandwidth-speed-workflow.sql.test.ts' : restSpeedOriginal ? 'src/services/bandwidth-rest-speed-original.sql.test.ts' : operationLocks ? 'src/services/operation-config-lock-lease.sql.test.ts' : serviceExecutionOrigin ? 'src/modules/mcp/service-execution-origin.sql.test.ts' : bandwidthNodeSource ? 'src/services/bandwidth-node-source.sql.test.ts' : bandwidthExternalRegistry ? 'src/services/bandwidth-external-node-registry.sql.test.ts' : bandwidthNodeRegistry ? 'src/services/bandwidth-node-registry.sql.test.ts' : bandwidthControlSource ? 'src/services/bandwidth-control-source.sql.test.ts' : bandwidthAdmission ? 'src/services/bandwidth-admission.sql.test.ts' : serverPollStorageFresh ? 'src/services/server-poll-storage-fresh.sql.test.ts' : serverPollStorage ? 'src/services/server-poll-storage.sql.test.ts' : probeStorageFresh ? 'src/services/server-probe-storage-fresh.sql.test.ts' : probeLegacyOrphans ? 'src/services/server-probe-legacy-orphans.sql.test.ts' : diagnosticCancelHost ? 'src/modules/mcp/diagnostic-cancellation-storage.sql.test.ts' : ipsecExportHttp ? 'src/modules/mcp/ipsec-existing-certificate-export-http.sql.test.ts' : ipsecExportJournal ? 'src/services/ipsec-existing-certificate-export-rest-journal.sql.test.ts' : migrationDataInventory ? 'src/db/migration-data-inventory.sql.test.ts' : probeStorageHistory ? 'src/services/server-probe-storage-history.sql.test.ts' : probeStorageJournal ? 'src/services/server-probe-storage-journal.sql.test.ts' : controlledSchemaReference ? 'src/db/controlled-schema-reference.sql.test.ts' : controlledMigrations ? 'src/db/controlled-migrations.sql.test.ts' : databaseSchemaControl ? 'src/db/database-schema-control.sql.test.ts' : migrationSchemaInventory ? 'src/db/migration-schema-inventory.sql.test.ts' : routingNetworkNative ? 'src/modules/mcp/routing-network-native.sql.test.ts' : routingReservationRuntime ? 'src/modules/mcp/routing-reservation-runtime.sql.test.ts' : routingReservations ? 'src/modules/mcp/routing-reservation.sql.test.ts' : collectorPartitionWriters ? 'src/services/collector-partition-writes.sql.test.ts' : serverPollDurableLine truncated
|
||||
const child = spawn(process.execPath, pollMemory ? ['--max-old-space-size=192', '--max-semi-space-size=16', fileURLToPath(new URL('../dist-mcp-memory/services/server-poll-memory.owned.test.js', import.meta.url))] : ['--import', 'tsx', ...(flowActiveRebuild ? ['--import', new URL('../src/services/traffic-flow-active-rebuild-preload.mjs', import.meta.url).href] : []), networkDiagnostics ? 'src/modules/mcp/network-diagnostics.owned.test.ts' : acceptanceShard ? 'src/modules/mcp/acceptance-shard.test.ts' : usersBindings ? 'src/modules/mcp/users-bindings-owned.test.ts' : bridgeVlanConfiguration ? 'src/modules/mcp/bridge-vlan-configuration-http.test.ts' : protocolLimits ? 'src/modules/mcp/protocol-limits.owned.test.ts' : principalSecuritySource ? 'src/modules/mcp/principal-security-source.owned.test.ts' : pollJournalSnapshot ? 'src/services/server-poll-journal-snapshot.owned.test.ts' : pollTerminalArchive ? 'src/services/server-poll-terminal-archive.owned.test.ts' : pollArchiveSchema ? 'src/db/server-poll-terminal-archives.sql.test.ts' : telemetrySettingsConfiguration ? 'src/modules/mcp/telemetry-settings-configuration.owned.test.ts' : routingReservationSchema ? 'src/db/routing-reservation-schema.owned.test.ts' : routingForwardRounds ? 'src/modules/mcp/routing-network-forward-rounds.owned.test.ts' : flowActiveServices ? 'src/services/traffic-flow-active-services.owned.test.ts' : flowActiveRebuild ? 'src/services/traffic-flow-active-rebuild.owned.test.ts' : flowQuality ? 'src/services/traffic-flow-quality.owned.test.ts' : flowWorkerIpc ? 'src/services/traffic-flow-worker-ipc.owned.test.ts' : manualUptime ? 'src/modules/mcp/manual-uptime-http.test.ts' : manualPingGroup ? 'src/modules/mcp/manual-ping-group-http.test.ts' : manualTraffic ? 'src/modules/mcp/manual-traffic-http.test.ts' : manualApiPing ? 'src/modules/mcp/manual-api-ping-http.test.ts' : simpleSpeedChr ? 'src/modules/mcp/simple-speed-chr.test.ts' : simpleSpeed ? 'src/modules/mcp/simple-speed-http.test.ts' : externalPeerMetadata ? 'src/services/bandwidth-external-peer-metadata.sql.test.ts' : operatorPeerMetadata ? 'src/services/bandwidth-operator-metadata.sql.test.ts' : publicRegistryMetadata ? 'src/services/bandwidth-public-registry.sql.test.ts' : operatorDockerSql ? 'src/services/bandwidth-operator-docker-stop.sql.test.ts' : probeOperationRetirement ? 'src/services/server-probe-operation-retirement.owned.test.ts' : ordinaryOperationRetirement ? 'src/modules/mcp/ordinary-operation-retirement.owned.test.ts' : pollOperationRetirement ? 'src/services/server-poll-operation-retirement.owned.test.ts' : mcpOperationOrigin ? 'src/modules/mcp/operation-execution-origin.sql.test.ts' : mcpSpeedOriginal ? 'src/modules/mcp/speed-bandwidth-original.sql.test.ts' : routerConfigurationGuard ? 'src/services/router-configuration-guard.sql.test.ts' : scheduledSpeedOriginal ? 'src/services/bandwidth-scheduled-speed-original.sql.test.ts' : bandwidthSpeedWorkflow ? 'src/services/bandwidth-speed-workflow.sql.test.ts' : restSpeedOriginal ? 'src/services/bandwidth-rest-speed-original.sql.test.ts' : operationLocks ? 'src/services/operation-config-lock-lease.sql.test.ts' : serviceExecutionOrigin ? 'src/modules/mcp/service-execution-origin.sql.test.ts' : bandwidthNodeSource ? 'src/services/bandwidth-node-source.sql.test.ts' : bandwidthExternalRegistry ? 'src/services/bandwidth-external-node-registry.sql.test.ts' : bandwidthNodeRegistry ? 'src/services/bandwidth-node-registry.sql.test.ts' : bandwidthControlSource ? 'src/services/bandwidth-control-source.sql.test.ts' : bandwidthAdmission ? 'src/services/bandwidth-admission.sql.test.ts' : serverPollStorageFresh ? 'src/services/server-poll-storage-fresh.sql.test.ts' : serverPollStorage ? 'src/services/server-poll-storage.sql.test.ts' : probeStorageFresh ? 'src/services/server-probe-storage-fresh.sql.test.ts' : probeLegacyOrphans ? 'src/services/server-probe-legacy-orphans.sql.test.ts' : diagnosticCancelHost ? 'src/modules/mcp/diagnostic-cancellation-storage.sql.test.ts' : ipsecExportHttp ? 'src/modules/mcp/ipsec-existing-certificate-export-http.sql.test.ts' : ipsecExportJournal ? 'src/services/ipsec-existing-certificate-export-rest-journal.sql.test.ts' : migrationDataInventory ? 'src/db/migration-data-inventory.sql.test.ts' : probeStorageHistory ? 'src/services/server-probe-storage-history.sql.test.ts' : probeStorageJournal ? 'src/services/server-probe-storage-journal.sql.test.ts' : controlledSchemaReference ? 'src/db/controlled-schema-reference.sql.test.ts' : controlledMigrations ? 'src/db/controlled-migrations.sql.test.ts' : databaseSchemaControl ? 'src/db/database-schema-control.sql.test.ts' : migrationSchemaInventory ? 'src/db/migration-schema-inventory.sql.test.ts' : routingNetworkNative ? 'src/modules/mcp/routing-network-native.sql.test.ts' : routingReservationRuntime ? 'src/modules/mcp/routing-reservation-runtime.sql.test.ts' : routingReservations ? 'src/modules/mcp/routing-reservation.sql.test.ts' : collectorPartitionWriters
Line truncated
|
||||
cwd: pollMemory ? directory : new URL('../', import.meta.url), stdio: 'inherit', env: { ...(pollMemory ? pollMemoryEnvironment : process.env),
|
||||
MMAPP_OWN_NETWORK_DIAGNOSTICS: String(networkDiagnostics),
|
||||
MMAPP_OWN_SKIP_POLL_CAPACITY: String(pollRetirementFocused),
|
||||
MMAPP_OWN_PROTOCOL_LIMITS: String(protocolLimits),
|
||||
MMAPP_OWN_EVENTS_ONLY: String(eventsOnly),
|
||||
@@ -300,7 +303,7 @@ try {
|
||||
})
|
||||
exitCode = result
|
||||
if (result === 0 && restoreQuarantineOnly) console.log('Restore quarantine: focused real PostgreSQL restore scenario complete')
|
||||
else if (result === 0 && !acceptanceShard && !regressionOnly && !profilesOnly && !usersBindings && !bridgeVlanConfiguration && !protocolLimits && !pollMemory && !principalSecuritySource && !pollJournalSnapshot && !pollArchiveSchema && !telemetrySettingsConfiguration && !routingReservationSchema && !routingForwardRounds && !flowActiveServices && !flowActiveRebuild && !flowQuality && !flowWorkerIpc && !manualUptime && !manualPingGroup && !manualTraffic && !manualApiPing && !simpleSpeed && !simpleSpeedChr && !externalPeerMetadata && !operatorPeerMetadata && !publicRegistryMetadata && !operatorDockerSql && !mcpOperationOrigin && !mcpSpeedOriginal && !routerConfigurationGuard && !scheduledSpeedOriginal && !bandwidthSpeedWorkflow && !restSpeedOriginal && !operationLocks && !serviceExecutionOrigin && !bandwidthNodeSource && !bandwidthNodeRegistry && !bandwidthExternalRegistry && !bandwidthControlSource && !bandwidthAdmission && !probeLegacyOrphans && !probeStorageJournal && !probeStorageHistory && !probeJournal && !chr && !flowWrites && !flowRebuild && !flowRebuildMcp && (process.argv.includes('--restore') || process.env.MMAPP_PG_CLIENT_BIN)) {
|
||||
else if (result === 0 && !networkDiagnostics && !acceptanceShard && !regressionOnly && !profilesOnly && !usersBindings && !bridgeVlanConfiguration && !protocolLimits && !pollMemory && !principalSecuritySource && !pollJournalSnapshot && !pollArchiveSchema && !telemetrySettingsConfiguration && !routingReservationSchema && !routingForwardRounds && !flowActiveServices && !flowActiveRebuild && !flowQuality && !flowWorkerIpc && !manualUptime && !manualPingGroup && !manualTraffic && !manualApiPing && !simpleSpeed && !simpleSpeedChr && !externalPeerMetadata && !operatorPeerMetadata && !publicRegistryMetadata && !operatorDockerSql && !mcpOperationOrigin && !mcpSpeedOriginal && !routerConfigurationGuard && !scheduledSpeedOriginal && !bandwidthSpeedWorkflow && !restSpeedOriginal && !operationLocks && !serviceExecutionOrigin && !bandwidthNodeSource && !bandwidthNodeRegistry && !bandwidthExternalRegistry && !bandwidthControlSource && !bandwidthAdmission && !probeLegacyOrphans && !probeStorageJournal && !probeStorageHistory && !probeJournal && !chr && !flowWrites && !flowRebuild && !flowRebuildMcp && (process.argv.includes('--restore') || process.env.MMAPP_PG_CLIENT_BIN)) {
|
||||
exitCode = await new Promise((resolve, reject) => {
|
||||
const child = spawn(process.execPath, ['--import', 'tsx', 'src/modules/mcp/database-restore.test.ts'], {
|
||||
cwd: new URL('../', import.meta.url), stdio: 'inherit', env: { ...process.env,
|
||||
@@ -313,6 +316,7 @@ try {
|
||||
child.once('error', reject); child.once('exit', code => resolve(code ?? 1))
|
||||
})
|
||||
}
|
||||
else if (result === 0 && networkDiagnostics) console.log('Network diagnostics: scoped MCP SDK and disposable PostgreSQL')
|
||||
else if (result === 0 && pollArchiveSchema) console.log('Poll archive schema: owned nonempty40 preservation, numbered41 and structural refusal guards; no positive MCP archive claim')
|
||||
else if (result === 0 && telemetrySettingsConfiguration) console.log('Telemetry settings: genuine MCP/SQL configuration binding, collector metadata tolerated; no native or external sources')
|
||||
else if (result === 0 && routingReservationSchema) console.log('Routing reservation numbered0040: ownSQL fresh/legacy/manual preservation; no READY, backfill, capabilities or public native activation')
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { registerIpsecServerDeleteActions } from "./ipsec-server-delete-actions.js"
|
||||
import { registerCapabilityActions } from "./capability-actions.js"
|
||||
import { registerIncidentActions } from "./incident-actions.js"
|
||||
import { registerNetworkDiagnosticActions } from "./network-diagnostic-actions.js"
|
||||
import { registerResilienceActions } from "./resilience-actions.js"
|
||||
import { registerIpsecServerInitActions } from "./ipsec-server-init-actions.js"
|
||||
import { registerIpsecRevisionActions } from "./ipsec-revision-actions.js"
|
||||
import { registerWireguardRevisionActions } from "./wireguard-revision-actions.js"
|
||||
@@ -30,7 +34,7 @@ import { gatewayReferencesTable, isDynamicRouteInsideTable } from "../../service
|
||||
import { readLogStream } from "../../services/router-logs-query.js"
|
||||
import { subscribeLogDevice } from "../../services/router-logs-collector.js"
|
||||
import { ospfFilterFields, rosResources, readRosSnapshot, resourceById, routerClient, validateRosStep, splitOspfUnsetUpdate } from "./resources.js"
|
||||
import { registerMcpOperation, listMcpOperations } from "./registry.js"
|
||||
import { registerMcpOperation } from "./registry.js"
|
||||
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, MAX_MCP_PUBLIC_ARRAY_ITEMS, MAX_MCP_PUBLIC_STRING_LENGTH, McpError, redact } from "./security.js"
|
||||
import { hasUnattendedPlanAuthority } from "./policy.js"
|
||||
import { effectiveMcpConnection } from "./store.js"
|
||||
@@ -386,9 +390,8 @@ for (const definition of [
|
||||
})
|
||||
}
|
||||
|
||||
add("capabilities.read", "mm_capabilities_get", "Доступные возможности", "mcp", null, "read", "connection", z.object({}).strict(), {
|
||||
read: async (_input, context) => ({ operations: listMcpOperations().filter(operation => operation.implementation === "available" && context.connection.policy.scope.operationIds.includes(operation.id)), schemaVersion: 1 }),
|
||||
})
|
||||
registerCapabilityActions(add)
|
||||
registerIncidentActions(add)
|
||||
add("servers.list", "mm_servers_list", "Серверы", "servers", "mm:servers:read", "read", "servers", z.object({ serverId: serverId.optional(), ...paging }).strict(), {
|
||||
read: async (input, context) => {
|
||||
const ids = typeof input.serverId === "number" ? [input.serverId] : context.connection.policy.scope.serverIds
|
||||
@@ -664,6 +667,8 @@ add("operations.read", "mm_operation_get", "Результат своей опе
|
||||
})
|
||||
|
||||
registerRoutingActions(add)
|
||||
registerNetworkDiagnosticActions(add)
|
||||
registerResilienceActions(add)
|
||||
registerRoutingProfileActions(add)
|
||||
registerRoutingControls(add)
|
||||
registerLifecycleActions(add)
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { z } from "zod"
|
||||
import type { McpPolicyPreviewRequest } from "@mmapp/contracts/mcp"
|
||||
import type { ActionContext } from "./action-types.js"
|
||||
import type { add } from "./actions.js"
|
||||
import { evaluateMcpPolicy } from "./policy.js"
|
||||
import { listMcpOperations } from "./registry.js"
|
||||
|
||||
const identifier = z.string().trim().min(1).max(200).optional()
|
||||
const capabilityInput = z.object({
|
||||
operationId: identifier,
|
||||
toolName: identifier,
|
||||
section: identifier,
|
||||
effect: z.enum(["read", "write", "diagnostic"]).optional(),
|
||||
scope: z.enum(["servers", "global", "connection"]).optional(),
|
||||
serverId: z.number().int().positive().safe().optional(),
|
||||
includeApplicability: z.boolean().optional(),
|
||||
applicable: z.boolean().optional(),
|
||||
}).strict()
|
||||
|
||||
export function readCapabilities(input: z.infer<typeof capabilityInput>, connection: ActionContext["connection"], now = new Date()) {
|
||||
const { policy, owner_permissions: ownerPermissions } = connection
|
||||
const granted = new Set(policy.scope.operationIds)
|
||||
const operations = listMcpOperations().filter(operation =>
|
||||
operation.implementation === "available" && granted.has(operation.id) &&
|
||||
(input.operationId === undefined || operation.id === input.operationId) &&
|
||||
(input.toolName === undefined || operation.toolName === input.toolName) &&
|
||||
(input.section === undefined || operation.section === input.section) &&
|
||||
(input.effect === undefined || operation.effect === input.effect) &&
|
||||
(input.scope === undefined || operation.scope === input.scope) &&
|
||||
(input.serverId === undefined || operation.scope === "servers"))
|
||||
if (!input.includeApplicability && input.serverId === undefined && input.applicable === undefined) return { operations, schemaVersion: 1 }
|
||||
|
||||
const assessed = operations.map(operation => {
|
||||
const serverId = input.serverId ?? policy.scope.serverIds[0]
|
||||
const target: McpPolicyPreviewRequest["target"] | null = operation.scope === "servers"
|
||||
? serverId === undefined ? null : { scope: "servers", serverIds: [serverId] }
|
||||
: { scope: operation.scope }
|
||||
const assessment = target
|
||||
? evaluateMcpPolicy({ operationId: operation.id, policy, ownerPermissions, target, objects: [], protections: [], objectCount: 0,
|
||||
usage: { callsInMinute: 0, concurrentReads: 0, mutationsInHour: 0 }, auditAvailable: true }, now)
|
||||
: { decision: "denied" as const, reasons: [{ code: "SERVER_DENIED", message: "Подключению не выдан доступ к серверам" }] }
|
||||
return { ...operation, applicability: { decision: assessment.decision, reasons: assessment.reasons,
|
||||
serverId: operation.scope === "servers" ? serverId ?? null : null } }
|
||||
})
|
||||
return { operations: assessed.filter(operation => input.applicable === undefined || input.applicable === (operation.applicability.decision !== "denied")),
|
||||
schemaVersion: 1, applicabilityBasis: "effective-policy-before-arguments-and-runtime-checks", observedAt: now.toISOString() }
|
||||
}
|
||||
|
||||
export function registerCapabilityActions(register: typeof add) {
|
||||
register("capabilities.read", "mm_capabilities_get", "Доступные возможности", "mcp", null, "read", "connection", capabilityInput, {
|
||||
read: async (input, context) => readCapabilities(capabilityInput.parse(input), context.connection),
|
||||
})
|
||||
}
|
||||
@@ -42,11 +42,21 @@ export function registerLegacyFlowAnalyticsAction(register: typeof add) {
|
||||
})
|
||||
}
|
||||
|
||||
const flowTupleSchema = z.object({
|
||||
srcIp: z.union([z.ipv4(), z.ipv6()]).optional().describe("Точный IP источника в экспортированной записи"),
|
||||
dstIp: z.union([z.ipv4(), z.ipv6()]).optional().describe("Точный IP назначения в экспортированной записи"),
|
||||
srcPort: z.number().int().min(0).max(65535).optional(),
|
||||
dstPort: z.number().int().min(0).max(65535).optional(),
|
||||
protocol: z.number().int().min(0).max(255).optional().describe("Номер IP-протокола IANA"),
|
||||
})
|
||||
const REPORT_ROW_LIMIT = 20000
|
||||
|
||||
export function registerFlowAnalyticsActions(register: typeof add) {
|
||||
register("traffic.flow.analytics.read", "mm_netflow_analytics_report_get", "NetFlow: нагрузка, приложения и разговоры выбранного сервера", "traffic", "mm:traffic:read", "read", "servers", z.object({
|
||||
register("traffic.flow.analytics.read", "mm_netflow_analytics_report_get", "NetFlow: нагрузка, приложения и разговоры выбранного сервера по сохранённым top-N данным", "traffic", "mm:traffic:read", "read", "servers", z.object({
|
||||
serverId: z.number().int().positive().safe(), minutes: z.number().int().min(1).max(1440).default(15),
|
||||
userId: z.string().min(1).max(100).optional(),
|
||||
interface: z.string().trim().min(1).max(200).refine(value => !/[\u0000-\u001f\u007f]/.test(value) && value !== "__all__").optional(),
|
||||
...flowTupleSchema.shape,
|
||||
dedup: z.boolean().default(true), excludeMesh: z.boolean().default(true), excludeOverlay: z.boolean().default(true),
|
||||
offset: z.number().int().min(0).max(100000).default(0), limit: z.number().int().min(1).max(100).default(50),
|
||||
}).strict(), {
|
||||
@@ -57,11 +67,15 @@ export function registerFlowAnalyticsActions(register: typeof add) {
|
||||
const authorize = () => assertTrafficHistorySource(context, server)
|
||||
const startedAt = new Date().toISOString()
|
||||
try {
|
||||
const filters = flowTupleSchema.parse(input)
|
||||
const tuple = Object.values(filters).some(value => value !== undefined) ? filters : undefined
|
||||
const requestedMinutes = Number(input.minutes)
|
||||
const limits = await readFlowSourceLimits()
|
||||
await authorize()
|
||||
const { sourceWindow, ...raw } = await readFlowWindow(Number(input.minutes), minutes => buildFlowAnalytics({ serverId: server.id, minutes, userId: input.userId as string | undefined,
|
||||
iface: input.interface as string | undefined, dedup: input.dedup === true, excludeMesh: input.excludeMesh === true, excludeOverlay: input.excludeOverlay === true },
|
||||
{ serverIds: context.connection.policy.scope.serverIds, maxRows: 20000, authorize }), context.signal)
|
||||
const { sourceWindow: reducedWindow, ...raw } = await readFlowWindow(requestedMinutes, minutes => buildFlowAnalytics({ serverId: server.id, minutes, userId: input.userId as string | undefined,
|
||||
iface: input.interface as string | undefined, tuple, dedup: input.dedup === true, excludeMesh: input.excludeMesh === true, excludeOverlay: input.excludeOverlay === true },
|
||||
{ serverIds: context.connection.policy.scope.serverIds, maxRows: REPORT_ROW_LIMIT, authorize }), context.signal)
|
||||
const sourceWindow = { requestedMinutes, effectiveMinutes: reducedWindow?.effectiveMinutes ?? requestedMinutes, incomplete: reducedWindow !== undefined }
|
||||
const result = flowAnalyticsDtoSchema.parse(raw)
|
||||
const offset = Number(input.offset), limit = Number(input.limit), pages: Record<string, { total: number; nextOffset: number | null }> = {}
|
||||
const analytics: Record<string, unknown> = { ...result }
|
||||
@@ -74,14 +88,16 @@ export function registerFlowAnalyticsActions(register: typeof add) {
|
||||
await authorize()
|
||||
if ((await readFlowSourceLimits()).topN !== limits.topN) throw new McpError("STATE_CONFLICT", "Предел источника NetFlow изменился во время чтения", 409)
|
||||
await authorize()
|
||||
const output = { serverId: server.id, minutes: sourceWindow?.effectiveMinutes ?? Number(input.minutes), sourceWindow, interface: input.interface ?? null, userId: input.userId ?? null,
|
||||
const output = { serverId: server.id, minutes: sourceWindow.effectiveMinutes, sourceWindow, interface: input.interface ?? null, userId: input.userId ?? null, filters,
|
||||
analytics: retained, pages, contextRates: { bpsNowEstimate: _bpsNow, bpsWireEstimate: _bpsWire, bpsOverlayEstimate: _bpsOverlay, bytesWireEstimate: _bytesWire,
|
||||
listenerBound: _live, userAttributionVerified: false, semantics: "REST estimates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback; wire uses current interface snapshots" },
|
||||
listenerBound: _live, userAttributionVerified: false, semantics: "REST estimates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback; wire uses unfiltered current interface snapshots" },
|
||||
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false,
|
||||
source: "retained flow_buckets plus pending; same REST analytics engine with scoped topology",
|
||||
rowLimit: 20000, topRowsPerBucketLimit: Math.max(20, limits.topN), engineTopListLimit: Math.min(50, Math.max(10, limits.topN)),
|
||||
rowLimit: REPORT_ROW_LIMIT, topRowsPerBucketLimit: Math.max(20, limits.topN), engineTopListLimit: Math.min(50, Math.max(10, limits.topN)),
|
||||
historicalDetail: { filtersAppliedTo: "retained rows before aggregation and pagination", rowLimitAppliedBeforeFilters: true,
|
||||
discardedRowsRecoverable: false, exactTupleTotalsVerified: false },
|
||||
incomplete: true, coverageVerified: false, rowSumIsNetworkTotal: false, forwardingVerified: false,
|
||||
inferredPathsVerified: false, historicalOwnershipVerified: false, attribution: "current named whole-interface bindings; users with hidden bindings excluded",
|
||||
inferredPathsVerified: false, historicalOwnershipVerified: false, attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
|
||||
backgroundEnrichmentStarted: false, collectorStarted: false }
|
||||
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ аналитики превышает 1 МиБ; уменьшите страницу", 409)
|
||||
return withCurrentFlowReadQuality(output,context)
|
||||
|
||||
@@ -72,7 +72,7 @@ export function registerFlowCatalogActions(register: typeof add) {
|
||||
for (const server of selected) await assertTrafficHistorySource(context, server)
|
||||
return withCurrentFlowReadQuality({ ...page, clients, total: data.total, nextOffset: offset + clients.length < data.total ? offset + clients.length : null,
|
||||
incomplete: !!data.sourceWindow || page.incomplete || clients.length < data.total || clients.some(row => !row.completeSourceSet || !row.completeAttribution),
|
||||
source: "retained ingress rows and current named whole-interface bindings", topRowsPerBucketLimit: data.window.topRowsPerBucketLimit,
|
||||
source: "retained ingress rows and current exclusive interface bindings, including confirmed single-peer WireGuard", topRowsPerBucketLimit: data.window.topRowsPerBucketLimit,
|
||||
from: data.window.since, to: data.window.until, sourceWindow: data.sourceWindow, ...sourceSemantics },context)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -59,7 +59,7 @@ export function registerFlowLiveActions(register: typeof add) {
|
||||
historicalOwnershipVerified: false, currentTrafficVerified: false,
|
||||
rateSemantics: "REST live rates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback",
|
||||
liveMeaning: "events[].data.live means listener bound; it does not prove exporter freshness or forwarding",
|
||||
attribution: "current named whole-interface bindings; users with hidden bindings excluded",
|
||||
attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
|
||||
collectorStarted: false, backgroundEnrichmentStarted: false }
|
||||
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ live превышает 1 МиБ; уменьшите страницу или число samples", 409)
|
||||
await authorize()
|
||||
|
||||
@@ -53,7 +53,7 @@ export function registerFlowMapActions(register: typeof add) {
|
||||
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,
|
||||
referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false,
|
||||
rowSumIsNetworkTotal: false, historicalOwnershipVerified: false,
|
||||
attribution: "current named whole-interface bindings; users with hidden bindings excluded",
|
||||
attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
|
||||
collectorStarted: false, backgroundEnrichmentStarted: false, tracerouteExecuted: false }
|
||||
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ карты превышает 1 МиБ; уменьшите страницы", 409)
|
||||
return withCurrentFlowReadQuality(output,context)
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { mkdtemp, rm } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { after, mock, test } from "node:test"
|
||||
import { mcpConnectionPolicySchema, mcpOperationDescriptorSchema } from "@mmapp/contracts/mcp"
|
||||
import type { ActionContext } from "./action-types.js"
|
||||
import type { add } from "./actions.js"
|
||||
import { registerMcpOperation } from "./registry.js"
|
||||
|
||||
const queries: Array<{ sql: string; values: unknown[] }> = []
|
||||
const from = "2026-11-27T00:00:00Z"
|
||||
const to = "2026-11-27T01:00:00Z"
|
||||
const observed = new Date("2026-11-27T00:15:00Z")
|
||||
const newer = new Date("2026-11-27T00:30:00Z")
|
||||
const observedPrecise = "2026-11-27T00:15:00.000000Z", newerPrecise = "2026-11-27T00:30:00.000002Z"
|
||||
const fixtures = await mkdtemp(join(tmpdir(), "mcp-incident-test-"))
|
||||
process.env.MCP_STATE_DIR = fixtures
|
||||
after(() => rm(fixtures, { recursive: true, force: true }))
|
||||
let paginate = false
|
||||
mock.module("../../db/index.js", { namedExports: { pool: { async query(sql: string, values: unknown[]) {
|
||||
queries.push({ sql, values })
|
||||
if (sql === "SELECT enabled FROM servers WHERE id=$1") return { rows: [{ enabled: true }] }
|
||||
if (sql.startsWith("SELECT id,enabled FROM servers")) {
|
||||
assert.match(sql, /id=ANY\(\$1::bigint\[\]\) AND id>\$2/)
|
||||
assert.deepEqual(values[0], [7, 9])
|
||||
return { rows: values[1] === 0 ? [{ id: 7, enabled: true }, { id: 9, enabled: false }] : [{ id: 9, enabled: false }] }
|
||||
}
|
||||
if (sql.includes("FROM mcp_requests")) {
|
||||
assert.match(sql, /server_ids=ARRAY\[\$1\]::bigint\[\]/)
|
||||
assert.match(sql, /connection_id=\$5 AND actor_id=\$6 AND tool=ANY\(\$7::text\[\]\)/)
|
||||
assert.deepEqual(values, [7, from, to, 51, "fixture-connection", "fixture-owner", ["mm_fixture_server"]])
|
||||
return { rows: [{ at: newerPrecise, key: "request-id", id: "request-id", status: "completed", timestampKind: "request-created", toolName: "mm_fixture_server" }] }
|
||||
}
|
||||
assert.match(sql, /server_id=\$1/)
|
||||
assert.ok(values[0] === 7 || values[0] === 9)
|
||||
if (sql.includes("servers_rest_ping_samples")) {
|
||||
if (values.length === 3) return { rows: [{ enabled: true, intervalSec: 60, observedAt: null, status: null }] }
|
||||
return { rows: [{ at: observedPrecise, key: "", id: "poll", status: "ok", timestampKind: "backend-sample" }] }
|
||||
}
|
||||
if (sql.includes("router_log_entries")) {
|
||||
const make = (at: string, id: string) => ({ at, id, key: id.padStart(20, "0"), status: "warning", timestampKind: "router", receivedAt: newer })
|
||||
if (!paginate) return { rows: [make(newerPrecise, "41")] }
|
||||
const rows = [make(newerPrecise, "100"), make(newerPrecise, "9"), make("2026-11-27T00:30:00.000001Z", "99")]
|
||||
if (values.length === 4) return { rows: rows.slice(0, Number(values[3])) }
|
||||
assert.match(sql, /\(effective_at,\(lpad\(id::text,20,'0'\)\) COLLATE "C"\) < \(\$5::timestamptz,\$6::text COLLATE "C"\)/)
|
||||
assert.equal(values[4], newerPrecise)
|
||||
return { rows: rows.filter(row => row.at < String(values[4]) || row.at === values[4] && row.key < String(values[5])).slice(0, Number(values[3])) }
|
||||
}
|
||||
if (sql.includes("router_log_collection_state")) throw Error("Sample source unavailable")
|
||||
if (sql.includes("uptime_probe_samples")) {
|
||||
assert.match(sql, /p\.src_server_id=\$1/)
|
||||
assert.match(sql, /sampled_at>=p\.updated_at/)
|
||||
assert.doesNotMatch(sql, /\bp\.(target|name|src_interface)\b/)
|
||||
if (values.length === 3) return { rows: [{ enabled: true, intervalSec: 60, observedAt: observed, status: "warn" }] }
|
||||
return { rows: [{ at: observedPrecise, key: "probe-1", id: "probe-1", status: "warn",
|
||||
timestampKind: "backend-sample", rttMs: 50, lossPct: 25 }] }
|
||||
}
|
||||
if (sql.includes("uptime_resource_samples")) return { rows: [] }
|
||||
throw Error("Unexpected source")
|
||||
} } } })
|
||||
|
||||
const { registerIncidentActions, telemetryFreshness } = await import("./incident-actions.js")
|
||||
const { readCapabilities } = await import("./capability-actions.js")
|
||||
const registered = new Map<string, Parameters<typeof add>>()
|
||||
registerIncidentActions((...args) => registered.set(args[1], args))
|
||||
const connection = {
|
||||
policy: mcpConnectionPolicySchema.parse({
|
||||
id: "fixture", version: 1, status: "active", expiresAt: "2027-01-01T00:00:00Z", mode: "observer",
|
||||
permissions: ["mm:servers:read", "mm:traffic:read"],
|
||||
scope: { serverIds: [7], operationIds: ["catalog.global.read", "catalog.server.read", "catalog.server.write"] },
|
||||
}), owner_permissions: ["mm:servers:read", "mm:uptime:read"],
|
||||
} as ActionContext["connection"]
|
||||
const context = { connection } as ActionContext
|
||||
|
||||
test("timeline limits interval and evidence, keeps order and timestamps, checks both source permission grants", async () => {
|
||||
const registration = registered.get("mm_incident_timeline_get")!
|
||||
const schema = registration[7], read = registration[8].read!
|
||||
const input = { serverId: 7, from, to, limit: 1 }
|
||||
assert.equal(schema.safeParse({ ...input, to: from }).success, false)
|
||||
assert.equal(schema.safeParse({ ...input, to: "2026-11-29T00:00:00Z" }).success, false)
|
||||
assert.equal(schema.safeParse({ ...input, to: "2026-11-27T01:00:00" }).success, false)
|
||||
for (const source of ["uptime", "netflow"]) {
|
||||
await assert.rejects(read(schema.parse({ ...input, sources: [source] }), context),
|
||||
{ code: "PERMISSION_DENIED" })
|
||||
}
|
||||
assert.equal(queries.length, 0)
|
||||
const result = await read(schema.parse(input), context)
|
||||
assert.deepEqual(result, {
|
||||
serverId: 7, from: new Date(from).toISOString(), to: new Date(to).toISOString(),
|
||||
observedAt: (result as { observedAt: string }).observedAt,
|
||||
order: "newest-first", sources: ["routeros-poll", "logs"],
|
||||
items: [{ id: "41", status: "warning", timestampKind: "router", source: "logs", at: newerPrecise, receivedAt: newer.toISOString() }],
|
||||
nextCursor: (result as { nextCursor: string }).nextCursor,
|
||||
truncated: true, coverageVerified: false, managerEventsIncluded: false,
|
||||
})
|
||||
assert.deepEqual(queries.map(query => query.values), [[7], [7, from, to, 2], [7, from, to, 2]])
|
||||
})
|
||||
|
||||
test("health separates disabled, absent, stale and unknown freshness from observed status", async () => {
|
||||
const row = { enabled: true, intervalSec: 30, observedAt: observed, status: "error" }
|
||||
assert.equal(telemetryFreshness(row, observed.getTime() + 90_000, true).freshness, "fresh")
|
||||
assert.equal(telemetryFreshness(row, observed.getTime() + 90_001, true).freshness, "stale")
|
||||
assert.equal(telemetryFreshness(row, observed.getTime(), false).freshness, "disabled")
|
||||
assert.equal(telemetryFreshness({ ...row, intervalSec: null }, observed.getTime(), true).freshness, "unknown")
|
||||
const registration = registered.get("mm_telemetry_health_get")!
|
||||
const result = await registration[8].read!(registration[7].parse({ serverId: 7, sources: ["routeros-poll", "logs"] }), context)
|
||||
assert.deepEqual((result as { observations: unknown[] }).observations, [{
|
||||
source: "routeros-poll", freshness: "unobserved", observedAt: null, ageMs: null,
|
||||
lastStatus: null,
|
||||
}, {
|
||||
source: "logs", freshness: "unavailable", observedAt: null, ageMs: null,
|
||||
lastStatus: null,
|
||||
}])
|
||||
})
|
||||
|
||||
test("capabilities keeps legacy shape and assesses filtered candidates under effective policy", () => {
|
||||
for (const [id, toolName, scope, effect, requiredPermissions] of [
|
||||
["catalog.global.read", "mm_fixture_global", "global", "read", []],
|
||||
["catalog.server.read", "mm_fixture_server", "servers", "read", ["mm:servers:read"]],
|
||||
["catalog.server.write", "mm_fixture_server_plan", "servers", "write", ["mm:traffic:read"]],
|
||||
["catalog.hidden.read", "mm_fixture_hidden", "global", "read", []],
|
||||
]) registerMcpOperation(mcpOperationDescriptorSchema.parse({ id, toolName, scope, effect, requiredPermissions, version: 1,
|
||||
title: "Fixture", section: "fixture", risk: "ordinary", implementation: "available",
|
||||
annotations: { readOnlyHint: effect === "read", destructiveHint: effect === "write", idempotentHint: true, openWorldHint: true } }))
|
||||
const baseline = readCapabilities({}, connection, observed)
|
||||
assert.deepEqual(Object.keys(baseline).sort(), ["operations", "schemaVersion"])
|
||||
assert.equal(baseline.operations.length, 3)
|
||||
assert.ok(baseline.operations.every(operation => !("applicability" in operation)))
|
||||
const applicability = (input: Parameters<typeof readCapabilities>[0]) => readCapabilities({ includeApplicability: true, ...input }, connection, observed)
|
||||
.operations.flatMap(operation => "applicability" in operation ? [operation.applicability] : [])
|
||||
assert.equal(applicability({ toolName: "mm_fixture_global" })[0]?.reasons[0]?.code, "GLOBAL_DENIED")
|
||||
assert.equal(applicability({ serverId: 7, effect: "read" })[0]?.decision, "allowed")
|
||||
assert.equal(applicability({ serverId: 8, effect: "read" })[0]?.reasons[0]?.code, "SERVER_DENIED")
|
||||
assert.deepEqual(applicability({ effect: "write" })[0]?.reasons.map(reason => reason.code), ["OWNER_PERMISSION_MISSING", "OBSERVER_WRITE_DENIED"])
|
||||
assert.equal(applicability({ section: "fixture", applicable: true }).length, 1)
|
||||
})
|
||||
|
||||
test("optional manager evidence requires both audit grants and selects current single-server tool metadata", async () => {
|
||||
const registration = registered.get("mm_incident_timeline_get")!
|
||||
const raw = registration[7].parse({ serverId: 7, from, to, sources: ["routeros-poll"], includeManagerEvents: true })
|
||||
const read = registration[8].read!
|
||||
const before = queries.length
|
||||
const audit = {
|
||||
...connection, id: "fixture-connection", owner_id: "fixture-owner",
|
||||
policy: { ...connection.policy, permissions: [...connection.policy.permissions, "mm:mcp:read"] },
|
||||
}
|
||||
await assert.rejects(read(raw, { ...context, connection: audit }), { code: "PERMISSION_DENIED" })
|
||||
assert.equal(queries.length, before)
|
||||
audit.owner_permissions = [...audit.owner_permissions, "mm:mcp:read"]
|
||||
const result = await read(raw, { ...context, connection: audit })
|
||||
assert.deepEqual((result as { sources: string[] }).sources, ["routeros-poll", "mcp-request"])
|
||||
assert.deepEqual((result as { items: unknown[] }).items[0], {
|
||||
id: "request-id", status: "completed", timestampKind: "request-created", toolName: "mm_fixture_server",
|
||||
source: "mcp-request", at: newerPrecise,
|
||||
})
|
||||
})
|
||||
|
||||
test("timeline paginates equal timestamps and microseconds with a bound opaque cursor", async () => {
|
||||
const registration = registered.get("mm_incident_timeline_get")!
|
||||
const base = { serverId: 7, from, to, sources: ["logs"], limit: 1 }
|
||||
const read = async (raw: typeof base & { cursor?: string }) => await registration[8].read!(registration[7].parse(raw), context) as {
|
||||
nextCursor: string | null; items: Array<{ id: string; at: string }>
|
||||
}
|
||||
paginate = true
|
||||
try {
|
||||
const one = await read(base)
|
||||
assert.ok(one.nextCursor)
|
||||
const two = await read({ ...base, cursor: one.nextCursor })
|
||||
assert.ok(two.nextCursor)
|
||||
const three = await read({ ...base, cursor: two.nextCursor })
|
||||
assert.equal(three.nextCursor, null)
|
||||
assert.deepEqual([one, two, three].flatMap(page => page.items.map(({ id, at }) => [id, at])), [
|
||||
["100", newerPrecise], ["9", newerPrecise], ["99", "2026-11-27T00:30:00.000001Z"],
|
||||
])
|
||||
await assert.rejects(read({ ...base, serverId: 9, cursor: one.nextCursor }), { code: "RESET_REQUIRED" })
|
||||
await assert.rejects(read({ ...base, cursor: "bogus" }), { code: "RESET_REQUIRED" })
|
||||
} finally { paginate = false }
|
||||
})
|
||||
|
||||
test("fleet health pages over the effective server allowlist only", async () => {
|
||||
const registration = registered.get("mm_telemetry_health_get")!
|
||||
const scoped = { ...context, connection: { ...connection, policy: { ...connection.policy,
|
||||
scope: { ...connection.policy.scope, serverIds: [7, 9] } } } }
|
||||
const raw = { sources: ["routeros-poll"], limit: 1 }
|
||||
const read = async (input: typeof raw & { afterServerId?: number }) => await registration[8].read!(registration[7].parse(input), scoped) as {
|
||||
nextAfterServerId: number | null; items: Array<{ serverId: number }>
|
||||
}
|
||||
assert.deepEqual(registration[8].target!(raw, scoped), { scope: "servers", serverIds: [7, 9] })
|
||||
const one = await read(raw), two = await read({ ...raw, afterServerId: 7 })
|
||||
assert.deepEqual([one.nextAfterServerId, two.nextAfterServerId], [7, null])
|
||||
assert.deepEqual([one, two].flatMap(page => page.items.map(item => item.serverId)), [7, 9])
|
||||
})
|
||||
|
||||
test("uptime combines scoped resource and retained probe evidence without target details", async () => {
|
||||
const scoped = { ...context, connection: { ...connection, policy: { ...connection.policy,
|
||||
permissions: [...connection.policy.permissions, "mm:uptime:read"] } } }
|
||||
const health = registered.get("mm_telemetry_health_get")!
|
||||
const sources = ["uptime"]
|
||||
const state = await health[8].read!(health[7].parse({ serverId: 7, sources }), scoped) as {
|
||||
observations: Array<{ source: string; lastStatus: string | null }>
|
||||
}
|
||||
assert.deepEqual(state.observations.map(row => [row.source, row.lastStatus]), [["uptime", null], ["uptime-probe", "warn"]])
|
||||
const timeline = registered.get("mm_incident_timeline_get")!
|
||||
const evidence = await timeline[8].read!(timeline[7].parse({ serverId: 7, from, to, sources }), scoped) as { items: unknown[] }
|
||||
assert.deepEqual(evidence.items, [{ at: observedPrecise, id: "probe-1", status: "warn", source: "uptime-probe",
|
||||
timestampKind: "backend-sample", rttMs: 50, lossPct: 25 }])
|
||||
})
|
||||
@@ -0,0 +1,213 @@
|
||||
import { z } from "zod"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { hasPermission } from "../../lib/permissions.js"
|
||||
import { listMcpOperations } from "./registry.js"
|
||||
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, McpError } from "./security.js"
|
||||
import type { ActionContext } from "./action-types.js"
|
||||
import type { add } from "./actions.js"
|
||||
|
||||
const sources = ["routeros-poll", "uptime", "logs", "netflow"] as const
|
||||
type Source = typeof sources[number]
|
||||
const permissions: Record<Source, string> = {
|
||||
"routeros-poll": "mm:servers:read", uptime: "mm:uptime:read", logs: "mm:servers:read", netflow: "mm:traffic:read",
|
||||
}
|
||||
const selection = {
|
||||
serverId: z.number().int().positive().safe(),
|
||||
sources: z.array(z.enum(sources)).min(1).max(sources.length).optional(),
|
||||
}
|
||||
const healthInput = z.object({ ...selection, serverId: selection.serverId.optional(),
|
||||
afterServerId: selection.serverId.optional(), limit: z.number().int().min(1).max(20).default(10),
|
||||
}).strict().refine(input => input.serverId === undefined || input.afterServerId === undefined, "Курсор доступен для списка серверов")
|
||||
const hourMs = 3_600_000
|
||||
const timelineSourceNames = [...sources, "uptime-probe", "mcp-request"] as const
|
||||
type TimelineSource = typeof timelineSourceNames[number]
|
||||
const cursorSchema = z.object({ scope: z.string(), at: z.iso.datetime({ precision: 6 }),
|
||||
source: z.enum(timelineSourceNames), key: z.string().max(1000),
|
||||
}).strict()
|
||||
const timelineInput = z.object({
|
||||
...selection, from: z.iso.datetime({ offset: true }), to: z.iso.datetime({ offset: true }),
|
||||
limit: z.number().int().min(1).max(200).default(50),
|
||||
includeManagerEvents: z.boolean().default(false),
|
||||
cursor: z.string().min(1).max(3000).optional(),
|
||||
}).strict().refine(({ from, to }) => {
|
||||
const duration = Date.parse(to) - Date.parse(from)
|
||||
return duration > 0 && duration <= 24 * hourMs
|
||||
}, "Требуется положительное окно до 24 часов")
|
||||
|
||||
function permittedSources(context: ActionContext, requested?: Source[]) {
|
||||
const permitted = (source: Source) => [context.connection.policy.permissions, context.connection.owner_permissions]
|
||||
.every(granted => hasPermission(granted, permissions[source]))
|
||||
if (requested?.some(source => !permitted(source))) throw new McpError("PERMISSION_DENIED", "Чтение выбранного источника запрещено", 403)
|
||||
return [...new Set(requested ?? sources.filter(permitted))]
|
||||
}
|
||||
|
||||
type HealthRow = { enabled: boolean | null; intervalSec: number | null; observedAt: Date | null; status: string | null; gapAt?: Date | null }
|
||||
type EvidenceRow = { at: string; key: string; id: string; status: string | null; timestampKind: string; receivedAt?: Date; topics?: string[]; message?: string; toolName?: string }
|
||||
const healthSources: Record<Source, string> = {
|
||||
"routeros-poll": `SELECT cfg.enabled,cfg.interval_sec AS "intervalSec",sample.sampled_at AS "observedAt",
|
||||
CASE sample.ok WHEN true THEN 'ok' WHEN false THEN 'error' END AS status
|
||||
FROM servers_api_ping_settings cfg LEFT JOIN LATERAL (
|
||||
SELECT sampled_at,ok FROM servers_rest_ping_samples WHERE server_id=$1 AND sampled_at BETWEEN $2 AND $3
|
||||
ORDER BY sampled_at DESC LIMIT 1
|
||||
) sample ON true WHERE cfg.id=1`,
|
||||
uptime: `SELECT cfg.enabled AND cfg.resources_enabled AS enabled,cfg.interval_sec AS "intervalSec",
|
||||
sample.sampled_at AS "observedAt",sample.status
|
||||
FROM uptime_settings cfg LEFT JOIN LATERAL (
|
||||
SELECT sampled_at,status FROM uptime_resource_samples WHERE server_id=$1 AND sampled_at BETWEEN $2 AND $3
|
||||
ORDER BY sampled_at DESC LIMIT 1
|
||||
) sample ON true WHERE cfg.id=1`,
|
||||
logs: `SELECT cfg.enabled,cfg.interval_sec AS "intervalSec",
|
||||
CASE WHEN sample.last_collected_at BETWEEN $2 AND $3 THEN sample.last_collected_at END AS "observedAt",
|
||||
CASE WHEN sample.gap_at BETWEEN $2 AND $3 THEN sample.gap_at END AS "gapAt",
|
||||
CASE WHEN sample.last_error IS NOT NULL AND sample.last_error <> '' THEN 'error'
|
||||
WHEN sample.last_collected_at BETWEEN $2 AND $3 THEN 'ok' END AS status
|
||||
FROM router_log_settings cfg LEFT JOIN router_log_collection_state sample ON sample.server_id=$1 WHERE cfg.id=1`,
|
||||
netflow: `SELECT NULL::boolean AS enabled,NULL::integer AS "intervalSec",bucket_at AS "observedAt",'retained-bucket' AS status
|
||||
FROM flow_minute_stats WHERE server_id=$1 AND bucket_at BETWEEN $2 AND $3
|
||||
ORDER BY bucket_at DESC LIMIT 1`,
|
||||
}
|
||||
const uptimeProbeHealth = `SELECT cfg.enabled AND cfg.ping_enabled AS enabled,
|
||||
COALESCE(NULLIF(sample.interval_sec,0),cfg.probe_interval_sec) AS "intervalSec",
|
||||
sample.sampled_at AS "observedAt",sample.status
|
||||
FROM uptime_settings cfg LEFT JOIN LATERAL (
|
||||
SELECT p.interval_sec,s.sampled_at,s.status FROM uptime_probes p CROSS JOIN LATERAL (
|
||||
SELECT sampled_at,status FROM uptime_probe_samples WHERE probe_id=p.id AND sampled_at BETWEEN $2 AND $3 AND sampled_at>=p.updated_at
|
||||
ORDER BY sampled_at DESC LIMIT 1
|
||||
) s WHERE p.src_server_id=$1 AND p.enabled ORDER BY s.sampled_at DESC,p.id LIMIT 1
|
||||
) sample ON true WHERE cfg.id=1`
|
||||
const timelineSources: Record<TimelineSource, { time: string; key: string; evidence: string }> = {
|
||||
"routeros-poll": { time: "sampled_at", key: "''::text", evidence: `sampled_at::text AS id,CASE ok WHEN true THEN 'ok' ELSE 'error' END AS status,
|
||||
'backend-sample' AS "timestampKind" FROM servers_rest_ping_samples WHERE server_id=$1` },
|
||||
uptime: { time: "sampled_at", key: "''::text", evidence: `sampled_at::text AS id,status,'backend-sample' AS "timestampKind"
|
||||
FROM uptime_resource_samples WHERE server_id=$1` },
|
||||
"uptime-probe": { time: "s.sampled_at", key: "p.id", evidence: `p.id,status,'backend-sample' AS "timestampKind",
|
||||
s.rtt_ms AS "rttMs",s.loss_pct AS "lossPct" FROM uptime_probes p
|
||||
JOIN uptime_probe_samples s ON s.probe_id=p.id WHERE p.src_server_id=$1 AND s.sampled_at>=p.updated_at` },
|
||||
logs: { time: "effective_at", key: "lpad(id::text,20,'0')", evidence: `id::text,level AS status,
|
||||
CASE WHEN event_at IS NULL THEN 'receipt' ELSE 'router' END AS "timestampKind",
|
||||
received_at AS "receivedAt",topics[1:20] AS topics,left(message,500) AS message FROM router_log_entries WHERE server_id=$1` },
|
||||
netflow: { time: "bucket_at", key: "''::text", evidence: `bucket_at::text AS id,'retained-bucket' AS status,'bucket' AS "timestampKind"
|
||||
FROM flow_minute_stats WHERE server_id=$1` },
|
||||
"mcp-request": { time: "created_at", key: "id::text", evidence: `id::text,CASE WHEN finished_at <= $3 THEN status END AS status,
|
||||
'request-created' AS "timestampKind",tool AS "toolName" FROM mcp_requests WHERE server_ids=ARRAY[$1]::bigint[]
|
||||
AND connection_id=$5 AND actor_id=$6 AND tool=ANY($7::text[])` },
|
||||
}
|
||||
|
||||
function timelineQuery(source: TimelineSource, parameters: unknown[], cursor?: z.infer<typeof cursorSchema>) {
|
||||
const { time, key, evidence } = timelineSources[source]
|
||||
const tie = `(${key}) COLLATE "C"`
|
||||
let clause = ""
|
||||
if (cursor) {
|
||||
const mark = `$${parameters.push(cursor.at)}::timestamptz`
|
||||
if (source === cursor.source) clause = `AND (${time},${tie}) < (${mark},$${parameters.push(cursor.key)}::text COLLATE "C")`
|
||||
else clause = `AND ${time} ${source > cursor.source ? "<=" : "<"} ${mark}`
|
||||
}
|
||||
return `SELECT to_char(${time} AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS at,
|
||||
${key} AS key,${evidence} AND ${time} BETWEEN $2 AND $3 ${clause}
|
||||
ORDER BY ${time} DESC,${tie} DESC LIMIT $4`
|
||||
}
|
||||
|
||||
function managerEventTools(context: ActionContext) {
|
||||
const { policy, owner_permissions } = context.connection
|
||||
const hasBoth = (permission: string) => hasPermission(policy.permissions, permission) && hasPermission(owner_permissions, permission)
|
||||
if (!hasBoth("mm:mcp:read")) throw new McpError("PERMISSION_DENIED", "Чтение аудита MCP запрещено", 403)
|
||||
const allowed = new Set(policy.scope.operationIds)
|
||||
return listMcpOperations().filter(operation => operation.implementation === "available" && operation.scope === "servers" &&
|
||||
allowed.has(operation.id) && operation.requiredPermissions.every(hasBoth)).map(operation => operation.toolName)
|
||||
}
|
||||
|
||||
async function requireServer(serverId: number) {
|
||||
const { rows } = await pool.query<{ enabled: boolean }>("SELECT enabled FROM servers WHERE id=$1", [serverId])
|
||||
if (!rows.length) throw new McpError("NOT_FOUND", "Сервер не найден", 404)
|
||||
return rows[0].enabled
|
||||
}
|
||||
|
||||
export function telemetryFreshness(row: HealthRow | undefined, asOf: number, serverEnabled: boolean) {
|
||||
const ageMs = row?.observedAt ? asOf - row.observedAt.getTime() : null
|
||||
const staleAfterMs = row?.intervalSec ? row.intervalSec * 3000 : null
|
||||
const freshness = !serverEnabled || row?.enabled === false ? "disabled"
|
||||
: ageMs === null ? "unobserved" : staleAfterMs === null ? "unknown" : ageMs > staleAfterMs ? "stale" : "fresh"
|
||||
return { freshness, observedAt: row?.observedAt?.toISOString() ?? null, ageMs, lastStatus: row?.status ?? null,
|
||||
...(row?.gapAt && { gapAt: row.gapAt.toISOString() }) }
|
||||
}
|
||||
|
||||
export function registerIncidentActions(register: typeof add) {
|
||||
register("telemetry.health.read", "mm_telemetry_health_get", "Здоровье источников телеметрии сервера", "logs",
|
||||
"mm:servers:read", "read", "servers", healthInput, {
|
||||
target: (raw, context) => {
|
||||
const serverIds = typeof raw.serverId === "number" ? [raw.serverId] : context.connection.policy.scope.serverIds
|
||||
if (!serverIds.length) throw new McpError("SERVER_DENIED", "Подключению не выдан доступ к серверам", 403)
|
||||
return { scope: "servers", serverIds }
|
||||
},
|
||||
read: async (raw, context) => {
|
||||
const input = healthInput.parse(raw), selected = permittedSources(context, input.sources)
|
||||
const asOf = Date.now(), from = new Date(asOf - 24 * hourMs), to = new Date(asOf)
|
||||
const healthQueries = selected.map(source => ({ source: source as Source | "uptime-probe", sql: healthSources[source] }))
|
||||
if (selected.includes("uptime")) healthQueries.push({ source: "uptime-probe", sql: uptimeProbeHealth })
|
||||
const readServer = async (serverId: number, serverEnabled: boolean) => ({
|
||||
serverId, serverEnabled, observations: await Promise.all(healthQueries.map(async ({ source, sql }) => {
|
||||
const expectsActiveServer = source === "netflow" || serverEnabled
|
||||
try {
|
||||
const { rows } = await pool.query<HealthRow>(sql, [serverId, from, to])
|
||||
return { source, ...telemetryFreshness(rows[0], asOf, expectsActiveServer) }
|
||||
} catch {
|
||||
context.signal?.throwIfAborted()
|
||||
return { source, ...telemetryFreshness(undefined, asOf, expectsActiveServer), freshness: "unavailable" as const }
|
||||
}
|
||||
})),
|
||||
})
|
||||
const metadata = { observedAt: to.toISOString(), lookbackFrom: from.toISOString(),
|
||||
sourceOmissions: sources.filter(source => !selected.includes(source)).map(source => ({
|
||||
source, reason: input.sources ? "not-requested" : "permission-denied",
|
||||
})),
|
||||
netflowDataQuality: { available: false, reason: "no-server-scoped-collector-quality", exportCoverage: "unverified" } }
|
||||
if (input.serverId !== undefined) return { ...await readServer(input.serverId, await requireServer(input.serverId)), ...metadata }
|
||||
const { rows } = await pool.query<{ id: number; enabled: boolean }>(
|
||||
"SELECT id,enabled FROM servers WHERE id=ANY($1::bigint[]) AND id>$2 ORDER BY id LIMIT $3",
|
||||
[context.connection.policy.scope.serverIds, input.afterServerId ?? 0, input.limit + 1])
|
||||
const page = rows.slice(0, input.limit)
|
||||
const items = await Promise.all(page.map(row => readServer(Number(row.id), row.enabled)))
|
||||
return { ...metadata, items, nextAfterServerId: rows.length > input.limit ? Number(page.at(-1)?.id) : null }
|
||||
},
|
||||
})
|
||||
register("incident.timeline.read", "mm_incident_timeline_get", "Хронология наблюдений по серверу", "logs",
|
||||
"mm:servers:read", "read", "servers", timelineInput, {
|
||||
read: async (raw, context) => {
|
||||
const input = timelineInput.parse(raw), selected = permittedSources(context, input.sources)
|
||||
const managerTools = input.includeManagerEvents ? managerEventTools(context) : null
|
||||
const { cursor: token, limit, ...filters } = input
|
||||
const scope = async () => fingerprint({ purpose: "incident-timeline-v1", filters, generation: await accessGeneration(),
|
||||
connection: context.connection.id, credential: context.principal?.credentialId,
|
||||
policy: context.connection.policy, ownerPermissions: context.connection.owner_permissions })
|
||||
let cursor: z.infer<typeof cursorSchema> | undefined
|
||||
if (token) {
|
||||
try {
|
||||
cursor = cursorSchema.parse(JSON.parse(await decryptSecret(token)))
|
||||
if (cursor.scope !== await scope()) throw Error("scope")
|
||||
} catch { throw new McpError("RESET_REQUIRED", "Курсор устарел или относится к другим фильтрам", 409) }
|
||||
}
|
||||
await requireServer(input.serverId)
|
||||
const parameters = [input.serverId, input.from, input.to, limit + 1]
|
||||
const queries: Array<{ source: TimelineSource; parameters: unknown[] }> =
|
||||
selected.map(source => ({ source, parameters: [...parameters] }))
|
||||
if (selected.includes("uptime")) queries.push({ source: "uptime-probe", parameters: [...parameters] })
|
||||
if (managerTools) queries.push({ source: "mcp-request",
|
||||
parameters: [...parameters, context.connection.id, context.connection.owner_id, managerTools] })
|
||||
const batches = await Promise.all(queries.map(async ({ source, parameters }) => {
|
||||
const { rows } = await pool.query<EvidenceRow>(timelineQuery(source, parameters, cursor), parameters)
|
||||
return rows.map(row => ({ ...row, source }))
|
||||
}))
|
||||
const items = batches.flat().sort((a, b) => a.at < b.at ? 1 : a.at > b.at ? -1 : a.source < b.source ? -1 : a.source > b.source ? 1 : 0)
|
||||
const page = items.slice(0, limit)
|
||||
const last = page.at(-1)
|
||||
const nextCursor = last && items.length > limit
|
||||
? await encryptSecret(JSON.stringify({ at: last.at, key: last.key, source: last.source, scope: cursor?.scope ?? await scope() }))
|
||||
: null
|
||||
return { serverId: input.serverId, from: new Date(input.from).toISOString(), to: new Date(input.to).toISOString(),
|
||||
observedAt: new Date().toISOString(), order: "newest-first", sources: queries.map(query => query.source),
|
||||
items: page.map(({ key: _key, receivedAt, ...row }) => ({
|
||||
...row, ...(receivedAt && { receivedAt: receivedAt.toISOString() }),
|
||||
})), nextCursor, truncated: nextCursor !== null, coverageVerified: false, managerEventsIncluded: input.includeManagerEvents }
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { projectDnsState, projectFibTableState, projectRouteLookup } from "./network-diagnostic-actions.js"
|
||||
|
||||
const route = (prefix: string, immediateGateway: string, table = "tenant") => ({
|
||||
"routing-table": table, "dst-address": prefix, active: "true",
|
||||
gateway: immediateGateway, "immediate-gw": immediateGateway,
|
||||
})
|
||||
|
||||
test("requires positive FIB evidence in the explicitly selected table", () => {
|
||||
const main = { name: "main", fib: true, invalid: false }
|
||||
assert.equal(projectFibTableState([main], "main"), "ready")
|
||||
assert.equal(projectFibTableState([main], "tenant"), "table-not-found")
|
||||
assert.equal(projectFibTableState([main, main], "main"), "partial")
|
||||
assert.equal(projectFibTableState([{ ...main, fib: "" }], "main"), "partial")
|
||||
assert.equal(projectFibTableState([{ ...main, fib: "false" }], "main"), "table-not-fib")
|
||||
assert.equal(projectFibTableState([{ ...main, invalid: true }], "main"), "table-inactive")
|
||||
})
|
||||
|
||||
test("looks up IPv4 by longest active prefix and preserves ECMP path multiplicity", () => {
|
||||
const prefix = "203.0.113.0/24"
|
||||
const result = projectRouteLookup([
|
||||
route("0.0.0.0/0", "192.0.2.1%wan"),
|
||||
route("203.0.113.10/32", "192.0.2.2%main", "main"),
|
||||
{ ...route("203.0.113.10/32", "192.0.2.3%disabled"), disabled: "true" },
|
||||
{ ...route("203.0.113.10/32", "192.0.2.4%inactive"), active: "false" },
|
||||
route(prefix, "192.0.2.5%uplink,192.0.2.6%uplink"),
|
||||
route(prefix, "192.0.2.5%uplink"),
|
||||
], "tenant", "203.0.113.10")
|
||||
assert.equal(result.status, "matched")
|
||||
assert.deepEqual(result.routes.map(item => item.prefix), [prefix, prefix])
|
||||
assert.deepEqual(result.nextHops, ["192.0.2.5%uplink", "192.0.2.6%uplink", "192.0.2.5%uplink"])
|
||||
assert.deepEqual(result.nextHopDetails.map(hop => hop.interface), ["uplink", "uplink", "uplink"])
|
||||
})
|
||||
|
||||
test("matches IPv6 blackhole and distinguishes absent and partial observations", () => {
|
||||
const blackhole = { "routing-table": "tenant", "dst-address": "2001:db8:1::/48", active: "true", blackhole: "yes" }
|
||||
const result = projectRouteLookup([route("::/0", "fe80::1%uplink"), blackhole], "tenant", "2001:db8:1:2::15")
|
||||
assert.equal(result.status, "matched")
|
||||
assert.equal(result.routes[0].disposition, "blackhole")
|
||||
assert.deepEqual(result.nextHops, [])
|
||||
assert.equal(projectRouteLookup([blackhole], "tenant", "2001:db8:2::1").status, "no-route")
|
||||
assert.equal(projectRouteLookup([{ ...blackhole, active: undefined }], "tenant", "2001:db8:1::1").status, "partial")
|
||||
assert.equal(projectRouteLookup([route("::/0", "")], "tenant", "2001:db8:1::1").status, "partial")
|
||||
assert.equal(projectRouteLookup([route("::/0", "fe80::1%uplink"), { ...blackhole, "dst-address": "2001:db8:1::/129" }], "tenant", "2001:db8:1::1").status, "partial")
|
||||
assert.equal(projectRouteLookup([{ ...blackhole, blackhole: "" }], "tenant", "2001:db8:1::1").routes[0].disposition, "blackhole")
|
||||
assert.equal(projectRouteLookup([route("::/0", "bridge wan")], "tenant", "2001:db8:1::1").nextHopDetails[0].interface, "bridge wan")
|
||||
})
|
||||
|
||||
test("bounds ECMP output and exposes omissions as partial", () => {
|
||||
const rows = Array.from({ length: 129 }, () => route("0.0.0.0/0", "192.0.2.1%uplink"))
|
||||
const result = projectRouteLookup(rows, "tenant", "203.0.113.10")
|
||||
assert.equal(result.status, "partial")
|
||||
assert.equal(result.nextHops.length, 128)
|
||||
})
|
||||
|
||||
test("retains duplicate native array nexthops across active default rows", () => {
|
||||
const defaults = Array.from({ length: 2 }, () => ({
|
||||
"routing-table": "main", "dst-address": "0.0.0.0/0", active: true,
|
||||
gateway: ["192.0.2.1"], "immediate-gw": ["192.0.2.1%ether1"],
|
||||
}))
|
||||
const result = projectRouteLookup(defaults, "main", "203.0.113.10")
|
||||
assert.equal(result.status, "matched")
|
||||
assert.deepEqual(result.nextHops, ["192.0.2.1%ether1", "192.0.2.1%ether1"])
|
||||
assert.deepEqual(result.routes.map(item => item.gateways), [["192.0.2.1"], ["192.0.2.1"]])
|
||||
assert.equal(projectRouteLookup([{ ...defaults[0], "immediate-gw": ["192.0.2.1%ether1", 1] }], "main", "203.0.113.10").status, "partial")
|
||||
})
|
||||
|
||||
test("DNS reports ordered upstream addresses and projects DoH to a boolean", () => {
|
||||
assert.deepEqual(projectDnsState({
|
||||
"allow-remote-requests": "yes", servers: "192.0.2.53@tenant,2001:db8::53", "dynamic-servers": "",
|
||||
"use-doh-server": "https://example.invalid/dns-query?secret=private", "cache-used": "private",
|
||||
}), {
|
||||
allowRemoteRequests: true, staticServers: ["192.0.2.53@tenant", "2001:db8::53"],
|
||||
dynamicServers: [], dohEnabled: true, incomplete: false,
|
||||
})
|
||||
assert.deepEqual(projectDnsState({ "allow-remote-requests": false, servers: "", "use-doh-server": "" }), {
|
||||
allowRemoteRequests: false, staticServers: [], dynamicServers: null, dohEnabled: false, incomplete: true,
|
||||
})
|
||||
assert.deepEqual(projectDnsState([{ "allow-remote-requests": false, servers: ["192.0.2.53", "2001:db8::53"], "dynamic-servers": [], "use-doh-server": "" }]), {
|
||||
allowRemoteRequests: false, staticServers: ["192.0.2.53", "2001:db8::53"], dynamicServers: [], dohEnabled: false, incomplete: false,
|
||||
})
|
||||
assert.throws(() => projectDnsState([{}, {}]))
|
||||
})
|
||||
@@ -0,0 +1,184 @@
|
||||
import { isIP } from "node:net"
|
||||
import { z } from "zod"
|
||||
import { observedBoolean } from "../../services/ospf-observed-values.js"
|
||||
import { isConfirmedRoutingFibTable } from "../../services/routing-table-fib.js"
|
||||
import { ipv4ToInt, ipv6ToInt, parseCidrV4, parseCidrV6 } from "../../services/traffic-flow-ip.js"
|
||||
import type { add } from "./actions.js"
|
||||
import { readNetworkValue } from "./network-neighbor-actions.js"
|
||||
import { parseRoutingEndpoint } from "./routing-native-endpoint.js"
|
||||
import { McpError } from "./security.js"
|
||||
|
||||
const serverIdSchema = z.number().int().positive().safe()
|
||||
const tableSchema = z.string().min(1).max(200).refine(value => !/[\u0000-\u001f\u007f]/.test(value))
|
||||
const destinationSchema = z.string().max(45).refine(value => !value.includes("%") && isIP(value) !== 0)
|
||||
const rowSchema = z.record(z.string(), z.unknown())
|
||||
const tablePath = "/routing/table?.proplist=name,fib,disabled,invalid"
|
||||
const dnsPath = "/ip/dns?.proplist=allow-remote-requests,servers,dynamic-servers,use-doh-server"
|
||||
const flags = z.union([z.boolean(), z.string()]).transform(value => typeof value === "boolean" ? value : observedBoolean(value))
|
||||
const flag = (value: unknown) => flags.safeParse(value).data ?? null
|
||||
const routeRows = z.array(rowSchema).max(10000)
|
||||
const maxRoutePaths = 128
|
||||
|
||||
export function projectFibTableState(raw: unknown, table: string) {
|
||||
const rows = routeRows.parse(raw)
|
||||
if (rows.some(row => typeof row.name !== "string")) return "partial"
|
||||
const matches = rows.filter(row => row.name === table)
|
||||
if (matches.length > 1) return "partial"
|
||||
if (!matches.length) return "table-not-found"
|
||||
const row = matches[0]
|
||||
if (flag(row.fib) === false) return "table-not-fib"
|
||||
if (flag(row.disabled) === true || flag(row.invalid) === true) return "table-inactive"
|
||||
// This REST catalog has produced an empty fib value for non-FIB tables as well.
|
||||
return row.fib !== "" && isConfirmedRoutingFibTable(row) ? "ready" : "partial"
|
||||
}
|
||||
|
||||
function matchingLength(value: unknown, destination: string): number | null {
|
||||
const family = isIP(destination)
|
||||
if (typeof value !== "string" || value.length > 50 || !/^[^/%]+\/\d+$/.test(value)) return null
|
||||
if (isIP(value.split("/")[0]) !== family) return null
|
||||
if (family === 4) {
|
||||
const prefix = parseCidrV4(value)
|
||||
if (!prefix) return null
|
||||
return ((ipv4ToInt(destination)! & prefix.mask) >>> 0) === prefix.net ? prefix.prefixLen : -1
|
||||
}
|
||||
const prefix = parseCidrV6(value)
|
||||
if (!prefix) return null
|
||||
return (ipv6ToInt(destination)! >> prefix.shift) === prefix.net ? prefix.prefixLen : -1
|
||||
}
|
||||
|
||||
const routePath = z.string().min(1).max(512).refine(value => !/[\u0000-\u001f\u007f]/.test(value))
|
||||
function nativeList(value: unknown, maxCharacters: number, maxItems: number): string[] | null {
|
||||
if (value === "") return []
|
||||
const items = typeof value === "string" && value.length <= maxCharacters ? value.split(",") : value
|
||||
if (!Array.isArray(items) || items.length > maxItems) return null
|
||||
let characters = 0
|
||||
const result = []
|
||||
for (const item of items) {
|
||||
if (typeof item !== "string") return null
|
||||
characters += item.length
|
||||
const entry = item.trim()
|
||||
if (!entry || characters > maxCharacters) return null
|
||||
result.push(entry)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function splitNexthops(value: unknown) {
|
||||
const paths = nativeList(value, 16384, 1024)
|
||||
return paths?.every(path => !path.includes(",") && routePath.safeParse(path).success) ? paths : []
|
||||
}
|
||||
|
||||
function nexthopDetails(value: string) {
|
||||
try {
|
||||
const hop = parseRoutingEndpoint(value)
|
||||
return { address: hop.address, interface: hop.interface ?? null, vrf: hop.vrf ?? null }
|
||||
} catch {
|
||||
const direct = /^([^%@/]+)(?:@([^%@/]+))?$/.exec(value)
|
||||
return { address: null, interface: direct?.[1] ?? null, vrf: direct?.[2] ?? null }
|
||||
}
|
||||
}
|
||||
|
||||
export function projectRouteLookup(raw: unknown, table: string, destination: string) {
|
||||
const routes: { prefix: string; disposition: "blackhole" | "unreachable" | "prohibit" | "forward"; gateways: string[]; immediateGateways: string[] }[] = []
|
||||
let longest = -1
|
||||
let unknownLongest = -1
|
||||
let limited = false
|
||||
let hopCount = 0
|
||||
for (const row of routeRows.parse(raw)) {
|
||||
if (typeof row["routing-table"] === "string" && row["routing-table"] !== table) continue
|
||||
if (flag(row.active) === false || flag(row.disabled) === true || flag(row.inactive) === true) continue
|
||||
const length = matchingLength(row["dst-address"], destination)
|
||||
if (length === null) {
|
||||
unknownLongest = isIP(destination) === 4 ? 32 : 128
|
||||
continue
|
||||
}
|
||||
if (length < 0) continue
|
||||
if (row["routing-table"] !== table || flag(row.active) !== true) {
|
||||
unknownLongest = Math.max(unknownLongest, length)
|
||||
continue
|
||||
}
|
||||
if (length < longest) continue
|
||||
if (length > longest) {
|
||||
routes.length = 0
|
||||
limited = false
|
||||
hopCount = 0
|
||||
longest = length
|
||||
}
|
||||
if (routes.length === maxRoutePaths) {
|
||||
limited = true
|
||||
continue
|
||||
}
|
||||
const disposition = row.blackhole === "" ? "blackhole" : (["blackhole", "unreachable", "prohibit"] as const)
|
||||
.find(kind => flag(row[kind]) === true || row.type === kind || row.gateway === kind) ?? "forward"
|
||||
const remaining = maxRoutePaths - hopCount
|
||||
const configured = disposition === "forward" ? splitNexthops(row.gateway) : []
|
||||
const resolved = disposition === "forward" ? splitNexthops(row["immediate-gw"]) : []
|
||||
const paths = Math.max(configured.length, resolved.length)
|
||||
limited ||= paths > remaining
|
||||
hopCount += Math.min(paths, remaining)
|
||||
const gateways = configured.slice(0, remaining)
|
||||
const immediateGateways = resolved.slice(0, remaining)
|
||||
routes.push({ prefix: String(row["dst-address"]), disposition, gateways, immediateGateways })
|
||||
}
|
||||
const nextHops = routes.flatMap(route => route.immediateGateways)
|
||||
const nextHopDetails = nextHops.map(nexthopDetails)
|
||||
const incomplete = (unknownLongest >= 0 && unknownLongest >= longest) || limited
|
||||
|| routes.some(route => route.disposition === "forward" && !route.immediateGateways.length)
|
||||
|| nextHopDetails.some(hop => !hop.address && !hop.interface)
|
||||
return { status: incomplete ? "partial" : routes.length ? "matched" : "no-route", incomplete, routes, nextHops, nextHopDetails }
|
||||
}
|
||||
|
||||
function dnsServers(value: unknown) {
|
||||
const items = nativeList(value, 8192, 128)
|
||||
if (!items || items.some(server => {
|
||||
const [address, vrf, extra] = server.split("@")
|
||||
return !isIP(address) || extra !== undefined || (vrf !== undefined && !tableSchema.safeParse(vrf).success)
|
||||
})) return null
|
||||
return items
|
||||
}
|
||||
|
||||
export function projectDnsState(raw: unknown) {
|
||||
const row = Array.isArray(raw) ? z.tuple([rowSchema]).parse(raw)[0] : rowSchema.parse(raw)
|
||||
const allowRemoteRequests = flag(row["allow-remote-requests"])
|
||||
const staticServers = dnsServers(row.servers)
|
||||
const dynamicServers = dnsServers(row["dynamic-servers"])
|
||||
const dohEnabled = typeof row["use-doh-server"] === "string" ? row["use-doh-server"].trim().length > 0 : null
|
||||
return { allowRemoteRequests, staticServers, dynamicServers, dohEnabled,
|
||||
incomplete: [allowRemoteRequests, staticServers, dynamicServers, dohEnabled].includes(null) }
|
||||
}
|
||||
|
||||
export function registerNetworkDiagnosticActions(register: typeof add) {
|
||||
register("network.route.lookup.read", "mm_route_lookup_get",
|
||||
"Поиск самого специфичного активного маршрута IPv4/IPv6 в явно выбранной таблице FIB RouterOS",
|
||||
"network", "mm:network:read", "read", "servers",
|
||||
z.object({ serverId: serverIdSchema, destination: destinationSchema, table: tableSchema }).strict(),
|
||||
{ read: async (input, context) => {
|
||||
const serverId = Number(input.serverId), destination = String(input.destination), table = String(input.table)
|
||||
const family = isIP(destination) === 4 ? "ipv4" : "ipv6"
|
||||
const empty = { routes: [], nextHops: [], nextHopDetails: [] }
|
||||
const observed = { serverId, family, table, destination, forwardingVerified: false, timestampKind: "backend-receipt" }
|
||||
try {
|
||||
const result = await readNetworkValue(serverId, context, tablePath, async (raw, get) => {
|
||||
const state = projectFibTableState(raw, table)
|
||||
if (state !== "ready") return { ...empty, status: state, incomplete: state === "partial" }
|
||||
const resource = family === "ipv4" ? "/ip/route" : "/ipv6/route"
|
||||
const path = `${resource}?.proplist=dst-address,routing-table,active,disabled,inactive,gateway,immediate-gw,blackhole,type&${new URLSearchParams({ "routing-table": table })}`
|
||||
return projectRouteLookup(await get(path), table, destination)
|
||||
})
|
||||
return { ...observed, ...result, observedAt: new Date().toISOString() }
|
||||
} catch (error) {
|
||||
if (!(error instanceof McpError) || error.code !== "STATE_UNAVAILABLE") throw error
|
||||
return { ...observed, ...empty, status: "partial", incomplete: true, reason: "source-unavailable", observedAt: null }
|
||||
}
|
||||
} },
|
||||
)
|
||||
register("network.dns.state.read", "mm_dns_state_get",
|
||||
"Состояние DNS RouterOS: удалённые запросы, статические и динамические серверы и признак настройки DoH",
|
||||
"network", "mm:network:read", "read", "servers", z.object({ serverId: serverIdSchema }).strict(),
|
||||
{ read: async (input, context) => {
|
||||
const serverId = Number(input.serverId)
|
||||
const state = await readNetworkValue(serverId, context, dnsPath, projectDnsState)
|
||||
return { serverId, ...state, observedAt: new Date().toISOString(), timestampKind: "backend-receipt" }
|
||||
} },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { createServer } from "node:http"
|
||||
import type { AddressInfo } from "node:net"
|
||||
import { basename, dirname, isAbsolute } from "node:path"
|
||||
import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
|
||||
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"
|
||||
|
||||
assert.equal(process.env.MMAPP_OWN_NETWORK_DIAGNOSTICS, "true")
|
||||
assert.equal(process.env.NODE_ENV, "test")
|
||||
const database = new URL(process.env.DATABASE_URL ?? "")
|
||||
assert.equal(database.protocol, "postgresql:")
|
||||
assert.equal(database.hostname, "127.0.0.1")
|
||||
assert.equal(database.username, "mcp_test")
|
||||
assert.equal(database.pathname, "/postgres")
|
||||
assert(database.port && database.password && !database.search && !database.hash)
|
||||
const stateDir = process.env.MCP_STATE_DIR ?? ""
|
||||
assert(isAbsolute(stateDir))
|
||||
assert.equal(basename(stateDir), "state")
|
||||
assert.match(basename(dirname(stateDir)), /^mm-mcp-test-/)
|
||||
|
||||
const { pool, closePool } = await import("../../db/index.js")
|
||||
const { applySqlMigrations } = await import("../../db/migrate.js")
|
||||
const { buildApp } = await import("../../index.js")
|
||||
const { createMcpConnection, updateMcpSettings } = await import("./store.js")
|
||||
const actor = {
|
||||
id: "network-diagnostics-owner", apps: ["mm"],
|
||||
permissions: ["mm:settings:admin", "mm:network:read", "mm:servers:read", "mm:traffic:read", "mm:mcp:read"],
|
||||
expiresAt: Date.now() + 3_600_000,
|
||||
}
|
||||
const operations = {
|
||||
mm_capabilities_get: "capabilities.read",
|
||||
mm_telemetry_health_get: "telemetry.health.read",
|
||||
mm_incident_timeline_get: "incident.timeline.read",
|
||||
mm_route_lookup_get: "network.route.lookup.read",
|
||||
mm_dns_state_get: "network.dns.state.read",
|
||||
mm_resilience_topology_get: "network.resilience.topology.read",
|
||||
mm_resilience_design_preview: "network.resilience.design.read",
|
||||
mm_failover_report_get: "network.resilience.failover.read",
|
||||
}
|
||||
const dnsSecret = "private-doh-url-fixture"
|
||||
const nativeReads: string[] = []
|
||||
const nativeRoutes = new Map<string, unknown>([
|
||||
["/rest/routing/table", [{ name: "main", fib: "true" }]],
|
||||
["/rest/ip/route", [{ "routing-table": "main", "dst-address": "0.0.0.0/0", active: "true",
|
||||
gateway: "192.0.2.1", "immediate-gw": "192.0.2.1%ether1" }]],
|
||||
["/rest/ip/dns", { "allow-remote-requests": "false", servers: "1.1.1.1", "dynamic-servers": "",
|
||||
"use-doh-server": `https://example.invalid/${dnsSecret}` }],
|
||||
])
|
||||
const router = createServer((request, response) => {
|
||||
const path = new URL(request.url ?? "/", "http://127.0.0.1").pathname
|
||||
nativeReads.push(`${request.method} ${path}`)
|
||||
const value = nativeRoutes.get(path)
|
||||
response.writeHead(request.method === "GET" && value !== undefined ? 200 : 404, { "content-type": "application/json" })
|
||||
response.end(JSON.stringify(value ?? {}))
|
||||
})
|
||||
const sdkClient = () => new Client({ name: "owned-network-diagnostics", version: "1.0.0" })
|
||||
let client = sdkClient()
|
||||
const call = (name: keyof typeof operations, args: Record<string, unknown>) => client.callTool({ name, arguments: args })
|
||||
async function read<T>(name: keyof typeof operations, args: Record<string, unknown>) {
|
||||
const response = await call(name, args)
|
||||
assert(!response.isError, `${name}: ${JSON.stringify(response.content)}`)
|
||||
const result = (response.structuredContent as { result?: T } | undefined)?.result
|
||||
assert(result !== undefined, `Missing structured result for ${name}`)
|
||||
return result
|
||||
}
|
||||
async function deny(name: keyof typeof operations, args: Record<string, unknown>, code: string) {
|
||||
const response = await call(name, args)
|
||||
assert.equal(response.isError, true, name)
|
||||
assert(JSON.stringify(response.content).includes(code), `${name}: ${JSON.stringify(response.content)}`)
|
||||
}
|
||||
|
||||
let app: Awaited<ReturnType<typeof buildApp>> | undefined
|
||||
try {
|
||||
await applySqlMigrations(pool)
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM servers")).rows[0].n, 0)
|
||||
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
|
||||
const port = (router.address() as AddressInfo).port
|
||||
await pool.query(`INSERT INTO servers(id,name,host,port,use_ssl,verify_ssl,username,password,enabled)
|
||||
VALUES (1,'scoped-router','127.0.0.1',$1,false,false,'owned','fixture',true),
|
||||
(2,'foreign-router','127.0.0.1',$1,false,false,'owned','fixture',true)`, [port])
|
||||
const now = Date.now()
|
||||
const instant = (offset: number) => new Date(now + offset).toISOString()
|
||||
const [localAt, foreignAt] = [instant(-2_000), instant(-1_000)]
|
||||
await pool.query("UPDATE router_log_settings SET enabled=true,interval_sec=3600 WHERE id=1")
|
||||
for (const [id, eventAt, message] of [[1, localAt, "local-log-fixture"], [2, foreignAt, "foreign-log-fixture"]] as const) {
|
||||
await pool.query(`INSERT INTO router_log_collection_state(server_id,server_name,host,last_collected_at)
|
||||
VALUES ($1,'fixture','127.0.0.1',$2)`, [id, eventAt])
|
||||
await pool.query(`INSERT INTO router_log_entries(server_id,server_name,host,router_id,raw_time,event_at,received_at,effective_at,topics,level,message,generation)
|
||||
VALUES ($1,'fixture','127.0.0.1','fixture','fixture',NULL,$2,$2,ARRAY['system'],'info',$3,1)`, [id, eventAt, message])
|
||||
}
|
||||
const segment = async (name: string, peerServerId?: number) => {
|
||||
const id = randomUUID()
|
||||
const configuration = { name, sites: [{ serverId: 1, autonomousSystem: 64512, routerId: "192.0.2.5",
|
||||
interfaces: [{ name: "ether1", kind: "uplink", peerServerId }],
|
||||
groups: [{ id: "internet", gateway: "192.0.2.1", primary: { interface: "ether1", nextHop: "192.0.2.1", probe: "192.0.2.8" } }],
|
||||
exits: ["internet"],
|
||||
}] }
|
||||
await pool.query(`INSERT INTO ix_segments(id,name,revision,configuration) VALUES ($1,$2,1,$3)`, [id, name, configuration])
|
||||
return { kind: "ix-segment", segmentId: id }
|
||||
}
|
||||
const target = await segment("scoped-segment"), foreignTarget = await segment("foreign-segment", 2)
|
||||
await updateMcpSettings({ enabled: true }, actor)
|
||||
const issue = (audit: boolean) => createMcpConnection(mcpConnectionCreateSchema.parse({
|
||||
name: "Scoped network diagnostics", mode: "observer", expiresAt: instant(600_000),
|
||||
permissions: ["mm:network:read", "mm:servers:read", ...(audit ? ["mm:mcp:read"] : [])],
|
||||
scope: { serverIds: [1], operationIds: Object.values(operations), allowGlobal: false },
|
||||
limits: { callsPerMinute: 120 },
|
||||
}), actor)
|
||||
|
||||
app = await buildApp({ startScheduler: false, logger: false })
|
||||
const address = await app.listen({ host: "127.0.0.1", port: 0 })
|
||||
const connect = (token: string) => client.connect(new StreamableHTTPClientTransport(new URL(`${address}/mcp`),
|
||||
{ requestInit: { headers: { Authorization: `Bearer ${token}` } } }))
|
||||
const access = await issue(false)
|
||||
await connect(access.token)
|
||||
const { tools } = await client.listTools()
|
||||
assert.deepEqual(tools.map(tool => tool.name).sort(), Object.keys(operations).sort())
|
||||
assert(tools.every(tool => tool.annotations?.readOnlyHint === true))
|
||||
const legacy = await read<{ operations: Array<{ id: string; applicability?: unknown }>; schemaVersion: number }>("mm_capabilities_get", {})
|
||||
assert.deepEqual(Object.keys(legacy).sort(), ["operations", "schemaVersion"])
|
||||
assert.equal(legacy.schemaVersion, 1)
|
||||
assert.deepEqual(legacy.operations.map(row => row.id).sort(), Object.values(operations).sort())
|
||||
assert(legacy.operations.every(row => !Object.hasOwn(row, "applicability")))
|
||||
const applicable = await read<{ operations: Array<{ applicability: { decision: string; reasons: Array<{ code: string }> } }> }>(
|
||||
"mm_capabilities_get", { toolName: "mm_route_lookup_get", serverId: 2 })
|
||||
assert.equal(applicable.operations.length, 1)
|
||||
assert.equal(applicable.operations[0].applicability.decision, "denied")
|
||||
assert(applicable.operations[0].applicability.reasons.some(reason => reason.code === "SERVER_DENIED"))
|
||||
|
||||
const health = await read<{ observations: Array<{ source: string; freshness: string; observedAt: string }>; netflowDataQuality: { available: boolean } }>(
|
||||
"mm_telemetry_health_get", { serverId: 1 })
|
||||
assert.deepEqual(health.observations.map(row => row.source).sort(), ["logs", "routeros-poll"])
|
||||
const logs = health.observations.find(row => row.source === "logs")
|
||||
assert.equal(logs?.observedAt, localAt)
|
||||
assert.equal(logs?.freshness, "fresh")
|
||||
assert.equal(health.netflowDataQuality.available, false)
|
||||
assert(!JSON.stringify(health).includes(foreignAt))
|
||||
const fleet = await read<{ items: Array<{ serverId: number }>; nextAfterServerId: number | null }>(
|
||||
"mm_telemetry_health_get", { sources: ["logs"], limit: 1 })
|
||||
assert.deepEqual(fleet.items.map(row => row.serverId), [1])
|
||||
assert.equal(fleet.nextAfterServerId, null)
|
||||
assert(!JSON.stringify(fleet).includes(foreignAt))
|
||||
const window = { from: instant(-60_000), outageAt: instant(-40_000), restoreAt: instant(-20_000), to: instant(0) }
|
||||
const range = { from: window.from, to: window.to, sources: ["logs"] }
|
||||
const timeline = await read<{ items: Array<{ message: string; timestampKind: string }>; coverageVerified: boolean }>(
|
||||
"mm_incident_timeline_get", { serverId: 1, ...range })
|
||||
assert.equal(timeline.items.length, 1)
|
||||
assert.equal(timeline.items[0].message, "local-log-fixture")
|
||||
assert.equal(timeline.items[0].timestampKind, "receipt")
|
||||
assert.equal(timeline.coverageVerified, false)
|
||||
await deny("mm_telemetry_health_get", { serverId: 2 }, "SERVER_DENIED")
|
||||
await deny("mm_incident_timeline_get", { serverId: 2, ...range }, "SERVER_DENIED")
|
||||
await deny("mm_telemetry_health_get", { serverId: 1, sources: ["netflow"] }, "PERMISSION_DENIED")
|
||||
await deny("mm_incident_timeline_get", { serverId: 1, ...range, sources: ["uptime"] }, "PERMISSION_DENIED")
|
||||
await deny("mm_incident_timeline_get", { serverId: 1, ...range, includeManagerEvents: true }, "PERMISSION_DENIED")
|
||||
|
||||
const lookup = { destination: "198.51.100.10", table: "main" }
|
||||
const route = await read<{ status: string; nextHops: string[]; forwardingVerified: boolean }>("mm_route_lookup_get", { serverId: 1, ...lookup })
|
||||
assert.equal(route.status, "matched")
|
||||
assert.deepEqual(route.nextHops, ["192.0.2.1%ether1"])
|
||||
assert.equal(route.forwardingVerified, false)
|
||||
const dns = await read<{ staticServers: string[]; dohEnabled: boolean }>("mm_dns_state_get", { serverId: 1 })
|
||||
assert.deepEqual(dns.staticServers, ["1.1.1.1"])
|
||||
assert.equal(dns.dohEnabled, true)
|
||||
assert(!JSON.stringify(dns).includes(dnsSecret))
|
||||
await deny("mm_route_lookup_get", { serverId: 2, ...lookup }, "SERVER_DENIED")
|
||||
await deny("mm_dns_state_get", { serverId: 2 }, "SERVER_DENIED")
|
||||
|
||||
const topology = await read<{ serverIds: number[]; paths: unknown[]; physicalIndependenceVerified: boolean }>("mm_resilience_topology_get", { target })
|
||||
assert.deepEqual(topology.serverIds, [1])
|
||||
assert.equal(topology.paths.length, 1)
|
||||
assert.equal(topology.physicalIndependenceVerified, false)
|
||||
const design = { scenario: "wan" }
|
||||
const preview = await read<{ suggestedTools: string[] }>("mm_resilience_design_preview", { target, ...design })
|
||||
assert(preview.suggestedTools.includes("mm_ix_segment_get"))
|
||||
const reportArgs = { window, targetFailoverMs: 1000, targetFailbackMs: 1000 }
|
||||
const report = await read<{ status: string; reason: string; managementSsh: string }>("mm_failover_report_get", { target, ...reportArgs })
|
||||
assert.equal(report.status, "inconclusive")
|
||||
assert.equal(report.reason, "NO_SAVED_IX_CONTROL_PROBE_HISTORY")
|
||||
assert.equal(report.managementSsh, "inconclusive")
|
||||
await deny("mm_resilience_topology_get", { target: foreignTarget }, "NOT_FOUND")
|
||||
await deny("mm_resilience_design_preview", { target: foreignTarget, ...design }, "NOT_FOUND")
|
||||
await deny("mm_failover_report_get", { target: foreignTarget, ...reportArgs }, "NOT_FOUND")
|
||||
assert.deepEqual(nativeReads, ["GET /rest/routing/table", "GET /rest/ip/route", "GET /rest/ip/dns"])
|
||||
|
||||
const auditedAccess = await issue(true)
|
||||
const requestId = randomUUID()
|
||||
await pool.query(`INSERT INTO mcp_requests(id,connection_id,actor_id,tool,server_ids,status,input,created_at,finished_at)
|
||||
VALUES ($1,$2,$4,'mm_dns_state_get',ARRAY[1]::bigint[],'succeeded','{"credential":"audit-secret-fixture"}',$5,$5),
|
||||
($6,$3,$4,'mm_dns_state_get',ARRAY[1]::bigint[],'succeeded','{}',$5,$5),
|
||||
($7,$2,$4,'mm_dns_state_get',ARRAY[1,2]::bigint[],'succeeded','{}',$5,$5)`,
|
||||
[requestId, auditedAccess.connection.id, access.connection.id, actor.id, foreignAt, randomUUID(), randomUUID()])
|
||||
await client.close()
|
||||
client = sdkClient()
|
||||
await connect(auditedAccess.token)
|
||||
type TimelinePage = { items: Array<{ id: string; source: string; toolName?: string }>; nextCursor: string | null }
|
||||
const auditArgs = { serverId: 1, ...range, includeManagerEvents: true, limit: 1 }
|
||||
const audited = await read<TimelinePage>("mm_incident_timeline_get", auditArgs)
|
||||
assert.deepEqual(audited.items.map(item => item.source), ["mcp-request"])
|
||||
assert.equal(audited.items[0].id, requestId)
|
||||
assert.equal(audited.items[0].toolName, "mm_dns_state_get")
|
||||
assert(!JSON.stringify(audited).includes("audit-secret-fixture"))
|
||||
assert(audited.nextCursor)
|
||||
const pageArgs = { ...auditArgs, cursor: audited.nextCursor }
|
||||
const next = await read<TimelinePage>("mm_incident_timeline_get", pageArgs)
|
||||
assert.deepEqual(next.items.map(item => item.source), ["logs"])
|
||||
assert.equal(next.nextCursor, null)
|
||||
await deny("mm_incident_timeline_get", { ...pageArgs, includeManagerEvents: false }, "RESET_REQUIRED")
|
||||
|
||||
const { assertSignedResilienceHistory } = await import("../../test/resilience-report-acceptance.js")
|
||||
await assertSignedResilienceHistory({
|
||||
connectionId: auditedAccess.connection.id,
|
||||
foreignConnectionId: access.connection.id,
|
||||
serverId: 1,
|
||||
callReport: input => read("mm_failover_report_get", input),
|
||||
})
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_plans")).rows[0].n, 0)
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_operations")).rows[0].n, 0)
|
||||
} finally {
|
||||
await client.close()
|
||||
await app?.close()
|
||||
if (router.listening) await new Promise<void>((resolve, reject) => router.close(error => error ? reject(error) : resolve()))
|
||||
await closePool()
|
||||
}
|
||||
@@ -44,7 +44,7 @@ function catalogRows<T>(value: unknown, project: (text: (key: string) => string
|
||||
}).sort((left, right) => left.id.localeCompare(right.id))
|
||||
}
|
||||
|
||||
async function readNetworkValue<T>(serverId: number, context: ActionContext, path: string, project: (raw: unknown) => T) {
|
||||
export async function readNetworkValue<T>(serverId: number, context: ActionContext, path: string, project: (raw: unknown, get: (path: string) => Promise<unknown>) => T | Promise<T>) {
|
||||
const authorize = async () => {
|
||||
if (context.signal?.aborted) throw new McpError("READ_CANCELLED", "Чтение сетевого каталога отменено", 409)
|
||||
const current = await effectiveMcpConnection(context.principal)
|
||||
@@ -57,8 +57,8 @@ async function readNetworkValue<T>(serverId: number, context: ActionContext, pat
|
||||
const check = async () => { await authorize(); await source.assertCurrent(); await authorize() }
|
||||
try {
|
||||
const { client } = await routerClient(serverId)
|
||||
const raw = await client.get<unknown>(path, 10000, context.signal, 1048576, check)
|
||||
const value = project(raw)
|
||||
const get = (resource: string) => client.get<unknown>(resource, 10000, context.signal, 1048576, check)
|
||||
const value = await project(await get(path), get)
|
||||
await check()
|
||||
return value
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing"
|
||||
import { assessFailover, routePaths, summarizePaths } from "./resilience-actions.js"
|
||||
|
||||
const first = { id: "a", wanInterface: "ether1", jumpHostId: 2, exitNodeId: 3,
|
||||
downstreamInterface: "wg-a", gateway: "192.0.2.1", gatewayRef: { resource: "ipv4_route", id: "*a" } }
|
||||
const second = { ...first, id: "b", jumpHostId: 4, exitNodeId: 5, downstreamInterface: "wg-b" }
|
||||
|
||||
function topology(reserve: typeof second) {
|
||||
const profile = routeAiProfileSchema.parse({ name: "failover", community: "65000:1", family: "ipv4", serverId: 1, candidates: [first, reserve] })
|
||||
return summarizePaths(routePaths(profile))
|
||||
}
|
||||
|
||||
test("different jump and exit nodes still share a WAN on the origin router", () => {
|
||||
const result = topology(second)
|
||||
assert.deepEqual(result.sharedDomains, [
|
||||
{ kind: "source", serverId: 1, pathIds: ["a", "b"] },
|
||||
{ kind: "wan", serverId: 1, interfaceName: "ether1", pathIds: ["a", "b"] },
|
||||
])
|
||||
assert.equal(result.physicalIndependenceVerified, false)
|
||||
})
|
||||
|
||||
test("logically disjoint WAN, jump and exit nodes retain an unknown physical domain", () => {
|
||||
const result = topology({ ...second, wanInterface: "ether2" })
|
||||
assert.deepEqual(result.sharedDomains, [{ kind: "source", serverId: 1, pathIds: ["a", "b"] }])
|
||||
assert.ok(result.unknownDomains.includes("carrier"))
|
||||
assert.equal(result.physicalIndependenceVerified, false)
|
||||
})
|
||||
|
||||
test("pinned profiles retain the other path for inspection and exclude it from eligible reserve", () => {
|
||||
const profile = routeAiProfileSchema.parse({
|
||||
name: "pinned", community: "65000:1", family: "ipv4", serverId: 1, pinnedCandidateId: "a",
|
||||
candidates: [{ ...first, wanRemoteInterface: "wan-up", downstreamRemoteInterface: "wg-remote" }, second],
|
||||
})
|
||||
const result = summarizePaths(routePaths(profile))
|
||||
assert.deepEqual(result.eligiblePathIds, ["a"])
|
||||
assert.deepEqual(result.sharedDomains, [])
|
||||
assert.deepEqual(result.paths[0].dependencies.slice(-2), [
|
||||
{ kind: "wan", serverId: 2, interfaceName: "wan-up" },
|
||||
{ kind: "tunnel", serverId: 3, interfaceName: "wg-remote" },
|
||||
])
|
||||
})
|
||||
|
||||
test("separate IX groups with a single eligible path do not form a reserve pair", () => {
|
||||
const profile = routeAiProfileSchema.parse({ name: "failover", community: "65000:1", family: "ipv4", serverId: 1, candidates: [first, second] })
|
||||
const paths = routePaths(profile).map((path, index) => ({ ...path, groupId: `${index + 2}/exit` }))
|
||||
assert.deepEqual(summarizePaths(paths).alternativeGroups, [
|
||||
{ groupId: "2/exit", eligiblePathIds: ["a"] },
|
||||
{ groupId: "3/exit", eligiblePathIds: ["b"] },
|
||||
])
|
||||
})
|
||||
|
||||
const time = (offset: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, 0, offset)).toISOString()
|
||||
const request = {
|
||||
target: { kind: "route-ai" as const, profileId: "1551445f-7c71-4411-976f-ce30302dcefe" },
|
||||
window: { from: time(0), outageAt: time(3000), restoreAt: time(10000), to: time(20000) },
|
||||
controlProbe: { primaryCandidateId: "a", backupCandidateId: "b" },
|
||||
targetFailoverMs: 1000, targetFailbackMs: 1000,
|
||||
}
|
||||
const probe = (candidateId: string, status: "passed" | "failed" | "unknown", begin: number, end: number) => ({
|
||||
id: candidateId + begin, candidateId, status, startedAt: time(begin), observedAt: time(end),
|
||||
})
|
||||
const baseline = probe("a", "passed", 2500, 2700)
|
||||
const failure = probe("a", "failed", 3100, 3300)
|
||||
const recovered = probe("a", "passed", 10100, 10500)
|
||||
|
||||
test("report passes each probe deadline and leaves HTTPS, SSH and existing connections unverified", () => {
|
||||
const result = assessFailover(request, [baseline, failure, probe("b", "failed", 3100, 3400), probe("b", "passed", 3500, 3800), recovered])
|
||||
assert.equal(result.status, "passed")
|
||||
assert.equal(result.failover.lowerBoundMs, 100)
|
||||
assert.equal(result.failover.upperBoundMs, 800)
|
||||
assert.equal(result.failover.firstGood?.id, "b3500")
|
||||
assert.equal(result.failback.upperBoundMs, 500)
|
||||
assert.equal(result.https, "inconclusive")
|
||||
assert.equal(result.serviceFailover, "inconclusive")
|
||||
assert.equal(result.existingConnections, "inconclusive")
|
||||
assert.equal(result.managementSsh, "inconclusive")
|
||||
assert.equal(result.returnPathVerified, false)
|
||||
})
|
||||
|
||||
test("report fails when the latest definitive failed probe started after the deadline", () => {
|
||||
const result = assessFailover(request, [baseline, failure, probe("b", "failed", 4500, 4700), probe("b", "passed", 4800, 5000), recovered])
|
||||
assert.equal(result.status, "failed")
|
||||
assert.equal(result.failover.lowerBoundMs, 1500)
|
||||
assert.equal(result.failover.upperBoundMs, 2000)
|
||||
assert.equal(result.failover.lastBad?.id, "b4500")
|
||||
})
|
||||
|
||||
test("late first success, unknown evidence, flap, or truncated history cannot establish success", () => {
|
||||
const history = [baseline, failure, recovered]
|
||||
assert.equal(assessFailover(request, [...history, probe("b", "passed", 4500, 4700)]).status, "inconclusive")
|
||||
assert.equal(assessFailover(request, [...history, probe("b", "unknown", 4500, 4700)]).status, "inconclusive")
|
||||
const pass = probe("b", "passed", 3500, 3700)
|
||||
assert.equal(assessFailover(request, [...history, pass, probe("b", "failed", 3800, 4000)]).status, "inconclusive")
|
||||
assert.equal(assessFailover(request, [...history, pass], true).status, "inconclusive")
|
||||
assert.equal(assessFailover(request, [baseline, probe("a", "unknown", 3100, 3300), recovered, pass]).status, "inconclusive")
|
||||
})
|
||||
@@ -0,0 +1,352 @@
|
||||
import { z } from "zod"
|
||||
import { routeAiProfileSchema, type RouteAiProfile } from "@mmapp/contracts/mcp-routing"
|
||||
import type { IxSegment } from "@mmapp/contracts/internet-exchange"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { ixDeviceIds } from "../../services/internet-exchange-plan.js"
|
||||
import { readIxRevision, readIxSegment } from "../../services/internet-exchange-store.js"
|
||||
import type { add } from "./actions.js"
|
||||
import type { ActionContext } from "./action-types.js"
|
||||
import { PATH_PROOF_VERSION, pathProofTag } from "./path-proof-purpose.js"
|
||||
import { constantEqual, fingerprint, McpError, privateFingerprinterExisting } from "./security.js"
|
||||
|
||||
const siteId = z.number().int().positive().safe()
|
||||
const name = z.string().trim().min(1).max(100)
|
||||
const targetSchema = z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("route-ai"), profileId: z.uuid() }).strict(),
|
||||
z.object({ kind: z.literal("ix-segment"), segmentId: z.uuid() }).strict(),
|
||||
z.object({ kind: z.literal("ix-client"), segmentId: z.uuid(), serverId: siteId, interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) }).strict(),
|
||||
])
|
||||
const topologyArgs = z.object({ target: targetSchema }).strict()
|
||||
const serviceEndpoint = z.object({
|
||||
serverId: siteId.optional(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/).optional(),
|
||||
address: z.union([z.ipv4(), z.ipv6()]).optional(),
|
||||
}).strict().refine(endpoint => endpoint.serverId !== undefined || endpoint.address !== undefined)
|
||||
const designArgs = topologyArgs.extend({
|
||||
scenario: z.enum(["wan", "jump-host", "exit", "tunnel", "return", "flap"]),
|
||||
offset: z.number().int().min(0).max(1000).default(0),
|
||||
limit: z.number().int().min(1).max(25).default(10),
|
||||
protectedService: z.object({
|
||||
name, source: serviceEndpoint.optional(), destination: serviceEndpoint.optional(),
|
||||
maxInterruptionMs: z.number().int().min(1).max(3600000).optional(),
|
||||
}).strict().optional(),
|
||||
})
|
||||
const timestamp = z.iso.datetime({ offset: true })
|
||||
const reportArgs = topologyArgs.extend({
|
||||
controlProbe: z.object({ primaryCandidateId: name, backupCandidateId: name }).strict().optional(),
|
||||
window: z.object({ from: timestamp, outageAt: timestamp, restoreAt: timestamp, to: timestamp }).strict(),
|
||||
targetFailoverMs: z.number().int().min(1).max(3600000),
|
||||
targetFailbackMs: z.number().int().min(1).max(3600000),
|
||||
})
|
||||
|
||||
type Target = z.infer<typeof targetSchema>
|
||||
type ReportArgs = z.infer<typeof reportArgs>
|
||||
type Domain = { kind: "source" | "wan" | "jump-host" | "exit" | "tunnel" | "peer"; serverId: number; interfaceName?: string }
|
||||
type Path = { id: string; groupId: string; eligible: boolean; dependencies: Domain[] }
|
||||
type Source = { target: Target; serverIds: number[] } & (
|
||||
{ kind: "route-ai"; profile: RouteAiProfile; revision: number } |
|
||||
{ kind: "ix"; segment: IxSegment; paths: Path[] }
|
||||
)
|
||||
|
||||
export function routePaths(profile: RouteAiProfile): Path[] {
|
||||
return profile.candidates.map(candidate => ({
|
||||
id: candidate.id,
|
||||
groupId: "route-ai",
|
||||
eligible: !profile.excludedCandidateIds.includes(candidate.id) &&
|
||||
(profile.pinnedCandidateId === null || profile.pinnedCandidateId === candidate.id),
|
||||
dependencies: [
|
||||
{ kind: "source", serverId: profile.serverId },
|
||||
{ kind: "wan", serverId: profile.serverId, interfaceName: candidate.wanInterface },
|
||||
{ kind: "jump-host", serverId: candidate.jumpHostId },
|
||||
{ kind: "exit", serverId: candidate.exitNodeId },
|
||||
{ kind: "tunnel", serverId: candidate.jumpHostId, interfaceName: candidate.downstreamInterface },
|
||||
...(candidate.wanRemoteInterface ? [{ kind: "wan" as const, serverId: candidate.jumpHostId, interfaceName: candidate.wanRemoteInterface }] : []),
|
||||
...(candidate.downstreamRemoteInterface ? [{ kind: "tunnel" as const, serverId: candidate.exitNodeId, interfaceName: candidate.downstreamRemoteInterface }] : []),
|
||||
],
|
||||
}))
|
||||
}
|
||||
|
||||
export function summarizePaths(paths: Path[]) {
|
||||
const domains = new Map<string, { domain: Domain; pathIds: Set<string> }>()
|
||||
const eligibleGroups = new Map<string, string[]>()
|
||||
for (const path of paths.filter(path => path.eligible)) {
|
||||
const alternatives = eligibleGroups.get(path.groupId) ?? []
|
||||
alternatives.push(path.id)
|
||||
eligibleGroups.set(path.groupId, alternatives)
|
||||
for (const domain of path.dependencies) {
|
||||
const key = domain.kind === "wan" || domain.kind === "tunnel"
|
||||
? JSON.stringify([domain.serverId, domain.interfaceName])
|
||||
: JSON.stringify([domain.serverId])
|
||||
const record = domains.get(key) ?? { domain, pathIds: new Set<string>() }
|
||||
record.pathIds.add(path.id)
|
||||
domains.set(key, record)
|
||||
}
|
||||
}
|
||||
return {
|
||||
paths,
|
||||
eligiblePathIds: paths.filter(path => path.eligible).map(path => path.id),
|
||||
alternativeGroups: [...eligibleGroups].map(([groupId, eligiblePathIds]) => ({ groupId, eligiblePathIds })),
|
||||
sharedDomains: [...domains.values()].filter(value => value.pathIds.size > 1).map(value => ({
|
||||
...value.domain, pathIds: [...value.pathIds],
|
||||
})),
|
||||
unknownDomains: ["physical-uplink", "carrier", "power", "facility", "management", "return-path"],
|
||||
physicalIndependenceVerified: false,
|
||||
}
|
||||
}
|
||||
|
||||
function ixPaths(segment: IxSegment, target: Extract<Target, { kind: "ix-segment" | "ix-client" }>): Path[] {
|
||||
const paths: Path[] = []
|
||||
let bindingFound = false
|
||||
for (const site of segment.configuration.sites) {
|
||||
const client = target.kind === "ix-client" && target.serverId === site.serverId
|
||||
? site.interfaces.find(binding => binding.name === target.interfaceName && binding.linux)
|
||||
: undefined
|
||||
if (target.kind === "ix-client" && !client) continue
|
||||
if (client) bindingFound = true
|
||||
const selectedExits = client?.linux?.exit ? [client.linux.exit] : site.exits
|
||||
for (const group of site.groups) {
|
||||
if (client && !selectedExits.includes(group.id)) continue
|
||||
for (const role of ["primary", "backup"] as const) {
|
||||
const path = group[role]
|
||||
if (!path) continue
|
||||
const binding = site.interfaces.find(item => item.name === path.interface)
|
||||
const remote = binding?.peerServerId
|
||||
const dependencies: Domain[] = [
|
||||
{ kind: "source", serverId: site.serverId },
|
||||
{ kind: path.viaMain || binding?.kind === "uplink" ? "wan" : "tunnel", serverId: site.serverId, interfaceName: path.interface },
|
||||
]
|
||||
if (client) dependencies.push({ kind: "tunnel", serverId: site.serverId, interfaceName: client.name })
|
||||
if (remote !== undefined) {
|
||||
dependencies.push({ kind: selectedExits.includes(group.id) ? "exit" : "peer", serverId: remote })
|
||||
const remoteWan = binding?.provisionTransit?.remoteWan.interface
|
||||
if (remoteWan) dependencies.push({ kind: "wan", serverId: remote, interfaceName: remoteWan })
|
||||
}
|
||||
paths.push({
|
||||
id: `${site.serverId}/${group.id}/${role}`,
|
||||
groupId: `${site.serverId}/${group.id}`,
|
||||
eligible: client?.linux?.enabled ?? true,
|
||||
dependencies,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
if (target.kind === "ix-client" && !bindingFound) throw new McpError("NOT_FOUND", "Подключение IX не найдено", 404)
|
||||
return paths
|
||||
}
|
||||
|
||||
async function resolve(target: Target, context: ActionContext): Promise<Source> {
|
||||
const allowed = context.connection.policy.scope.serverIds
|
||||
const inScope = (ids: number[]) => ids.every(id => allowed.includes(id))
|
||||
if (target.kind === "route-ai") {
|
||||
const { rows: [row] } = await (context.transactionClient ?? pool).query(
|
||||
"SELECT version,config FROM mcp_routing_profiles WHERE id=$1 AND connection_id=$2",
|
||||
[target.profileId, context.connection.id],
|
||||
)
|
||||
if (!row) throw new McpError("NOT_FOUND", "Профиль Route AI не найден", 404)
|
||||
const profile = routeAiProfileSchema.parse(row.config)
|
||||
const serverIds = [...new Set([profile.serverId, ...profile.candidates.flatMap(candidate => [candidate.jumpHostId, candidate.exitNodeId])])]
|
||||
if (!inScope(serverIds)) throw new McpError("NOT_FOUND", "Профиль Route AI не найден", 404)
|
||||
return { kind: target.kind, target, profile, serverIds, revision: row.version }
|
||||
}
|
||||
|
||||
const segment = await readIxSegment(target.segmentId, context.transactionClient)
|
||||
if (!segment || !inScope(ixDeviceIds(segment.configuration))) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
|
||||
const applied = segment.appliedRevision !== null && segment.appliedRevision !== segment.revision
|
||||
? await readIxRevision(segment.id, segment.appliedRevision)
|
||||
: null
|
||||
const serverIds = [...new Set([...ixDeviceIds(segment.configuration), ...(applied ? ixDeviceIds(applied) : [])])]
|
||||
if (!inScope(serverIds)) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
|
||||
return { kind: "ix", target, segment, serverIds, paths: ixPaths(segment, target) }
|
||||
}
|
||||
|
||||
function topology(source: Source) {
|
||||
const { target, serverIds } = source
|
||||
const details = source.kind === "route-ai"
|
||||
? { source: "saved-route-ai-profile", revision: source.revision, pinnedCandidateId: source.profile.pinnedCandidateId }
|
||||
: { source: "saved-ix-configuration", revision: source.segment.revision, appliedRevision: source.segment.appliedRevision }
|
||||
return { target, serverIds, ...details, ...summarizePaths(source.kind === "route-ai" ? routePaths(source.profile) : source.paths) }
|
||||
}
|
||||
|
||||
const design = {
|
||||
wan: { tools: ["mm_server_wan_runtime_get", "mm_recursive_routes_get", "mm_recursive_routes_replace_plan"], criteria: "Разные WAN и next hop, с проверкой физической независимости линий." },
|
||||
"jump-host": { tools: ["mm_route_optimizer_analyze", "mm_ospf_application_preview"], criteria: "Разнести транзит по разным узлам и проверить общие зависимости кандидатов." },
|
||||
exit: { tools: ["mm_route_optimizer_analyze", "mm_bgp_sessions_get", "mm_ecmp_plan"], criteria: "Проверить независимость выходов, NAT, анонсы и доступность префиксов со стороны назначения." },
|
||||
tunnel: { tools: ["mm_wireguard_state_get", "mm_ospf_state_get", "mm_recursive_routes_get"], criteria: "Проверить тоннели, выбранный маршрут и детектирование отказа подложки." },
|
||||
return: { tools: ["mm_route_optimizer_analyze", "mm_route_path_verify"], criteria: "Проверить предпочтительный путь после восстановления, обратное направление и сохранение доступа управления вне переключаемого пути." },
|
||||
flap: { tools: ["mm_route_controller_get", "mm_route_profile_save_plan"], criteria: "Сопоставить интервалы наблюдений, подтверждения, гистерезис, cooldown и бюджет переключений с допустимым временем восстановления." },
|
||||
} as const
|
||||
|
||||
function scenarioFailures(paths: Path[], scenario: keyof typeof design) {
|
||||
if (scenario === "return" || scenario === "flap") return []
|
||||
const eligible = paths.filter(path => path.eligible)
|
||||
const failures = new Map<string, { groupId: string; domain: Domain }>()
|
||||
for (const path of eligible) {
|
||||
for (const domain of path.dependencies.filter(domain => domain.kind === scenario)) {
|
||||
failures.set(JSON.stringify([path.groupId, domain.serverId, domain.interfaceName]), { groupId: path.groupId, domain })
|
||||
}
|
||||
}
|
||||
return [...failures.values()].map(({ groupId, domain }) => ({
|
||||
groupId, domain,
|
||||
remainingEligiblePathIds: eligible.filter(path => path.groupId === groupId && !path.dependencies.some(dependency =>
|
||||
dependency.serverId === domain.serverId &&
|
||||
(domain.interfaceName === undefined || dependency.interfaceName === domain.interfaceName),
|
||||
)).map(path => path.id),
|
||||
}))
|
||||
}
|
||||
|
||||
type Observation = { id: string; candidateId: string; status: "passed" | "failed" | "unknown"; startedAt: string; observedAt: string }
|
||||
type PhaseStatus = "passed" | "failed" | "inconclusive"
|
||||
const at = (date: string) => Date.parse(date)
|
||||
|
||||
function phase(observations: Observation[], start: number, end: number, targetMs: number, goodAfter = start) {
|
||||
const samples = observations.filter(row => at(row.startedAt) >= start && at(row.observedAt) <= end)
|
||||
.sort((left, right) => at(left.observedAt) - at(right.observedAt))
|
||||
const firstGood = samples.find(row => row.status === "passed" && at(row.startedAt) >= goodAfter)
|
||||
const lastBad = samples.filter(row => row.status === "failed" && (!firstGood || at(row.observedAt) <= at(firstGood.startedAt))).at(-1)
|
||||
const subsequentFailure = firstGood && samples.find(row => row.status === "failed" && at(row.startedAt) >= at(firstGood.observedAt))
|
||||
const lowerBoundMs = (lastBad ? at(lastBad.startedAt) : start) - start
|
||||
const upperBoundMs = firstGood ? at(firstGood.observedAt) - start : null
|
||||
const ambiguous = firstGood && samples.some(row => row.status === "failed" &&
|
||||
at(row.startedAt) < at(firstGood.observedAt) && at(row.observedAt) > at(firstGood.startedAt))
|
||||
const status: PhaseStatus = ambiguous || subsequentFailure ? "inconclusive"
|
||||
: upperBoundMs !== null && upperBoundMs <= targetMs ? "passed"
|
||||
: lowerBoundMs > targetMs ? "failed" : "inconclusive"
|
||||
return { status, lowerBoundMs, upperBoundMs, targetMs, firstGood: firstGood ?? null, lastBad: lastBad ?? null, subsequentFailure: subsequentFailure ?? null }
|
||||
}
|
||||
|
||||
export function assessFailover(input: ReportArgs, observations: Observation[], truncated = false) {
|
||||
const { window, controlProbe } = input
|
||||
const ordered = [...observations].sort((left, right) => at(left.observedAt) - at(right.observedAt))
|
||||
const primary = ordered.filter(row => row.candidateId === controlProbe?.primaryCandidateId)
|
||||
const backup = ordered.filter(row => row.candidateId === controlProbe?.backupCandidateId)
|
||||
const outage = at(window.outageAt), restore = at(window.restoreAt)
|
||||
const latestBaseline = primary.filter(row => at(row.startedAt) >= at(window.from) && at(row.observedAt) < outage).at(-1)
|
||||
const baseline = latestBaseline?.status === "passed" ? latestBaseline : null
|
||||
const primaryFailure = primary.find(row => row.status === "failed" && at(row.startedAt) >= outage && at(row.observedAt) < restore) ?? null
|
||||
const failover = phase(backup, outage, restore - 1, input.targetFailoverMs, primaryFailure ? at(primaryFailure.observedAt) : restore)
|
||||
const failback = phase(primary, restore, at(window.to), input.targetFailbackMs)
|
||||
const status: PhaseStatus = truncated || !baseline || !primaryFailure ? "inconclusive"
|
||||
: [failover.status, failback.status].includes("failed") ? "failed"
|
||||
: failover.status === "passed" && failback.status === "passed" ? "passed" : "inconclusive"
|
||||
return {
|
||||
status, scope: "configured-control-probe-reachability", baseline, primaryFailure, failover, failback,
|
||||
restoredPath: failback.firstGood ? "control-probe-observed" : "inconclusive",
|
||||
serviceFailover: "inconclusive", https: "inconclusive", existingConnections: "inconclusive", managementSsh: "inconclusive",
|
||||
forwardingSelectionVerified: false, returnPathVerified: false, truncated,
|
||||
}
|
||||
}
|
||||
|
||||
const savedObservation = z.object({
|
||||
id: z.uuid(), connectionId: z.uuid(), profileHash: z.string(), candidateId: name,
|
||||
proofPurpose: z.literal("control-path"), proofVersion: z.literal(PATH_PROOF_VERSION),
|
||||
dependencyProof: z.string().regex(/^[a-f0-9]{64}$/), status: z.enum(["passed", "failed", "unknown"]), startedAt: timestamp, observedAt: timestamp,
|
||||
sourceProofs: z.array(z.object({ serverId: siteId, proof: z.string().regex(/^[a-f0-9]{64}$/) }).strict()).min(1).max(3),
|
||||
})
|
||||
|
||||
async function report(input: ReportArgs, source: Source, context: ActionContext) {
|
||||
const { window, controlProbe } = input
|
||||
const from = at(window.from), outage = at(window.outageAt), restore = at(window.restoreAt), to = at(window.to)
|
||||
if (!(from < outage && outage < restore && restore < to && to <= Date.now() && to - from <= 86400000)) {
|
||||
throw new McpError("INVALID_INPUT", "Окно должно быть завершено, не длиннее 24 часов и включать фазы до отказа, после отказа и после восстановления", 400)
|
||||
}
|
||||
if (source.kind !== "route-ai") return { ...assessFailover(input, []), target: input.target, window, reason: "NO_SAVED_IX_CONTROL_PROBE_HISTORY" }
|
||||
if (!controlProbe || controlProbe.primaryCandidateId === controlProbe.backupCandidateId ||
|
||||
![controlProbe.primaryCandidateId, controlProbe.backupCandidateId].every(id => source.profile.candidates.some(candidate => candidate.id === id && candidate.controlProbe))) {
|
||||
throw new McpError("INVALID_INPUT", "Выберите два разных кандидата с контрольной пробой из сохранённого профиля", 400)
|
||||
}
|
||||
const connectionId = context.connection.id
|
||||
const profileHash = fingerprint(source.profile)
|
||||
const { rows } = await pool.query<{ id: string; candidate_id: string; status: string; evidence: Record<string, unknown> | null }>(
|
||||
`SELECT id,candidate_id,status,CASE WHEN octet_length(evidence::text)<=32768 THEN evidence END AS evidence FROM mcp_path_checks
|
||||
WHERE connection_id=$1 AND profile_hash=$2 AND candidate_id=ANY($3::text[])
|
||||
AND created_at >= $4::timestamptz AND created_at <= $5::timestamptz
|
||||
AND evidence->>'proofPurpose' IS DISTINCT FROM 'community'
|
||||
ORDER BY created_at,id LIMIT 501`,
|
||||
[connectionId, profileHash, [controlProbe.primaryCandidateId, controlProbe.backupCandidateId], window.from, window.to],
|
||||
)
|
||||
const sign = rows.length ? await privateFingerprinterExisting("route-control-path-context-v1").catch(error => {
|
||||
if (error instanceof McpError && error.code === "STATE_UNAVAILABLE") return null
|
||||
throw error
|
||||
}) : null
|
||||
const observations: Observation[] = []
|
||||
const sourceProofs = new Map<number, string>()
|
||||
let evidenceError: "INVALID_CONTROL_PATH_EVIDENCE" | "SOURCE_IDENTITY_CHANGED" | null = null
|
||||
for (const row of rows.slice(0, 500)) {
|
||||
const { proof, ...payload } = row.evidence ?? {}
|
||||
const parsed = savedObservation.safeParse(payload)
|
||||
if (!parsed.success || !sign || typeof proof !== "string") {
|
||||
evidenceError = "INVALID_CONTROL_PATH_EVIDENCE"
|
||||
break
|
||||
}
|
||||
const { id, status, candidateId, startedAt, observedAt, dependencyProof } = parsed.data
|
||||
const candidate = source.profile.candidates.find(candidate => candidate.id === candidateId)
|
||||
const expected = new Set([source.profile.serverId, candidate?.jumpHostId, candidate?.exitNodeId])
|
||||
const observed = new Set(parsed.data.sourceProofs.map(source => source.serverId))
|
||||
if (id !== row.id || status !== row.status || candidateId !== row.candidate_id ||
|
||||
parsed.data.connectionId !== connectionId || parsed.data.profileHash !== profileHash ||
|
||||
at(startedAt) > at(observedAt) || observed.size !== parsed.data.sourceProofs.length ||
|
||||
expected.size !== observed.size || ![...expected].every(id => id !== undefined && observed.has(id)) ||
|
||||
!constantEqual(sign(pathProofTag("control-path") + fingerprint({ dependencyProof, value: payload })), proof)) {
|
||||
evidenceError = "INVALID_CONTROL_PATH_EVIDENCE"
|
||||
break
|
||||
}
|
||||
if (at(startedAt) < from || at(observedAt) > to) continue
|
||||
for (const source of parsed.data.sourceProofs) {
|
||||
if (sourceProofs.has(source.serverId) && sourceProofs.get(source.serverId) !== source.proof) evidenceError = "SOURCE_IDENTITY_CHANGED"
|
||||
sourceProofs.set(source.serverId, source.proof)
|
||||
}
|
||||
observations.push({ id, status, candidateId, startedAt, observedAt })
|
||||
}
|
||||
const result = assessFailover(input, evidenceError ? [] : observations, rows.length > 500)
|
||||
const eligible = routePaths(source.profile).filter(path => path.eligible).map(path => path.id)
|
||||
const reason = rows.length && !sign ? "PROOF_KEY_UNAVAILABLE" : evidenceError ?? (
|
||||
!eligible.includes(controlProbe.primaryCandidateId) || !eligible.includes(controlProbe.backupCandidateId) ? "CANDIDATE_UNAVAILABLE_IN_PROFILE" : null)
|
||||
return { target: input.target, window, controlProbe, ...result,
|
||||
...(reason ? { status: "inconclusive" as const, reason } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function registerResilienceActions(register: typeof add) {
|
||||
const target = async (input: Record<string, unknown>, context: ActionContext) => ({
|
||||
scope: "servers" as const, serverIds: (await resolve(targetSchema.parse(input.target), context)).serverIds,
|
||||
})
|
||||
register("network.resilience.topology.read", "mm_resilience_topology_get", "Зависимости путей и общие домены отказа", "network", "mm:network:read", "read", "servers", topologyArgs, {
|
||||
target,
|
||||
read: async (input, context) => topology(await resolve(topologyArgs.parse(input).target, context)),
|
||||
})
|
||||
register("network.resilience.design.read", "mm_resilience_design_preview", "Предпросмотр резервирования по сценарию отказа", "network", "mm:network:read", "read", "servers", designArgs, {
|
||||
target,
|
||||
read: async (input, context) => {
|
||||
const args = designArgs.parse(input)
|
||||
const source = await resolve(args.target, context)
|
||||
const serviceServers = [args.protectedService?.source?.serverId, args.protectedService?.destination?.serverId]
|
||||
if (serviceServers.some(id => id !== undefined && !source.serverIds.includes(id))) {
|
||||
throw new McpError("INVALID_INPUT", "Устройство защищаемого сервиса вне выбранной топологии", 400)
|
||||
}
|
||||
const observed = topology(source)
|
||||
const proposal = design[args.scenario]
|
||||
const failures = scenarioFailures(observed.paths, args.scenario)
|
||||
const tools = source.kind === "ix"
|
||||
? ["mm_ix_segment_get", "mm_ix_change_plan", ...(args.target.kind === "ix-client" ? ["mm_ix_linux_path_get"] : []),
|
||||
...proposal.tools.filter(tool => !tool.startsWith("mm_route_") && !tool.endsWith("_plan"))]
|
||||
: [...proposal.tools]
|
||||
return {
|
||||
target: args.target, scenario: args.scenario, protectedService: args.protectedService ?? null,
|
||||
criteria: proposal.criteria, suggestedTools: tools,
|
||||
eligiblePathIds: observed.eligiblePathIds, alternativeGroups: observed.alternativeGroups,
|
||||
configuredReserve: observed.alternativeGroups.some(group => group.eligiblePathIds.length > 1),
|
||||
configuredPathsAfterFailure: failures.slice(args.offset, args.offset + args.limit),
|
||||
nextOffset: args.offset + args.limit < failures.length ? args.offset + args.limit : null,
|
||||
sharedDomains: observed.sharedDomains, unknownDomains: observed.unknownDomains,
|
||||
missingEvidence: ["usable-capacity", "path-mtu", "return-path", "service-interruption", "management-reachability"],
|
||||
requiredChecks: ["Отдельная проверка активного маршрута и обратного направления", "Непрерывность HTTPS, действующих соединений и независимого SSH-управления по отдельным измерениям"],
|
||||
}
|
||||
},
|
||||
})
|
||||
register("network.resilience.failover.read", "mm_failover_report_get", "Оценка failover и failback по сохранённым контрольным пробам", "network", "mm:network:read", "read", "servers", reportArgs, {
|
||||
target,
|
||||
read: async (input, context) => {
|
||||
const args = reportArgs.parse(input)
|
||||
return report(args, await resolve(args.target, context), context)
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { hasPermission } from "../../lib/permissions.js"
|
||||
import { executeTerminalDiagnostic, terminalDiagnosticSchema, type TerminalDiagnosticClient } from "../../services/terminal-diagnostics.js"
|
||||
import { executeTerminalDiagnostic, readTerminalInterfaceCounters, terminalDiagnosticNames, terminalDiagnosticSchema, terminalInterfaceCountersSchema, type TerminalDiagnosticClient } from "../../services/terminal-diagnostics.js"
|
||||
import { withTerminalDiagnosticClient } from "../../services/terminal-diagnostic-client.js"
|
||||
import { readRoutingEndpoints } from "./routing-observation-source.js"
|
||||
import { effectiveMcpConnection } from "./store.js"
|
||||
@@ -10,11 +10,20 @@ import type { add } from "./actions.js"
|
||||
|
||||
export const TERMINAL_DIAGNOSTIC_MAX_OUTPUT_BYTES = 12000
|
||||
export function registerTerminalDiagnosticActions(register: typeof add) {
|
||||
const schema = terminalDiagnosticSchema.safeExtend({ serverId: z.number().int().positive().safe() })
|
||||
const schema = z.object({
|
||||
...terminalDiagnosticSchema.shape,
|
||||
serverId: z.number().int().positive().safe(),
|
||||
diagnostic: z.enum([...terminalDiagnosticNames, "interface_counters"]),
|
||||
interface: terminalInterfaceCountersSchema.shape.interface,
|
||||
}).strict().superRefine(({ serverId: _id, ...args }, ctx) => {
|
||||
const parsed = args.diagnostic === "interface_counters" ? terminalInterfaceCountersSchema.safeParse(args) : terminalDiagnosticSchema.safeParse(args)
|
||||
if (!parsed.success) for (const issue of parsed.error.issues) ctx.addIssue({ code: "custom", message: issue.message, path: issue.path })
|
||||
})
|
||||
register("servers.terminal.read", "mm_server_terminal_diagnostic", "Разрешённая типизированная диагностика REST-терминала", "servers", "mm:servers:write", "read", "servers", schema, {
|
||||
read: async (input, context) => {
|
||||
const serverId = Number(input.serverId), { serverId: _id, ...args } = input
|
||||
const command = terminalDiagnosticSchema.parse(args), generation = await accessGeneration()
|
||||
const command = args.diagnostic === "interface_counters" ? terminalInterfaceCountersSchema.parse(args) : terminalDiagnosticSchema.parse(args)
|
||||
const generation = await accessGeneration()
|
||||
const initial = (await pool.query("SELECT id,enabled,routing_endpoint_epoch FROM servers WHERE id=$1", [serverId])).rows[0]
|
||||
const authorize = async () => {
|
||||
context.signal?.throwIfAborted()
|
||||
@@ -33,11 +42,20 @@ export function registerTerminalDiagnosticActions(register: typeof add) {
|
||||
await authorize()
|
||||
if (endpoints.length !== 1 || endpoints[0].routingEndpointEpoch !== initial.routing_endpoint_epoch || !endpoints[0].enabled) throw new McpError("STATE_CONFLICT", "Источник диагностики изменился", 409)
|
||||
const endpoint = endpoints[0]
|
||||
try { output = await withTerminalDiagnosticClient(endpoint, { signal: context.signal, authorize }, client => executeTerminalDiagnostic(client, command)) }
|
||||
const secrets = [endpoint.password, Buffer.from(`${endpoint.username}:${endpoint.password}`).toString("base64")].filter(Boolean)
|
||||
try {
|
||||
if (command.diagnostic === "interface_counters") {
|
||||
const protect = (value: string) => secrets.some(secret => value.includes(secret)) ? "[redacted]" : String(redact(value))
|
||||
const interfaceCounters = await withTerminalDiagnosticClient(endpoint, { signal: context.signal, authorize }, client => readTerminalInterfaceCounters(client, command, protect))
|
||||
await authorize()
|
||||
return { serverId, diagnostic: command.diagnostic, interfaceCounters, activity: { kind: "read", configurationApplied: false } }
|
||||
}
|
||||
output = await withTerminalDiagnosticClient(endpoint, { signal: context.signal, authorize }, client => executeTerminalDiagnostic(client, command))
|
||||
}
|
||||
catch (error) { if (error instanceof McpError) throw error; throw new McpError("STATE_UNAVAILABLE", "Терминальная диагностика не вернула подтверждённый результат", 409) }
|
||||
// Free-form comments and log text may echo stored credentials. Mask exact
|
||||
// credentials as well as labelled secrets before returning or auditing.
|
||||
for (const value of [endpoint.password, Buffer.from(`${endpoint.username}:${endpoint.password}`).toString("base64")].filter(Boolean)) output = output.split(value).join("[redacted]")
|
||||
for (const value of secrets) output = output.split(value).join("[redacted]")
|
||||
}
|
||||
await authorize()
|
||||
const redactionTruncated = output.length > MAX_MCP_PUBLIC_STRING_LENGTH
|
||||
|
||||
@@ -19,6 +19,7 @@ import { getEnabledServerById } from "../services/wireguard-live.js"
|
||||
import { readTrafficCollectionContext } from "../services/traffic-collection-state.js"
|
||||
import { readServerTrafficHistory, readServerTrafficHistoryWithSeries, readServerTrafficInterfaces } from "../services/traffic-history-read.js"
|
||||
import { mergeBuiltTraffic } from "../services/traffic-rate.js"
|
||||
import { getUserById } from "../modules/users/service/users-service.js"
|
||||
import {
|
||||
buildBoundInterfaceTraffic,
|
||||
buildUserTrafficList,
|
||||
@@ -236,9 +237,9 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
const minutes = rangeToMinutes(q.range)
|
||||
const rangeEndMs = Date.now()
|
||||
const rangeStartMs = rangeEndMs - minutes * 60_000
|
||||
const users = await buildUserTrafficList(rangeStartMs, rangeEndMs)
|
||||
const user = users.find((u) => u.id === id)
|
||||
if (!user) return reply.status(404).send({ error: "Пользователь не найден" })
|
||||
const source = await getUserById(id)
|
||||
if (!source) return reply.status(404).send({ error: "Пользователь не найден" })
|
||||
const [user] = await buildUserTrafficList(rangeStartMs, rangeEndMs, { users: [source] })
|
||||
return reply.send({ user })
|
||||
})
|
||||
|
||||
|
||||
@@ -12,11 +12,12 @@ import {
|
||||
uptimeSpeedProbes,
|
||||
} from "../db/schema.js"
|
||||
import { listServersRead } from "../modules/servers/service/servers-service.js"
|
||||
import { rosIdToIfIndex } from "./traffic-flow-ifindex.js"
|
||||
import { MikrotikClient } from "./mikrotik.js"
|
||||
import type { InternetPathRunSnapshot } from "../types/scheduler-run-snapshot.js"
|
||||
import { SCHEDULER_RUN_SNAPSHOT_VERSION } from "../types/scheduler-run-snapshot.js"
|
||||
|
||||
import { collectConfirmedInternetPath, readInternetPathRows } from "./internet-path-snapshot.js"
|
||||
import { collectConfirmedInternetPath, observedGrePeers, readGreEnrichment, readInternetPathRows } from "./internet-path-snapshot.js"
|
||||
|
||||
const INTERNET_TARGET = "1.1.1.1"
|
||||
let collecting = false
|
||||
@@ -177,12 +178,22 @@ function parseInnerIps(comment: string): { localInnerIp: string; remoteInnerIp:
|
||||
|
||||
async function collectGreTunnels() {
|
||||
const enabled = await db.select().from(servers).where(eq(servers.enabled, true))
|
||||
const assignedAddresses = new Map<string, Set<string>>()
|
||||
const all = await Promise.all(enabled.map(async (srv) => {
|
||||
try {
|
||||
const client = MikrotikClient.fromServer(srv)
|
||||
const rows = await client.get<unknown>("/interface/gre").then(raw => readInternetPathRows(raw, "GRE " + srv.id, [".id", "name", "local-address", "remote-address"]))
|
||||
if (!rows.length) return []
|
||||
const [addresses, interfaces] = await Promise.all([
|
||||
readGreEnrichment(() => client.get<unknown>("/ip/address"), "GRE addresses " + srv.id, ["interface", "address"]),
|
||||
readGreEnrichment(() => client.get<unknown>("/interface"), "interfaces " + srv.id, [".id", "name"]),
|
||||
])
|
||||
const activeAddresses = addresses.filter(a => !isTrue(a.disabled) && !isTrue(a.invalid))
|
||||
assignedAddresses.set(String(srv.id), new Set(activeAddresses.map(a => a.address!.split("/")[0]!)))
|
||||
return rows.map((g, idx) => {
|
||||
const keepalive = String(g.keepalive ?? "0,0").split(",")
|
||||
const identities = interfaces.filter(row => row.name === g.name)
|
||||
const identity = identities.length === 1 ? identities[0] : undefined
|
||||
const inner = parseInnerIps(String(g.comment ?? ""))
|
||||
return {
|
||||
id: String(g.name ?? g[".id"] ?? `gre-${srv.id}-${idx}`),
|
||||
@@ -190,6 +201,10 @@ async function collectGreTunnels() {
|
||||
serverId: String(srv.id),
|
||||
localAddress: String(g["local-address"] ?? ""),
|
||||
remoteAddress: String(g["remote-address"] ?? ""),
|
||||
currentRemoteAddress: String(g["current-remote-address"] ?? ""),
|
||||
nativeIndex: rosIdToIfIndex(identity?.[".id"]),
|
||||
ifIndex: /^[1-9][0-9]*$/.test(identity?.ifindex ?? "") ? Number(identity!.ifindex) : null,
|
||||
observedAddresses: activeAddresses.filter(a => a.interface === g.name).map(a => a.address!),
|
||||
localInnerIp: inner.localInnerIp,
|
||||
remoteInnerIp: inner.remoteInnerIp,
|
||||
poolId: "live",
|
||||
@@ -212,7 +227,7 @@ async function collectGreTunnels() {
|
||||
throw new Error(`Internet path: GRE устройства ${srv.id}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}))
|
||||
return all.flat()
|
||||
return observedGrePeers(all.flat(), new Map(enabled.map(server => [String(server.id), server.host])), assignedAddresses)
|
||||
}
|
||||
|
||||
export async function getInternetPathSettings() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import assert from "node:assert/strict"
|
||||
import {collectConfirmedInternetPath, readInternetPathRows, readStoredInternetPathPayload, mapStoredInternetPathResponse} from "./internet-path-snapshot.js"
|
||||
import {collectConfirmedInternetPath, observedGrePeers, readGreEnrichment, readInternetPathRows, readStoredInternetPathPayload, mapStoredInternetPathResponse} from "./internet-path-snapshot.js"
|
||||
const servers=[{id:1,type:"home-router",enabled:true},{id:2,type:"home-router",enabled:false},{id:3,type:"exit-node",enabled:true}]
|
||||
const sampledAt="2026-10-04T00:00:00Z"
|
||||
const defaults={servers:async()=>servers,gre:async()=>[],filters:async()=>[],speed:async()=>[],route:async(id:number)=>{assert.equal(id,1);return {gateway:null,routingMark:null}},wan:async(id:number)=>{assert.equal(id,1);return {defaultGateway:null,defaultInterface:null,uplinks:[]}}}
|
||||
@@ -35,3 +35,29 @@ for (const stored of ["2026-10-04 07:00:00+07", "2026-10-04T00:00:00Z"]) {
|
||||
for (const invalid of ["", "bad", null]) assert.throws(()=>mapStoredInternetPathResponse({payloadJson:good,sampledAt:invalid as string}))
|
||||
assert.throws(()=>mapStoredInternetPathResponse({payloadJson:"bad",sampledAt}))
|
||||
console.log("internet path HTTP timestamp: PostgreSQL/ISO instant preserved; invalid metadata rejected")
|
||||
|
||||
const jh = { serverId: "7", enabled: true, localAddress: "0.0.0.0", remoteAddress: "198.51.100.9", observedAddresses: ["10.200.100.53/30"] }
|
||||
const exit = { serverId: "9", enabled: true, localAddress: "198.51.100.9", remoteAddress: "198.51.100.7", observedAddresses: ["10.200.100.54/30"] }
|
||||
const hosts = new Map([["7", "198.51.100.7"], ["9", "198.51.100.9"]])
|
||||
assert.deepEqual(observedGrePeers([jh, exit], hosts, new Map()).map(t => t.observedNextHops), [[{ip:"10.200.100.54",serverId:"9"}],[{ip:"10.200.100.53",serverId:"7"}]])
|
||||
for (const incomplete of [[jh], [jh, exit, {...exit, serverId:"18"}], [jh, {...exit, enabled:false}], [jh, {...exit, remoteAddress:"198.51.100.8"}], [jh, {...exit, observedAddresses:["10.200.100.55/30"]}]]) {
|
||||
assert.ok(observedGrePeers(incomplete, hosts, new Map()).every(t => !t.observedNextHops.length))
|
||||
}
|
||||
|
||||
const wildcard = observedGrePeers([
|
||||
{...jh, localAddress:"0.0.0.0",remoteAddress:"exit.example",currentRemoteAddress:"198.51.100.2"},
|
||||
{...exit,localAddress:"0.0.0.0",remoteAddress:"198.51.100.1"},
|
||||
], new Map([["7","jump.example"],["9","exit.example"]]), new Map([["7",new Set(["198.51.100.1"])],["9",new Set(["198.51.100.2"])]]))
|
||||
assert.deepEqual(wildcard[0]?.observedNextHops, [{ip:"10.200.100.54",serverId:"9"}])
|
||||
|
||||
for (const read of [async () => { throw Error("forbidden") }, async () => ({ message:"invalid response" })]) {
|
||||
const observed = await readGreEnrichment(read, "GRE", ["address","interface"])
|
||||
const [base] = observedGrePeers([{...jh, observedAddresses:observed.map(a => a.address!),localInnerIp:"10.0.0.1/30"}],hosts,new Map())
|
||||
assert.equal(base?.localInnerIp,"10.0.0.1/30")
|
||||
assert.deepEqual(base?.observedNextHops,[])
|
||||
}
|
||||
|
||||
const staleDns = observedGrePeers([
|
||||
{...jh, remoteAddress:"exit.example",currentRemoteAddress:"192.0.2.11"}, exit,
|
||||
], new Map([["7","198.51.100.7"],["9","exit.example"]]), new Map())
|
||||
assert.ok(staleDns.every(t => !t.observedNextHops.length))
|
||||
@@ -1,3 +1,5 @@
|
||||
import { ipv4ToInt, parseCidrV4 } from "./traffic-flow-ip.js"
|
||||
|
||||
// No database or RouterOS imports: this boundary can be checked with injected readers.
|
||||
type PathServer = {id: number | string; type: string; enabled: boolean}
|
||||
export async function collectConfirmedInternetPath<S extends PathServer, G, F, P, R extends object, W extends object>(sampledAt: string, readers: {
|
||||
@@ -36,3 +38,50 @@ export function mapStoredInternetPathResponse(row: { payloadJson: unknown; sampl
|
||||
if (typeof row.sampledAt !== "string" || !row.sampledAt.trim()) throw new Error("Сохранённая дата Internet path повреждена")
|
||||
return { snapshot: readStoredInternetPathPayload(row.payloadJson), sampledAt: new Date(row.sampledAt).toISOString() }
|
||||
}
|
||||
|
||||
|
||||
// Enrichment may be unauthorized on otherwise observable GRE routers.
|
||||
export async function readGreEnrichment(read: () => Promise<unknown>, source: string, fields: string[]) {
|
||||
try { return readInternetPathRows(await read(), source, fields) } catch { return [] }
|
||||
}
|
||||
|
||||
// A shared point-to-point subnet and matching outer peers identify the exact next hop on this exporter.
|
||||
export function observedGrePeers<T extends {serverId: string; enabled: boolean; localAddress: string; remoteAddress: string; currentRemoteAddress?: string; localInnerIp?: string; observedAddresses: string[]}>(
|
||||
tunnels: T[], hosts: Map<string, string>, assignedAddresses: Map<string, Set<string>>,
|
||||
) {
|
||||
const subnets = new Map<string, Array<{ tunnel: T; ip: string }>>()
|
||||
const peers = new Map<T, Array<{ ip: string; serverId: string }>>()
|
||||
for (const tunnel of tunnels) {
|
||||
if (!tunnel.enabled) continue
|
||||
for (const cidr of tunnel.observedAddresses) {
|
||||
if (!/^[0-9.]+\/(30|31)$/.test(cidr)) continue
|
||||
const parsed = parseCidrV4(cidr)
|
||||
const ip = cidr.split("/")[0]!
|
||||
if (!parsed || (parsed.prefixLen === 30 && (ipv4ToInt(ip) === parsed.net || ipv4ToInt(ip) === parsed.net + 3))) continue
|
||||
const key = parsed.net + "/" + parsed.prefixLen
|
||||
const entries = subnets.get(key) ?? []
|
||||
entries.push({ tunnel, ip })
|
||||
subnets.set(key, entries)
|
||||
}
|
||||
}
|
||||
function pointsTo(local: T, peer: T) {
|
||||
const current = local.currentRemoteAddress?.trim().toLowerCase()
|
||||
const remote = current && current !== "0.0.0.0" ? current : local.remoteAddress.trim().toLowerCase()
|
||||
return remote && remote !== "0.0.0.0" && (remote === peer.localAddress.toLowerCase() ||
|
||||
remote === hosts.get(peer.serverId)?.toLowerCase() || assignedAddresses.get(peer.serverId)?.has(remote))
|
||||
}
|
||||
for (const endpoints of subnets.values()) {
|
||||
if (endpoints.length !== 2) continue
|
||||
const [a, b] = endpoints as [typeof endpoints[number], typeof endpoints[number]]
|
||||
if (a.ip === b.ip || a.tunnel.serverId === b.tunnel.serverId || !pointsTo(a.tunnel, b.tunnel) || !pointsTo(b.tunnel, a.tunnel)) continue
|
||||
for (const [local, peer] of [[a, b], [b, a]] as const) {
|
||||
const matches = peers.get(local.tunnel) ?? []
|
||||
matches.push({ ip: peer.ip, serverId: peer.tunnel.serverId })
|
||||
peers.set(local.tunnel, matches)
|
||||
}
|
||||
}
|
||||
return tunnels.map(tunnel => {
|
||||
const { observedAddresses, ...rest } = tunnel
|
||||
return { ...rest, localInnerIp: observedAddresses[0] ?? tunnel.localInnerIp ?? "", observedNextHops: peers.get(tunnel) ?? [] }
|
||||
})
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { setTimeout as delay } from "node:timers/promises"
|
||||
import { MikrotikClient } from "./mikrotik.js"
|
||||
import { dispatchTerminalCommand, executeTerminalDiagnostic, parseTerminalCommand, terminalDiagnosticSchema } from "./terminal-diagnostics.js"
|
||||
import { dispatchTerminalCommand, executeTerminalDiagnostic, parseTerminalCommand, readTerminalInterfaceCounters, terminalDiagnosticSchema, terminalInterfaceCountersSchema } from "./terminal-diagnostics.js"
|
||||
import { withTerminalDiagnosticClient } from "./terminal-diagnostic-client.js"
|
||||
import { createTerminalDiagnosticFixture, terminalDiagnosticCases } from "../test/terminal-diagnostic-fixture.js"
|
||||
|
||||
@@ -22,6 +22,24 @@ try {
|
||||
for (const bad of [{ diagnostic: "execute", command: "/system reboot" }, { diagnostic: "interfaces", target: "host" }, { diagnostic: "logs", count: 2 }, { diagnostic: "ping" }, { diagnostic: "ping", target: "192.0.2.1", count: 21 }, { diagnostic: "logs", limit: 201 }]) assert.equal(terminalDiagnosticSchema.safeParse(bad).success, false)
|
||||
for (const bad of ["/system reboot", ":execute /system resource print", "ip address print;system reboot", "log print limit=0", "ping host count=1junk"]) assert.throws(() => parseTerminalCommand(bad))
|
||||
const oldInterfaces = fixture.payloads["/interface"]
|
||||
fixture.payloads["/interface"] = [
|
||||
{ name: "ether-a", running: "true", "rx-byte": "18446744073709551615", "rx-error": "0", "tx-error": "-1", "rx-drop": "2", "link-downs": "3", "last-link-down-time": "2026-01-01 00:00:00", comment: endpoint.password },
|
||||
{ name: "ether-b", "tx-queue-drop": "4" },
|
||||
]
|
||||
const counters = (args: object) => withTerminalDiagnosticClient(endpoint, { authorize }, native => readTerminalInterfaceCounters(native,
|
||||
terminalInterfaceCountersSchema.parse({ diagnostic: "interface_counters", ...args }), value => value))
|
||||
const first = await counters({ limit: 1 })
|
||||
assert.equal(first.total, 2)
|
||||
assert.equal(first.truncated, true)
|
||||
assert.equal(first.rows.length, 1)
|
||||
assert.equal(first.rows[0].lastLinkDownAt, "2026-01-01 00:00:00")
|
||||
assert.equal(first.rows[0].running, true)
|
||||
assert.deepEqual(first.rows[0].counters, { rxBytes: "18446744073709551615", txBytes: null, rxPackets: null, txPackets: null, rxDrops: "2", txDrops: null, txQueueDrops: null, rxErrors: "0", txErrors: null, linkDowns: "3" })
|
||||
assert.equal(first.resetHistoryAvailable, false)
|
||||
assert.ok(first.routerUptime)
|
||||
assert.ok(!JSON.stringify(first).includes(endpoint.password))
|
||||
assert.equal((await counters({ interface: "ether-b" })).rows[0].counters.txQueueDrops, "4")
|
||||
assert.equal(terminalInterfaceCountersSchema.safeParse({ diagnostic: "interface_counters", limit: 51 }).success, false)
|
||||
fixture.payloads["/interface"] = Array.from({ length: 1001 }, () => ({ name: "x" }))
|
||||
await assert.rejects(withTerminalDiagnosticClient(endpoint, { authorize }, native => native.getInterfaces()))
|
||||
fixture.payloads["/interface"] = [{ name: "x".repeat(1048577) }]
|
||||
|
||||
@@ -236,6 +236,46 @@ export const terminalDiagnosticSchema = z.object({
|
||||
})
|
||||
export type TerminalDiagnostic = z.infer<typeof terminalDiagnosticSchema>
|
||||
export type TerminalDiagnosticClient = Pick<MikrotikClient, "getIpAddresses" | "getInterfaces" | "getResource" | "getIdentity" | "getIpRoutes" | "getFirewallFilters" | "getBgpSessions" | "getOspfNeighbors" | "getOspfAreas" | "getOspfInstances" | "getOspfInterfaceTemplates" | "getBfdSessions" | "getLogs" | "ping">
|
||||
export const terminalInterfaceCountersSchema = z.object({
|
||||
diagnostic: z.literal("interface_counters"),
|
||||
interface: z.string().min(1).max(128).regex(/^[^\p{Cc}]+$/u).optional(),
|
||||
limit: z.number().int().min(1).max(50).default(20),
|
||||
}).strict()
|
||||
|
||||
export async function readTerminalInterfaceCounters(
|
||||
client: Pick<TerminalDiagnosticClient, "getInterfaces" | "getResource">,
|
||||
input: z.infer<typeof terminalInterfaceCountersSchema>,
|
||||
protect: (value: string) => string,
|
||||
) {
|
||||
const [interfaces, resource] = await Promise.all([client.getInterfaces(), client.getResource()])
|
||||
const properties = {
|
||||
rxBytes: "rx-byte", txBytes: "tx-byte", rxPackets: "rx-packet", txPackets: "tx-packet",
|
||||
rxDrops: "rx-drop", txDrops: "tx-drop", txQueueDrops: "tx-queue-drop",
|
||||
rxErrors: "rx-error", txErrors: "tx-error", linkDowns: "link-downs",
|
||||
} as const
|
||||
const text = (value: unknown, max: number) =>
|
||||
typeof value === "string" && value.length <= max && /^[^\p{Cc}]+$/u.test(value) ? protect(value) : null
|
||||
const counter = (value: unknown) => {
|
||||
if (typeof value !== "string" || !/^\d{1,20}$/.test(value) || BigInt(value) > 18446744073709551615n) return null
|
||||
return protect(value) === value ? value : null
|
||||
}
|
||||
const flag = (value: unknown) => value === "true" ? true : value === "false" ? false : null
|
||||
const selected = interfaces.filter(row => input.interface === undefined || row.name === input.interface)
|
||||
const rows = selected.slice(0, input.limit).map(row => {
|
||||
const native = row as typeof row & Partial<Record<(typeof properties)[keyof typeof properties] | "last-link-down-time" | "last-link-up-time", unknown>>
|
||||
const counters = Object.fromEntries(Object.entries(properties).map(([key, property]) => [key, counter(native[property])])) as Record<keyof typeof properties, string | null>
|
||||
return {
|
||||
name: text(row.name, 128), type: text(row.type, 64), running: flag(row.running), disabled: flag(row.disabled),
|
||||
counters,
|
||||
lastLinkDownAt: text(native["last-link-down-time"], 40), lastLinkUpAt: text(native["last-link-up-time"], 40),
|
||||
}
|
||||
})
|
||||
return {
|
||||
rows, total: selected.length, limit: input.limit, truncated: rows.length < selected.length,
|
||||
observedAt: new Date().toISOString(), routerUptime: text(resource.uptime, 64),
|
||||
countersAreCumulative: true, lastCounterResetAt: null, resetHistoryAvailable: false,
|
||||
}
|
||||
}
|
||||
export class ExecValidationError extends Error { readonly statusCode = 400 }
|
||||
|
||||
/** REST grammar is intentionally an allowlist, never a RouterOS script. */
|
||||
|
||||
@@ -27,6 +27,7 @@ import { resolveIfaceName } from "./traffic-flow-ifaces.js"
|
||||
import { factIfaceAliases } from "./traffic-flow-ifindex.js"
|
||||
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
|
||||
import { applicationName, flowRowMatchesFilter } from "./traffic-flow-apps.js"
|
||||
import { canonicalIp, ipv6ToInt } from "./traffic-flow-ip.js"
|
||||
import { collapseGreEspRows, dedupFlowRowsMaxBytes, flowTupleKey } from "./traffic-flow-dedup.js"
|
||||
import { enqueueRipeMisses } from "./traffic-flow-ripe.js"
|
||||
import { classifyFlowPlane, flowBps, shouldKeepPlane } from "./traffic-flow-planes.js"
|
||||
@@ -37,7 +38,8 @@ import {
|
||||
getServerCatalog,
|
||||
latestWireBps,
|
||||
loadFlowTopology,
|
||||
resolveClient,
|
||||
flowClientInterfaces,
|
||||
resolveFlowClient,
|
||||
resolveEn,
|
||||
} from "./traffic-flow-topology.js"
|
||||
|
||||
@@ -49,6 +51,7 @@ export interface FlowAnalyticsQuery {
|
||||
serverId?: number
|
||||
userId?: string
|
||||
iface?: string
|
||||
tuple?: { srcIp?: string; dstIp?: string; srcPort?: number; dstPort?: number; protocol?: number }
|
||||
/** Default true: один 5-tuple за минуту = max байт по ifaces. */
|
||||
dedup?: boolean
|
||||
/** Default true: скрыть GRE/WG между клиентами JH. */
|
||||
@@ -95,18 +98,6 @@ function bump(
|
||||
map.set(id, prev)
|
||||
}
|
||||
|
||||
async function userIfaceAllow(userId: string): Promise<Map<number, Set<string>> | null> {
|
||||
if (!userId) return null
|
||||
const binds = await flowReadDbAll<{serverId:number;interfaceName:string}>('SELECT server_id AS "serverId",interface_name AS "interfaceName" FROM user_interface_bindings WHERE user_id=?',[userId])
|
||||
const allow = new Map<number, Set<string>>()
|
||||
for (const b of binds) {
|
||||
const set = allow.get(b.serverId) ?? new Set<string>()
|
||||
set.add(b.interfaceName)
|
||||
allow.set(b.serverId, set)
|
||||
}
|
||||
return allow
|
||||
}
|
||||
|
||||
function seriesFromRows(rows: PendingFlowRow[], minutes: number, direction: (row: PendingFlowRow) => "rx" | "tx" | "both" | null, now = Date.now()) {
|
||||
const slots = Math.min(60, Math.max(5, minutes))
|
||||
const slotMs = (minutes * 60_000) / slots
|
||||
@@ -182,6 +173,7 @@ function analyticsQueryKey(q: FlowAnalyticsQuery): string {
|
||||
serverId: q.serverId ?? null,
|
||||
userId: q.userId ?? null,
|
||||
iface: q.iface ?? null,
|
||||
tuple: q.tuple ?? null,
|
||||
dedup: q.dedup !== false,
|
||||
excludeMesh: q.excludeMesh !== false,
|
||||
excludeOverlay: q.excludeOverlay !== false,
|
||||
@@ -241,7 +233,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
const excludeOverlay = q.excludeOverlay !== false
|
||||
await authorize()
|
||||
const topo = await loadFlowTopology(scope?.serverIds, authorize)
|
||||
const allow = q.userId ? scope ? new Map([...topo.clientByIface.values()].filter(b => b.userId === q.userId).map(b => [b.serverId, new Set([...topo.clientByIface.values()].filter(other => other.userId === q.userId && other.serverId === b.serverId).map(other => other.interfaceName))])) : await userIfaceAllow(q.userId) : null
|
||||
const allow = q.userId ? flowClientInterfaces(topo, q.userId) : null
|
||||
if (scope && q.userId && !allow?.size) throw new Error("Пользователь не найден в разрешённой топологии")
|
||||
|
||||
if (!scope) refreshFlowCatalogInBackground()
|
||||
@@ -253,7 +245,21 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
const ingress = matchesIngress(row), egress = matchesEgress(row)
|
||||
return ingress === egress ? null : ingress ? "rx" : "tx"
|
||||
}
|
||||
const selected = ifaceFilter || allow ? raw.filter(row => matchesIngress(row) || matchesEgress(row)) : raw
|
||||
const visible = ifaceFilter || allow ? raw.filter(row => (matchesIngress(row) || matchesEgress(row)) &&
|
||||
(!q.userId || resolveFlowClient(topo, row.serverId, resolveIfaceName(row.serverId, row.inIface).name, resolveIfaceName(row.serverId, row.outIface).name)?.userId === q.userId)) : raw
|
||||
const tuple = q.tuple
|
||||
const ipKey = (value: string) => {
|
||||
const ip = canonicalIp(value)
|
||||
return ip.includes(":") ? ipv6ToInt(ip) ?? ip : ip
|
||||
}
|
||||
const src = tuple?.srcIp === undefined ? undefined : ipKey(tuple.srcIp)
|
||||
const dst = tuple?.dstIp === undefined ? undefined : ipKey(tuple.dstIp)
|
||||
const selected = tuple ? visible.filter(row =>
|
||||
(src === undefined || src === ipKey(row.src)) &&
|
||||
(dst === undefined || dst === ipKey(row.dst)) &&
|
||||
(tuple.srcPort === undefined || tuple.srcPort === row.srcPort) &&
|
||||
(tuple.dstPort === undefined || tuple.dstPort === row.dstPort) &&
|
||||
(tuple.protocol === undefined || tuple.protocol === row.proto)) : visible
|
||||
const { rows, espDirections } = collapseGreEspRows(selected, ifaceFilter ? interfaceDirection : serverDirection)
|
||||
const previousMinute = new Date(Math.floor(now / 60_000) * 60_000 - 60_000).toISOString()
|
||||
const ifacesForWire = new Set<string>()
|
||||
@@ -370,7 +376,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
inIface: resolved.name,
|
||||
outIface: outResolved.name,
|
||||
}, topo.plane)
|
||||
const client = resolveClient(topo, r.serverId, resolved.name) ?? resolveClient(topo, r.serverId, outResolved.name)
|
||||
const client = resolveFlowClient(topo, r.serverId, resolved.name, outResolved.name)
|
||||
const en = resolveEn(topo, r.nextHop, outResolved.name)
|
||||
const outIface = outResolved.name === "—" ? "" : outResolved.name
|
||||
const pathKey = JSON.stringify([client?.userId ?? "unknown", r.serverId, en?.id ?? "", dst, resolved.name, outIface,
|
||||
@@ -489,7 +495,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
const topCategory = topLabel(categories)
|
||||
|
||||
const ringServer = q.serverId ?? (matched[0]?.serverId ?? 0)
|
||||
const ring = ringServer && !ifaceFilter && !allow && excludeOverlay ? getRingMbps(ringServer) : null
|
||||
const ring = ringServer && !ifaceFilter && !allow && !tuple && excludeOverlay ? getRingMbps(ringServer) : null
|
||||
|
||||
// The live ring covers about one minute; historical charts must use the requested window.
|
||||
const fromBuckets = seriesFromRows(working, q.minutes, row => {
|
||||
@@ -546,11 +552,11 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
const bpsNow = ring
|
||||
? (!fromBuckets.undirectedBytes && (ring.rxNow + ring.txNow) * 1_000_000) || (totalBytes * 8) / windowSec
|
||||
: (recentBytes * 8) / 60 || (totalBytes * 8) / windowSec
|
||||
const greNames = ringServer ? enGreIfaceNames(topo, ringServer, [...ifacesForWire]) : []
|
||||
const greNames = ringServer && !q.userId ? enGreIfaceNames(topo, ringServer, [...ifacesForWire]) : []
|
||||
await authorize()
|
||||
const wire = ringServer ? await latestWireBps(ringServer, greNames, Boolean(scope)) : { bps: 0, bytes: 0 }
|
||||
await authorize()
|
||||
const admittedTotals = q.serverId !== undefined && !q.userId
|
||||
const admittedTotals = q.serverId !== undefined && !q.userId && !tuple
|
||||
? await readAdmittedFlowTotals(q.serverId, ifaceFilter, q.minutes, now)
|
||||
: undefined
|
||||
|
||||
@@ -660,32 +666,26 @@ export async function listFlowExporters(minutes: number): Promise<FlowExportersD
|
||||
}
|
||||
}
|
||||
|
||||
export async function listFlowClients(minutes: number): Promise<{ clients: { id: string; name: string; subtitle: string; site: string; country: string; status: "online" | "offline" | "degraded"; rxNow: number; txNow: number; sessions: number; rxSeries: number[]; txSeries: number[]; bytes: number; }[]; }> {
|
||||
const inputs = await readFlowClientInputs(minutes)
|
||||
const users = inputs.users
|
||||
const binds = users.flatMap(user => user.bindings.map(binding => ({ ...binding, userId: user.id })))
|
||||
const byUser = new Map<string, typeof binds>()
|
||||
for (const b of binds) {
|
||||
const list = byUser.get(b.userId) ?? []
|
||||
list.push(b)
|
||||
byUser.set(b.userId, list)
|
||||
export async function listFlowClients(minutes: number): Promise<{ clients: FlowEntityCard[] }> {
|
||||
const [inputs, topo] = await Promise.all([readFlowClientInputs(minutes), loadFlowTopology()])
|
||||
const byUser = new Map<string, PendingFlowRow[]>()
|
||||
for (const row of inputs.window.rows) {
|
||||
const inIface = resolveIfaceName(row.serverId, row.inIface).name
|
||||
const outIface = resolveIfaceName(row.serverId, row.outIface).name
|
||||
const client = resolveFlowClient(topo, row.serverId, inIface, outIface)
|
||||
if (!client || classifyFlowPlane({ ...row, inIface, outIface }, topo.plane) !== "payload") continue
|
||||
const rows = byUser.get(client.userId) ?? []
|
||||
rows.push(row)
|
||||
byUser.set(client.userId, rows)
|
||||
}
|
||||
const rows = inputs.window.rows
|
||||
const clients: FlowEntityCard[] = []
|
||||
for (const u of users) {
|
||||
const userBinds = byUser.get(u.id) ?? []
|
||||
if (userBinds.length === 0) continue
|
||||
const allow = new Map<number, Set<string>>()
|
||||
for (const b of userBinds) {
|
||||
const set = allow.get(b.serverId) ?? new Set<string>()
|
||||
set.add(b.interfaceName)
|
||||
allow.set(b.serverId, set)
|
||||
}
|
||||
for (const u of inputs.users) {
|
||||
const allow = flowClientInterfaces(topo, u.id)
|
||||
const namedBindings = u.bindings.filter(binding => allow.get(binding.serverId)?.has(binding.interfaceName)).length
|
||||
const bound = (id: number, iface: string) => {
|
||||
const names = allow.get(id)
|
||||
return names?.has(iface) || names?.has(resolveIfaceName(id, iface).name)
|
||||
return allow.get(id)?.has(resolveIfaceName(id, iface).name)
|
||||
}
|
||||
const matched = rows.filter(r => bound(r.serverId, r.inIface) || bound(r.serverId, r.outIface))
|
||||
const matched = dedupFlowRowsMaxBytes(byUser.get(u.id) ?? [])
|
||||
const rates = seriesFromRows(matched, minutes, r => {
|
||||
if (!bound(r.serverId, r.inIface)) return "rx"
|
||||
return bound(r.serverId, r.outIface) ? "both" : "tx"
|
||||
@@ -694,18 +694,18 @@ export async function listFlowClients(minutes: number): Promise<{ clients: { id:
|
||||
id: u.id,
|
||||
name: u.login,
|
||||
subtitle: u.name || u.login,
|
||||
site: `${userBinds.length} ifaces`,
|
||||
site: namedBindings < u.bindings.length ? `IPFIX: ${namedBindings}/${u.bindings.length} привязок` : `${namedBindings} инт.`,
|
||||
country: "UN",
|
||||
status: u.active ? "online" : "offline",
|
||||
rxNow: rates.rxNow,
|
||||
txNow: rates.txNow,
|
||||
rxNow: matched.length ? rates.rxNow : null,
|
||||
txNow: matched.length ? rates.txNow : null,
|
||||
sessions: matched.length,
|
||||
rxSeries: rates.rx,
|
||||
txSeries: rates.tx,
|
||||
rxSeries: matched.length ? rates.rx : [],
|
||||
txSeries: matched.length ? rates.tx : [],
|
||||
bytes: matched.reduce((sum, row) => sum + row.bytes, 0),
|
||||
})
|
||||
}
|
||||
clients.sort((a, b) => b.rxNow - a.rxNow)
|
||||
clients.sort((a, b) => (b.rxNow ?? -1) - (a.rxNow ?? -1))
|
||||
return { clients }
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ const WELL_KNOWN: Record<string, string> = {
|
||||
"17:853": "DNS",
|
||||
"6:853": "DNS",
|
||||
"17:51820": "WireGuard",
|
||||
"17:13231": "WireGuard",
|
||||
"17:13232": "WireGuard",
|
||||
"17:51821": "WireGuard",
|
||||
"17:4789": "VXLAN",
|
||||
@@ -63,6 +64,13 @@ export function applicationName(proto: number, dstPort: number, srcPort = 0): st
|
||||
return WELL_KNOWN[dstKey] ?? WELL_KNOWN[srcKey] ?? `${protoName(proto)}/${dstPort || srcPort || "—"}`
|
||||
}
|
||||
|
||||
/** Port hints keep a conventional service port separate from the observed transport. */
|
||||
export function flowPortApplication(proto: number, port: number): string | null {
|
||||
if (proto === 6 && port === 853) return "DNS over TLS"
|
||||
if (proto === 17 && port === 853) return "Защищённый DNS"
|
||||
return port > 0 ? WELL_KNOWN[`${proto}:${port}`] ?? null : null
|
||||
}
|
||||
|
||||
export interface FlowMatchQuery {
|
||||
serverId?: number
|
||||
userId?: string
|
||||
|
||||
@@ -89,7 +89,12 @@ assert.equal(resolveFlowBrand("173.194.160.163", 15169, "GOOGLE", 6, 443, 51234)
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 17, 443, 50000)?.service, "YouTube")
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 6, 80, 50000)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("2001:4860:4860::8888", 15169, "GOOGLE", 17, 53, 53000)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("2001:4860:4860::8888", 15169, "GOOGLE", 17, 443, 50000)?.service, "YouTube")
|
||||
assert.equal(resolveFlowBrand("2001:4860:4860::8888", 15169, "GOOGLE", 17, 443, 50000)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("2001:4860:4860:0:0:0:0:8844/128", 15169, "GOOGLE", 6, 443)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("::ffff:8.8.4.4", 15169, "", 17, 443)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("2607:f8b0::123", 15169, "", 17, 443)?.service, "YouTube")
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 396982, "", 6, 443)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 6, 50000, 443)?.service, "Google", "443 на стороне клиента")
|
||||
|
||||
assert.equal(brandByAsn(32934)?.service, "Meta")
|
||||
assert.equal(lookupBrand("157.240.12.52", 0)?.service, "Meta")
|
||||
@@ -100,12 +105,12 @@ assert.equal(isNamedInternetService("Instagram", "Видео / стриминг"
|
||||
assert.equal(
|
||||
resolveFlowBrand("157.240.12.52", 32934, "FACEBOOK", 6, 443, 51234)?.service,
|
||||
"Instagram",
|
||||
"HTTPS на Meta front → Instagram, как YouTube на Google",
|
||||
"HTTPS в сети Meta",
|
||||
)
|
||||
assert.equal(
|
||||
resolveFlowBrand("57.144.22.192", 0, "", 17, 443, 50000)?.service,
|
||||
"Instagram",
|
||||
"cdninstagram CIDR :443 без ASN → Instagram",
|
||||
"QUIC в префиксе Meta без ASN",
|
||||
)
|
||||
assert.equal(
|
||||
resolveFlowBrand("157.240.12.52", 32934, "FACEBOOK", 6, 80, 50000)?.service,
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { ipInCidrV4, parseCidrV4 } from "./traffic-flow-ip.js"
|
||||
import { canonicalIp, ipInCidrV4, ipv6ToInt, parseCidrV4 } from "./traffic-flow-ip.js"
|
||||
|
||||
export const OTHER_SERVICE = "Прочее"
|
||||
|
||||
export interface BrandHit {
|
||||
service: string
|
||||
category: string
|
||||
operator?: string
|
||||
heuristic?: true
|
||||
}
|
||||
|
||||
const CDN = { category: "CDN" } as const
|
||||
@@ -12,6 +14,7 @@ const WEB = { category: "Веб" } as const
|
||||
const VIDEO = { category: "Видео / стриминг" } as const
|
||||
const GAMES = { category: "Игры" } as const
|
||||
const VOICE = { category: "Голос" } as const
|
||||
const MESSAGING = { category: "Мессенджеры" } as const
|
||||
const AI = { category: "ИИ" } as const
|
||||
const DNS = { category: "DNS" } as const
|
||||
|
||||
@@ -39,7 +42,7 @@ const TIMEWEB: BrandHit = { service: "Timeweb", ...CDN }
|
||||
const BEGET: BrandHit = { service: "Beget", ...CDN }
|
||||
const DDOS_GUARD: BrandHit = { service: "DDoS-Guard", ...CDN }
|
||||
const META: BrandHit = { service: "Meta", ...CDN }
|
||||
const INSTAGRAM: BrandHit = { service: "Instagram", ...VIDEO }
|
||||
const INSTAGRAM: BrandHit = { service: "Instagram", operator: META.service, ...VIDEO }
|
||||
|
||||
const GOOGLE: BrandHit = { service: "Google", ...WEB }
|
||||
const GITHUB: BrandHit = { service: "GitHub", ...WEB }
|
||||
@@ -54,7 +57,9 @@ const WIKIPEDIA: BrandHit = { service: "Wikipedia", ...WEB }
|
||||
const PAYPAL: BrandHit = { service: "PayPal", ...WEB }
|
||||
const SALESFORCE: BrandHit = { service: "Salesforce", ...WEB }
|
||||
|
||||
const YOUTUBE: BrandHit = { service: "YouTube", ...VIDEO }
|
||||
const YOUTUBE: BrandHit = { service: "YouTube", operator: GOOGLE.service, ...VIDEO }
|
||||
const LIKELY_YOUTUBE: BrandHit = { ...YOUTUBE, heuristic: true }
|
||||
const LIKELY_INSTAGRAM: BrandHit = { ...INSTAGRAM, heuristic: true }
|
||||
const NETFLIX: BrandHit = { service: "Netflix", ...VIDEO }
|
||||
const TWITCH: BrandHit = { service: "Twitch", ...VIDEO }
|
||||
const TIKTOK: BrandHit = { service: "TikTok", ...VIDEO }
|
||||
@@ -69,7 +74,7 @@ const ROBLOX: BrandHit = { service: "Roblox", ...GAMES }
|
||||
const UBISOFT: BrandHit = { service: "Ubisoft", ...GAMES }
|
||||
|
||||
const DISCORD: BrandHit = { service: "Discord", ...VOICE }
|
||||
const TELEGRAM: BrandHit = { service: "Telegram", ...VOICE }
|
||||
const TELEGRAM: BrandHit = { service: "Telegram", ...MESSAGING }
|
||||
const ZOOM: BrandHit = { service: "Zoom", ...VOICE }
|
||||
|
||||
const CHATGPT: BrandHit = { service: "ChatGPT", ...AI }
|
||||
@@ -222,18 +227,13 @@ const HOLDER_BRANDS: Array<{ re: RegExp; hit: BrandHit }> = [
|
||||
const NON_ISO = new Set(["EU", "AP", "ZZ", "XX", "A1", "A2", "O1"])
|
||||
|
||||
const STEAM_ASN = 32590
|
||||
const GOOGLE_FRONT_ASN = new Set([15169, 396982])
|
||||
/** AS32934 / AS63293 — Meta front (Facebook + Instagram CDN). AS54115 — WhatsApp, не Instagram. */
|
||||
const META_FRONT_ASN = new Set([32934, 63293])
|
||||
const WHATSAPP_ASN = 54115
|
||||
const GOOGLE_DNS_V6 = new Set([ipv6ToInt("2001:4860:4860::8888")!, ipv6ToInt("2001:4860:4860::8844")!])
|
||||
|
||||
function isGooglePublicDns(ip: string): boolean {
|
||||
return ipInCidrV4(ip, "8.8.8.0/24") || ipInCidrV4(ip, "8.8.4.0/24")
|
||||
}
|
||||
|
||||
function isHttpsOrQuic(proto: number, dstPort: number, srcPort: number): boolean {
|
||||
if (proto !== 6 && proto !== 17) return false
|
||||
return dstPort === 443 || srcPort === 443
|
||||
const host = canonicalIp(ip)
|
||||
if (host === "8.8.8.8" || host === "8.8.4.4") return true
|
||||
const ipv6 = host.includes(":") ? ipv6ToInt(host) : null
|
||||
return ipv6 !== null && GOOGLE_DNS_V6.has(ipv6)
|
||||
}
|
||||
|
||||
export function isIsoCountry(code: string): boolean {
|
||||
@@ -295,19 +295,10 @@ export function lookupBrand(ip: string, asn: number): BrandHit | null {
|
||||
return brandByCidr(ip) || brandByAsn(asn)
|
||||
}
|
||||
|
||||
function isGoogleFront(asn: number, cidrBrand: BrandHit | null, asnBrand: BrandHit | null): boolean {
|
||||
return GOOGLE_FRONT_ASN.has(asn) || cidrBrand?.service === "Google" || asnBrand?.service === "Google"
|
||||
}
|
||||
|
||||
function isInstagramFront(asn: number, cidrBrand: BrandHit | null, asnBrand: BrandHit | null): boolean {
|
||||
if (asn === WHATSAPP_ASN) return false
|
||||
return META_FRONT_ASN.has(asn) || cidrBrand?.service === "Meta" || asnBrand?.service === "Meta"
|
||||
}
|
||||
|
||||
/**
|
||||
* Cloudflare CIDR бьёт holder (витрина на CF не становится Steam).
|
||||
* Holder (YouTube / Instagram и др.) бьёт остальные CIDR/ASN.
|
||||
* HTTPS/QUIC на Google front → YouTube (кроме 8.8.8.8); на Meta front → Instagram (кроме WhatsApp ASN).
|
||||
* На порту 443 интернет-узла общие сети Google и Meta дают вероятную атрибуцию.
|
||||
* Порты Steam — только AS32590 и не выше Cloudflare CIDR.
|
||||
*/
|
||||
export function resolveFlowBrand(
|
||||
@@ -323,13 +314,12 @@ export function resolveFlowBrand(
|
||||
const holderBrand = brandByHolder(holder)
|
||||
if (holderBrand) return holderBrand
|
||||
const asnBrand = brandByAsn(asn)
|
||||
if (!isGooglePublicDns(ip) && isHttpsOrQuic(proto, dstPort, srcPort) && isGoogleFront(asn, cidrBrand, asnBrand)) {
|
||||
return YOUTUBE
|
||||
}
|
||||
if (isHttpsOrQuic(proto, dstPort, srcPort) && isInstagramFront(asn, cidrBrand, asnBrand)) {
|
||||
return INSTAGRAM
|
||||
}
|
||||
const fromLookup = cidrBrand || asnBrand
|
||||
if (asnBrand === YOUTUBE && cidrBrand === GOOGLE) return YOUTUBE
|
||||
if ((proto === 6 || proto === 17) && dstPort === 443) {
|
||||
if (fromLookup === GOOGLE && (!asn || asn === 15169) && !isGooglePublicDns(ip)) return LIKELY_YOUTUBE
|
||||
if (fromLookup === META && (!asn || asn === 32934 || asn === 63293)) return LIKELY_INSTAGRAM
|
||||
}
|
||||
if (fromLookup) return fromLookup
|
||||
if (asn === STEAM_ASN && isSteamGamePort(proto, dstPort, srcPort)) return STEAM
|
||||
return null
|
||||
|
||||
@@ -8,14 +8,18 @@ for (const value of [-1, NaN, Infinity, "bad", "1.5", "9007199254740992", null,
|
||||
assert.equal(flowCounter("0"), 0); assert.equal(flowCounterSum([0, 5, 10]), 15)
|
||||
assert.throws(() => flowCounterSum([Number.MAX_SAFE_INTEGER, 1]))
|
||||
const row = { serverId: 1, bytes: 1000, packets: 10, inIface: "client-vlan", bucketAt: "2026-10-19T00:00:00Z" } as PendingFlowRow
|
||||
const user: FlowClientInput = { id: "u", login: "user", name: "Name", active: true, bindingCount: 2, selectedBindingCount: 1, bindings: [{ serverId: 1, interfaceName: "client-vlan", peerSpecific: false }] }
|
||||
const user: FlowClientInput = { id: "u", login: "user", name: "Name", active: true, bindingCount: 2, selectedBindingCount: 1, bindings: [{ serverId: 1, interfaceName: "client-vlan", peerSpecific: false, attributable: true }] }
|
||||
const observed = observeFlowClient(user, [row, { ...row, inIface: "2", bytes: 9999 }, { ...row, serverId: 2, bytes: 8888 }], 5)
|
||||
assert.equal(observed.ingressNamedRowsBytes, 1000); assert.equal(observed.ingressNamedRowCount, 1)
|
||||
assert.equal(observed.ifIndexRowsNotAttributed, 1); assert.equal(observed.completeSourceSet, false); assert.equal(observed.completeAttribution, false)
|
||||
assert.equal(observed.availability, "unknown"); assert.equal(observed.rxMbps, null); assert.equal(observed.txMbps, null); assert.equal(observed.historicalOwnershipVerified, false)
|
||||
assert.equal(observeFlowClient(user, [row], 5).completeAttribution, false)
|
||||
const peer = observeFlowClient({ ...user, bindings: [{ ...user.bindings[0], peerSpecific: true }] }, [row], 5)
|
||||
const peer = observeFlowClient({ ...user, bindings: [{ ...user.bindings[0], peerSpecific: true, attributable: false }] }, [row], 5)
|
||||
assert.equal(peer.ingressNamedRowsBytes, null); assert.equal(peer.peerBindingsNotAttributed, 1)
|
||||
const exclusivePeer = observeFlowClient({ ...user, bindingCount: 1, bindings: [{ ...user.bindings[0], peerSpecific: true }] }, [row], 5)
|
||||
assert.equal(exclusivePeer.ingressNamedRowsBytes, 1000)
|
||||
assert.equal(exclusivePeer.peerBindingsNotAttributed, 0)
|
||||
assert.equal(exclusivePeer.completeAttribution, true)
|
||||
assert.equal(observeFlowClient({ ...user, active: false }, [], 5).availability, "unknown")
|
||||
const source = { id: 1, name: "R", site: "site", country: "RU", host: "192.0.2.1", type: "home-router", enabled: false }
|
||||
const exporter = observeFlowExporter({ catalog: { list: [source], byId: new Map([[1, source]]) }, configuredIds: new Set([1]), configurationMembershipVerified: true, window: { rows: [row], since: "", until: "", topRowsPerBucketLimit: 20 } }, 1, 5)
|
||||
|
||||
@@ -3,7 +3,7 @@ import { flowCounter, flowCounterSum } from "./traffic-flow-observed-values.js"
|
||||
export { flowCounter, flowCounterSum } from "./traffic-flow-observed-values.js"
|
||||
import { listStoredFlowRows, type PendingFlowRow } from "./traffic-flow-ingest.js"
|
||||
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
|
||||
import { getServerCatalog } from "./traffic-flow-topology.js"
|
||||
import { flowBindingAttributionSql, getServerCatalog } from "./traffic-flow-topology.js"
|
||||
import { observeFlowRing } from "./traffic-flow-engine.js"
|
||||
|
||||
const fail = (message: string) => Object.assign(new Error(message), { statusCode: 502 })
|
||||
@@ -39,7 +39,7 @@ export async function readFlowExporterInputs(minutes: number, serverIds?: readon
|
||||
}
|
||||
export interface FlowClientInput {
|
||||
id: string; login: string; name: string; active: boolean; bindingCount: number; selectedBindingCount: number;
|
||||
bindings: { serverId: number; interfaceName: string; peerSpecific: boolean }[];
|
||||
bindings: { serverId: number; interfaceName: string; peerSpecific: boolean; attributable: boolean }[];
|
||||
}
|
||||
/** Eligibility, hidden-binding exclusion, paging and selected bindings use one
|
||||
* SQL statement/snapshot. No hidden user or binding is deserialized in Node. */
|
||||
@@ -57,7 +57,8 @@ export async function readFlowClientInputs(minutes: number, options?: { serverId
|
||||
SELECT p.*,
|
||||
(SELECT count(*) FROM user_interface_bindings b WHERE b.user_id=p.id) AS "bindingCount",
|
||||
(SELECT count(*) FROM user_interface_bindings b WHERE b.user_id=p.id AND ($1::bigint[] IS NULL OR b.server_id=ANY($1))) AS "selectedBindingCount",
|
||||
COALESCE((SELECT jsonb_agg(jsonb_build_object('serverId',b.server_id,'interfaceName',b.interface_name,'peerSpecific',b.peer_public_key<>''))
|
||||
COALESCE((SELECT jsonb_agg(jsonb_build_object('serverId',b.server_id,'interfaceName',b.interface_name,
|
||||
'peerSpecific',b.peer_public_key<>'','attributable',(${flowBindingAttributionSql})))
|
||||
FROM (SELECT b.* FROM user_interface_bindings b WHERE b.user_id=p.id AND ($1::bigint[] IS NULL OR b.server_id=ANY($1)) ORDER BY b.id LIMIT $5) b),'[]'::jsonb) AS bindings
|
||||
FROM page p
|
||||
) SELECT (SELECT count(*) FROM eligible) AS total,COALESCE(jsonb_agg(to_jsonb(projected)),'[]'::jsonb) AS users FROM projected
|
||||
@@ -68,7 +69,7 @@ export async function readFlowClientInputs(minutes: number, options?: { serverId
|
||||
if (!user || typeof user.id !== "string" || typeof user.login !== "string" || typeof user.name !== "string" || typeof user.active !== "boolean" || !Array.isArray(user.bindings)) throw fail("Некорректный клиент NetFlow")
|
||||
const bindingCount = flowCounter(user.bindingCount), selectedBindingCount = flowCounter(user.selectedBindingCount)
|
||||
if (options && user.bindings.length > 1000 || user.bindings.length !== selectedBindingCount) throw fail("Превышен предел привязок клиента NetFlow")
|
||||
if (user.bindings.some((binding: FlowClientInput["bindings"][number]) => !Number.isSafeInteger(binding.serverId) || typeof binding.interfaceName !== "string" || typeof binding.peerSpecific !== "boolean" || selected && !selected.includes(binding.serverId))) throw fail("Некорректная привязка клиента NetFlow")
|
||||
if (user.bindings.some((binding: FlowClientInput["bindings"][number]) => !Number.isSafeInteger(binding.serverId) || typeof binding.interfaceName !== "string" || typeof binding.peerSpecific !== "boolean" || typeof binding.attributable !== "boolean" || selected && !selected.includes(binding.serverId))) throw fail("Некорректная привязка клиента NetFlow")
|
||||
return { id: user.id, login: user.login, name: user.name, active: user.active, bindingCount, selectedBindingCount, bindings: user.bindings }
|
||||
})
|
||||
return { users, total, window: await readFlowCatalogWindow(minutes, selected) }
|
||||
@@ -84,16 +85,16 @@ export function observeFlowExporter(input: Awaited<ReturnType<typeof readFlowExp
|
||||
}
|
||||
export function observeFlowClient(user: FlowClientInput, rows: PendingFlowRow[], minutes: number) {
|
||||
const interfaces = new Map<number, Set<string>>()
|
||||
for (const binding of user.bindings) if (!binding.peerSpecific) {
|
||||
for (const binding of user.bindings) if (binding.attributable) {
|
||||
const names = interfaces.get(binding.serverId) ?? new Set<string>(); names.add(binding.interfaceName); interfaces.set(binding.serverId, names)
|
||||
}
|
||||
const ifIndexRowsNotAttributed = rows.filter(row => interfaces.has(row.serverId) && /^#?\d+$/.test(row.inIface)).length
|
||||
const matched = rows.filter(row => !/^#?\d+$/.test(row.inIface) && interfaces.get(row.serverId)?.has(row.inIface))
|
||||
const attributable = user.bindings.some(binding => !binding.peerSpecific), bytes = attributable ? flowCounterSum(matched.map(row => row.bytes)) : null
|
||||
const attributable = interfaces.size > 0, bytes = attributable ? flowCounterSum(matched.map(row => row.bytes)) : null
|
||||
return { id: user.id, name: user.login, displayName: user.name, accountEnabled: user.active, availability: "unknown",
|
||||
scopedBindingCount: user.bindingCount, selectedBindingCount: user.selectedBindingCount, peerBindingsNotAttributed: user.bindings.filter(binding => binding.peerSpecific).length,
|
||||
completeSourceSet: user.bindingCount === user.selectedBindingCount, completeAttribution: user.bindingCount === user.selectedBindingCount && user.bindings.every(binding => !binding.peerSpecific) && ifIndexRowsNotAttributed === 0,
|
||||
ifIndexRowsNotAttributed, historicalOwnershipVerified: false, attribution: "current-named-whole-interface-bindings",
|
||||
scopedBindingCount: user.bindingCount, selectedBindingCount: user.selectedBindingCount, peerBindingsNotAttributed: user.bindings.filter(binding => binding.peerSpecific && !binding.attributable).length,
|
||||
completeSourceSet: user.bindingCount === user.selectedBindingCount, completeAttribution: user.bindingCount === user.selectedBindingCount && user.bindings.every(binding => binding.attributable) && ifIndexRowsNotAttributed === 0,
|
||||
ifIndexRowsNotAttributed, historicalOwnershipVerified: false, attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard",
|
||||
ingressNamedRowsBytes: bytes, ingressNamedRowCount: attributable ? matched.length : null,
|
||||
ingressNamedRowsMeanMbps: bytes === null ? null : bytes * 8 / (minutes * 60) / 1000000,
|
||||
serverContextFlowRing: user.bindings.length ? { serverId: user.bindings[0].serverId, scope: "server-payload; not per-client", ...observeFlowRing(user.bindings[0].serverId) } : null,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { applicationName } from "./traffic-flow-apps.js"
|
||||
import { applicationName, flowPortApplication } from "./traffic-flow-apps.js"
|
||||
import { classifyFlowDst, disableCatalogFetchForTests, resetFlowCatalogForTests, seedFlowCatalogForTests } from "./traffic-flow-classify.js"
|
||||
|
||||
disableCatalogFetchForTests()
|
||||
@@ -7,12 +7,17 @@ resetFlowCatalogForTests()
|
||||
seedFlowCatalogForTests({
|
||||
cidrs: [{ cidr: "192.0.2.0/24", purpose: "steam-gaming" },
|
||||
{ cidr: "198.51.100.0/25", purpose: "Игры" },
|
||||
{ cidr: "198.51.100.128/25", purpose: "Видео / стриминг" }],
|
||||
{ cidr: "198.51.100.128/25", purpose: "Видео / стриминг" },
|
||||
{ cidr: "173.194.0.0/16", purpose: "GOOGLE" },
|
||||
{ cidr: "173.194.1.0/24", purpose: "Work" },
|
||||
{ cidr: "57.144.0.0/16", purpose: "Meta" },
|
||||
{ cidr: "203.0.113.128/25", purpose: "main" }],
|
||||
})
|
||||
|
||||
const hit = classifyFlowDst("192.0.2.10", 6, 443, 50000, null)
|
||||
assert.equal(hit.category, "Игры")
|
||||
assert.equal(hit.service, "steam-gaming")
|
||||
assert.equal(hit.basis, "catalog")
|
||||
assert.equal(classifyFlowDst("198.51.100.10", 6, 443, 50000, null).category, "Игры")
|
||||
assert.equal(classifyFlowDst("198.51.100.150", 6, 443, 50000, null).category, "Видео / стриминг")
|
||||
|
||||
@@ -37,11 +42,11 @@ const google = classifyFlowDst("173.194.160.163", 6, 443, 1, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(google.service, "YouTube")
|
||||
assert.equal(google.category, "Видео / стриминг")
|
||||
assert.deepEqual(google, { service: "YouTube", category: "Видео / стриминг", basis: "heuristic" })
|
||||
assert.equal(classifyFlowDst("173.194.1.1", 17, 443, 50000, null).service, "Work")
|
||||
|
||||
const googleCidr = classifyFlowDst("173.194.151.65", 6, 80, 50000, null)
|
||||
assert.equal(googleCidr.service, "Google")
|
||||
assert.equal(googleCidr.service, "GOOGLE")
|
||||
assert.equal(googleCidr.category, "Веб")
|
||||
|
||||
const youtube = classifyFlowDst("173.194.160.163", 6, 443, 1, {
|
||||
@@ -56,6 +61,8 @@ const youtube = classifyFlowDst("173.194.160.163", 6, 443, 1, {
|
||||
})
|
||||
assert.equal(youtube.service, "YouTube")
|
||||
assert.equal(youtube.category, "Видео / стриминг")
|
||||
assert.equal(youtube.basis, "network")
|
||||
assert.equal(classifyFlowDst("208.65.153.1", 17, 443, 50000, null).basis, "network")
|
||||
|
||||
const valve = classifyFlowDst("203.0.113.40", 17, 27015, 50000, {
|
||||
prefix: "203.0.113.0/24",
|
||||
@@ -119,8 +126,8 @@ const googleCloud = classifyFlowDst("203.0.113.43", 6, 443, 1, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(googleCloud.service, "YouTube")
|
||||
assert.equal(googleCloud.category, "Видео / стриминг")
|
||||
assert.equal(googleCloud.service, "Google")
|
||||
assert.equal(googleCloud.category, "Веб")
|
||||
|
||||
const gre = classifyFlowDst("198.51.100.1", 47, 0, 0, null)
|
||||
assert.equal(gre.service, "GRE")
|
||||
@@ -146,8 +153,10 @@ const dnsGoogle = classifyFlowDst("8.8.8.8", 17, 53, 53000, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(dnsGoogle.service, "Google")
|
||||
assert.notEqual(dnsGoogle.service, "Прочее")
|
||||
assert.equal(dnsGoogle.service, "DNS")
|
||||
assert.deepEqual(classifyFlowDst("104.18.35.51", 6, 853, 53000, null), {service: "DNS", category: "DNS", basis: "port"})
|
||||
assert.deepEqual(classifyFlowDst("203.0.113.10", 17, 13231, 53000, null), {service: "WireGuard", category: "Туннель", basis: "port"})
|
||||
assert.deepEqual(classifyFlowDst("203.0.113.132", 6, 443, 53000, null), {service: "Прочее", category: "Прочее", basis: "unknown"})
|
||||
const ipv6Yt = classifyFlowDst("2001:4860:4860::8888", 17, 443, 50000, {
|
||||
prefix: "2001:4860:4860::8888/128",
|
||||
asn: 15169,
|
||||
@@ -158,7 +167,7 @@ const ipv6Yt = classifyFlowDst("2001:4860:4860::8888", 17, 443, 50000, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(ipv6Yt.service, "YouTube")
|
||||
assert.equal(ipv6Yt.service, "Google")
|
||||
|
||||
const instagram = classifyFlowDst("157.240.12.52", 6, 443, 62598, {
|
||||
prefix: "157.240.0.0/16",
|
||||
@@ -170,9 +179,7 @@ const instagram = classifyFlowDst("157.240.12.52", 6, 443, 62598, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(instagram.service, "Instagram")
|
||||
assert.equal(instagram.category, "Видео / стриминг")
|
||||
assert.notEqual(instagram.service, "Meta")
|
||||
assert.deepEqual(instagram, { service: "Instagram", category: "Видео / стриминг", basis: "heuristic" })
|
||||
|
||||
const metaHttp = classifyFlowDst("157.240.12.52", 6, 80, 50000, {
|
||||
prefix: "157.240.0.0/16",
|
||||
@@ -198,14 +205,17 @@ const igHolder = classifyFlowDst("203.0.113.80", 6, 443, 1, {
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(igHolder.service, "Instagram")
|
||||
assert.equal(igHolder.basis, "network")
|
||||
|
||||
const igCidr = classifyFlowDst("57.144.22.192", 17, 443, 50000, null)
|
||||
assert.equal(igCidr.service, "Instagram")
|
||||
assert.equal(igCidr.category, "Видео / стриминг")
|
||||
assert.deepEqual(igCidr, { service: "Instagram", category: "Видео / стриминг", basis: "heuristic" })
|
||||
|
||||
const esp = classifyFlowDst("198.51.100.1", 50, 0, 0, null)
|
||||
assert.equal(esp.category, "Туннель")
|
||||
assert.equal(applicationName(17, 443, 50000), "QUIC")
|
||||
assert.equal(applicationName(17, 853, 50000), "DNS")
|
||||
assert.equal(flowPortApplication(6, 853), "DNS over TLS")
|
||||
assert.equal(flowPortApplication(17, 853), "Защищённый DNS")
|
||||
assert.equal(flowPortApplication(17, 50505), null)
|
||||
|
||||
console.log("traffic-flow-classify.test.ts: ok")
|
||||
@@ -6,10 +6,12 @@ import { withActiveDatabaseRequest } from "../modules/mcp/database-request-lease
|
||||
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 {
|
||||
@@ -54,6 +56,7 @@ export function categoryFromPurpose(purpose: string, proto: number, dstPort: num
|
||||
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"
|
||||
@@ -71,6 +74,11 @@ function matchCidr(ip: string,rows=cidrs): CatalogCidr | null {
|
||||
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,
|
||||
@@ -80,20 +88,23 @@ export function classifyFlowDst(
|
||||
opts?: { ignoreTunnelProto?: boolean;catalog?:{cidrs:CatalogCidr[];asnPurpose:Map<number,string>} },
|
||||
): FlowClassification {
|
||||
if (!opts?.ignoreTunnelProto) {
|
||||
if (proto === 47) return { service: "GRE", category: "Туннель" }
|
||||
if (proto === 50) return { service: "ESP", category: "Туннель" }
|
||||
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 (app === "WireGuard") return { service: "WireGuard", category: "Туннель" }
|
||||
const hit = matchCidr(dst,opts?.catalog?.cidrs)
|
||||
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)
|
||||
const asnName = ripe?.asn ? (opts?.catalog?.asnPurpose??asnPurpose).get(ripe.asn) : undefined
|
||||
const service = (hit?.purpose || brand?.service || asnName || OTHER_SERVICE).trim() || OTHER_SERVICE
|
||||
const category = hit
|
||||
? categoryFromPurpose(hit.purpose, proto, dstPort, srcPort)
|
||||
: (brand?.category || categoryFromPurpose(asnName || "", proto, dstPort, srcPort))
|
||||
return { service, category }
|
||||
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. */
|
||||
|
||||
@@ -142,7 +142,7 @@ assert.equal(classifyInternetBrand("8.8.8.8", 6, 443, 51234, {
|
||||
fetchedAt: Date.now(),
|
||||
})?.service, "Google")
|
||||
assert.equal(mapInternetBrand("203.0.113.50", 6, 443, 51234, null).service, "Прочее")
|
||||
assert.deepEqual(mapInternetBrand("185.246.117.91", 17, 53, 53000, null), { service: "DNS", category: "DNS" })
|
||||
assert.deepEqual(mapInternetBrand("185.246.117.91", 17, 53, 53000, null), { service: "DNS", category: "DNS", basis: "port" })
|
||||
assert.equal(mapInternetBrand("8.8.8.8", 47, 0, 0, null).service, "Прочее")
|
||||
assert.equal(mapInternetBrand("8.8.8.8", 6, 443, 51234, {
|
||||
prefix: "8.8.8.0/24",
|
||||
@@ -174,7 +174,7 @@ assert.equal(mapInternetBrand("8.8.8.8", 17, 53, 53000, {
|
||||
holder: "GOOGLE",
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
}).service, "Google")
|
||||
}).service, "DNS")
|
||||
assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, {
|
||||
prefix: "2001:4860:4860::8888/128",
|
||||
asn: 15169,
|
||||
@@ -184,7 +184,7 @@ assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, {
|
||||
holder: "GOOGLE",
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
}).service, "YouTube")
|
||||
}).service, "Google")
|
||||
assert.equal(mapInternetBrand("64.233.161.1", 17, 443, 50000, null).service, "YouTube")
|
||||
assert.equal(mapInternetBrand("142.250.1.10", 6, 443, 1, null).service, "YouTube")
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ export function destCtxForIface(
|
||||
}
|
||||
}
|
||||
|
||||
const OTHER_BRAND: FlowClassification = { service: OTHER_SERVICE, category: OTHER_SERVICE }
|
||||
export const OTHER_BRAND: FlowClassification = { service: OTHER_SERVICE, category: OTHER_SERVICE, basis: "unknown" }
|
||||
|
||||
function isTunnelProto(proto: number, dstPort: number, srcPort: number): boolean {
|
||||
if (proto === 47 || proto === 50) return true
|
||||
@@ -85,7 +85,7 @@ export function classifyInternetBrand(
|
||||
dstPort: number,
|
||||
srcPort: number,
|
||||
ripe: FlowIpMeta | null,
|
||||
): FlowClassification | null {
|
||||
): Pick<FlowClassification, "service" | "category"> | null {
|
||||
if (isTunnelProto(proto, dstPort, srcPort)) return null
|
||||
const brand = resolveFlowBrand(dst, ripe?.asn ?? 0, ripe?.holder ?? "", proto, dstPort, srcPort)
|
||||
if (brand && isNamedInternetService(brand.service, brand.category)) return brand
|
||||
@@ -105,7 +105,7 @@ export function mapInternetBrand(
|
||||
if (isTunnelProto(proto, dstPort, srcPort)) return OTHER_BRAND
|
||||
const classified = classifyFlowDst(dst, proto, dstPort, srcPort, ripe, { ignoreTunnelProto: true })
|
||||
if (isNamedInternetService(classified.service, classified.category)) return classified
|
||||
return { service: classified.category, category: classified.category }
|
||||
return { ...classified, service: classified.category }
|
||||
}
|
||||
|
||||
export function resolveInternetDest(opts: {
|
||||
|
||||
@@ -114,7 +114,7 @@ setGeoipReadersForTests({
|
||||
})
|
||||
const v6meta = resolveFlowIp("2001:4860:4860::8888")
|
||||
assert.equal(v6meta?.asn, 15169)
|
||||
assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, v6meta).service, "YouTube")
|
||||
assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, v6meta).service, "Google")
|
||||
assert.notEqual(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, v6meta).service, "Прочее")
|
||||
const cidrYt = mapInternetBrand("64.233.161.1", 17, 443, 50000, resolveFlowIp("64.233.161.1"))
|
||||
assert.equal(cidrYt.service, "YouTube")
|
||||
|
||||
@@ -3,6 +3,8 @@ import { mock } from "node:test"
|
||||
import { dbQuery } from "../db/index.js"
|
||||
import { configureEngine, flushEngineNow } from "./traffic-flow-engine.js"
|
||||
import { parseFlowPacket } from "./traffic-flow-parse.js"
|
||||
import { buildFlowAnalytics } from "./traffic-flow-analytics.js"
|
||||
import { readFlowClientInputs } from "./traffic-flow-catalog-read.js"
|
||||
import { rememberServerIfaces, resetIfaceCacheForTests } from "./traffic-flow-ifindex.js"
|
||||
import {
|
||||
ingestParsedFlowsForServerForTests,
|
||||
@@ -112,8 +114,9 @@ const { rows: [snapshot] } = await dbQuery<{id: number}>(`
|
||||
INSERT INTO internet_path_snapshots(sampled_at,payload_json) VALUES (?,?::jsonb) RETURNING id
|
||||
`, [new Date(bucket).toISOString(), JSON.stringify({ collectionComplete: true, greTunnels: [
|
||||
{serverId: "7", name: "gre-jh-en", remoteAddress: "198.51.100.1", enabled: true},
|
||||
{serverId: "7", name: "SWE-VEESP", remoteAddress: "198.51.100.1", enabled: true},
|
||||
{serverId: "7", name: "gre-second", remoteAddress: "198.51.100.2", enabled: true},
|
||||
{serverId: "7", name: "SWE-VEESP", remoteAddress: "198.51.100.1", enabled: true, nativeIndex:4, ifIndex:6, observedNextHops:[{ip:"10.200.100.54", serverId:"9"}]},
|
||||
{serverId:"7", name:"gre-client", remoteAddress:"192.0.2.77", enabled:true,nativeIndex:5,ifIndex:7},
|
||||
{serverId: "7", name: "gre-second", remoteAddress: "198.51.100.2", enabled: true, nativeIndex:12, ifIndex:4, observedNextHops:[{ip:"10.200.101.54",serverId:"10"}]},
|
||||
] })])
|
||||
|
||||
const topo: FlowTopology = {
|
||||
@@ -460,13 +463,13 @@ try {
|
||||
assert.equal(leak.totalBytes, 30_000)
|
||||
assert.equal(leak.namedBytes, 10_000)
|
||||
assert.equal(leak.unclassifiedBytes, 20_000)
|
||||
const yt = leak.services?.find((s) => s.id === "svc:youtube")
|
||||
const youtube = leak.services?.find((s) => s.id === "svc:youtube")
|
||||
const other = leak.services?.find((s) => s.id === "svc:other")
|
||||
assert.ok(yt, "64.233:443 без RIPE → YouTube")
|
||||
assert.ok(youtube, "YouTube по общему диапазону Google без RIPE")
|
||||
assert.ok(other, "dest без бренда → Прочее")
|
||||
assert.equal(yt.bytes, 10_000)
|
||||
assert.equal(youtube.bytes, 10_000)
|
||||
assert.equal(other.bytes, 20_000)
|
||||
assert.ok(Math.abs(yt.share - 10 / 30) < 0.01)
|
||||
assert.ok(Math.abs(youtube.share - 10 / 30) < 0.01)
|
||||
assert.ok(Math.abs(other.share - 20 / 30) < 0.01)
|
||||
assert.equal((leak.serviceEdges ?? []).reduce((n, e) => n + e.bytes, 0), hop.bytes)
|
||||
} finally {
|
||||
@@ -656,7 +659,7 @@ ingestClosed(7, [
|
||||
try {
|
||||
resetFlowMapHopsCacheForTests()
|
||||
const rev = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
|
||||
assert.ok(rev.services?.some((s) => s.id === "svc:youtube"), "реверс googlevideo:443 → YouTube")
|
||||
assert.ok(rev.services?.some((s) => s.id === "svc:youtube"), "Ответный поток с порта 443 сети Google учитывается как YouTube")
|
||||
assert.ok(rev.services?.some((s) => s.id === "svc:cloudflare"), "реверс Cloudflare:443 → 10.x")
|
||||
assert.ok(rev.serviceEdges?.some((e) => e.toId === "svc:youtube" && e.fromId === "9"))
|
||||
} finally {
|
||||
@@ -735,7 +738,13 @@ ingestClosed(7, [
|
||||
try {
|
||||
resetFlowMapHopsCacheForTests()
|
||||
const wanOnly = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
|
||||
assert.equal(wanOnly.services?.find(s => s.id === "svc:youtube")?.bytes, 9000)
|
||||
const youtube = wanOnly.services?.find(s => s.id === "svc:youtube")
|
||||
assert.equal(youtube?.bytes, 9000)
|
||||
assert.deepEqual(youtube.serviceEvidence, [{basis: "heuristic", bytes: 9000}])
|
||||
assert.deepEqual(youtube.trafficTypes, [{transport: "TCP", application: "HTTPS", bytes: 9000}])
|
||||
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.trafficTypes,
|
||||
[{transport: "UDP", application: "DNS", bytes: 6000}])
|
||||
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.serviceEvidence, [{basis: "port", bytes: 6000}])
|
||||
const dns = wanOnly.serviceEdges?.find(e => e.toId === "svc:dns")
|
||||
assert.deepEqual(dns && [dns.fromId, dns.observedOnly, dns.bytes], ["7", true, 6000])
|
||||
const dnsPath = wanOnly.servicePaths?.find(p => p.serviceId === "svc:dns")
|
||||
@@ -1044,6 +1053,7 @@ try {
|
||||
try {
|
||||
const map = await buildFlowMapHops({ serverId: 7, minutes: 5, minSharePct: 0 })
|
||||
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.bytes, 12000)
|
||||
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, new Date(bucket).toISOString())
|
||||
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes, Boolean(e.observedOnly)]), [["7", 9000, true], ["10", 2000, false], ["9", 1000, false]])
|
||||
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 12000)
|
||||
assert.equal(map.nodeUsers?.["7"]?.find(u => u.clientName === "Alice")?.bytes, 12000)
|
||||
@@ -1051,8 +1061,51 @@ try {
|
||||
|
||||
const recent = await buildFlowMapHops({ serverId: 7, minutes: 1, includeCurrentMinute: true, minSharePct: 0 })
|
||||
assert.equal(recent.windowSec, 90)
|
||||
const lastMinute = new Date(bucket + 60_000).toISOString()
|
||||
assert.equal(recent.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, lastMinute)
|
||||
assert.equal(recent.countryServiceGroups?.flatMap(g => g.services).find(s => s.label === "YouTube")?.lastBucketAt, lastMinute)
|
||||
assert.equal(recent.services?.find(s => s.id === "svc:youtube")?.bps, 900_012_000 * 8 / 90)
|
||||
assert.equal(recent.serviceEdges?.find(edge => edge.fromId === "9")?.bps, 900_001_000 * 8 / 90)
|
||||
const later = bucket + 150_000
|
||||
clock.mock.mockImplementation(() => later)
|
||||
ingestParsedFlowsForServerForTests(7, [{ ...flow, bytes: 0, packets: 1, outIface: "ether1" }])
|
||||
const idle = await buildFlowMapHops({ serverId: 7, minutes: 3, includeCurrentMinute: true, minSharePct: 0 })
|
||||
assert.equal(idle.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, lastMinute)
|
||||
|
||||
resetFlowRingsForTests()
|
||||
resetFlowMapHopsCacheForTests()
|
||||
clock.mock.mockImplementation(() => bucket + 90_000)
|
||||
const forward = { ...flow, src:"10.10.0.1", inIface:"5", outIface:"4", nextHop:"10.200.100.54", bytes:1000 }
|
||||
const reverse = { ...forward, src:forward.dst, dst:forward.src, srcPort:forward.dstPort, dstPort:forward.srcPort, inIface:"4", outIface:"5", nextHop:"0.0.0.0", bytes:9000 }
|
||||
ingestClosed(7, [forward, reverse])
|
||||
rememberServerIfaces(7, [{".id":"*4",name:"ether1"},{".id":"*5",name:"wrong-client"}])
|
||||
const direct = await buildFlowMapHops({serverId:7, minutes:1, minSharePct:0})
|
||||
assert.equal(direct.nodeUsers?.["9"]?.find(u => u.clientName === "Alice")?.bytes, 10000)
|
||||
const own = await buildFlowMapHops({serverId:7, userId:"u1", minutes:1, minSharePct:0})
|
||||
assert.equal(own.totalBytes, 10000)
|
||||
assert.deepEqual(direct.serviceEdges?.map(e => [e.fromId,e.bytes]), [["9",10000]])
|
||||
resetFlowRingsForTests()
|
||||
resetFlowMapHopsCacheForTests()
|
||||
ingestClosed(7, [reverse, {...forward, outIface:"ether1", bytes:500}, {...forward, src:"10.10.0.2", outIface:"48", bytes:250}])
|
||||
const unproven = await buildFlowMapHops({serverId:7, minutes:1, minSharePct:0})
|
||||
assert.deepEqual(unproven.serviceEdges?.map(e => [e.fromId,e.observedOnly,e.bytes]), [["7",true,9750]])
|
||||
resetFlowRingsForTests()
|
||||
resetFlowMapHopsCacheForTests()
|
||||
ingestClosed(7, [forward, reverse, {...forward, src:"10.10.0.2", nextHop:"10.200.101.54"}])
|
||||
const ambiguous = await buildFlowMapHops({serverId:7, minutes:1, minSharePct:0})
|
||||
assert.ok(ambiguous.serviceEdges?.every(e => e.observedOnly), "conflicting paths for one raw index")
|
||||
const scoped = await buildFlowMapHops({serverId:7,userId:"u1", minutes:1,minSharePct:0})
|
||||
assert.equal(scoped.totalBytes,0, "a conflicting interface namespace cannot establish client scope")
|
||||
|
||||
resetFlowRingsForTests()
|
||||
resetFlowMapHopsCacheForTests()
|
||||
clock.mock.mockImplementation(() => bucket + 150_000)
|
||||
ingestClosed(7, [forward])
|
||||
ingestClosed(7, [reverse], bucket + 60_000)
|
||||
const otherMinute = await buildFlowMapHops({serverId:7,minutes:2,minSharePct:0})
|
||||
assert.equal(otherMinute.serviceEdges?.find(e => e.fromId === "9")?.bytes, 1000)
|
||||
assert.equal(otherMinute.serviceEdges?.find(e => e.observedOnly)?.bytes, 9000)
|
||||
|
||||
} finally { clock.mock.restore() }
|
||||
} finally {
|
||||
await dbQuery("DELETE FROM internet_path_snapshots WHERE id=?", [snapshot.id])
|
||||
@@ -1060,6 +1113,31 @@ try {
|
||||
seedFlowTopologyForTests(null)
|
||||
}
|
||||
|
||||
// A video download can arrive in an earlier receipt minute than the latest HTTPS traffic.
|
||||
seedFlowTopologyForTests(topo)
|
||||
try {
|
||||
const youtube = (bytes: number) => ({ ...payloadFlow("173.194.151.65", bytes), proto: 17 })
|
||||
ingestClosed(7, [youtube(224_932_500)], bucket - 120_000)
|
||||
ingestClosed(7, [youtube(67_500), payloadFlow("104.18.35.51", 69_075_000)], bucket)
|
||||
const clock = mock.method(Date, "now", () => bucket + 90_000)
|
||||
try {
|
||||
const query = { serverId: 7, minSharePct: 0 }
|
||||
const recent = await buildFlowMapHops({ ...query, minutes: 1, includeCurrentMinute: true })
|
||||
assert.equal(recent.services?.find(s => s.id === "svc:youtube")?.bps, 6_000)
|
||||
assert.equal(recent.services?.find(s => s.id === "svc:cloudflare")?.bps, 6_140_000)
|
||||
|
||||
const map = await buildFlowMapHops({ ...query, minutes: 5 })
|
||||
assert.equal(map.windowSec, 300)
|
||||
const video = map.services?.find(s => s.id === "svc:youtube")
|
||||
assert.equal(video?.bytes, 225_000_000)
|
||||
assert.equal(video.bps, 6_000_000)
|
||||
assert.equal(map.services?.find(s => s.id === "svc:cloudflare")?.bytes, 69_075_000)
|
||||
} finally { clock.mock.restore() }
|
||||
} finally {
|
||||
resetFlowRingsForTests()
|
||||
seedFlowTopologyForTests(null)
|
||||
}
|
||||
|
||||
// Captured on the test CHR. Three 64-byte UDP packets traversed GRE A -> GRE B.
|
||||
// RouterOS also exported three 88-byte outer GRE packets on GRE B -> underlay.
|
||||
const datagram = Buffer.from(
|
||||
@@ -1132,6 +1210,36 @@ try {
|
||||
assert.equal(resolveClient(topology, sid, "wg-shared"), null, "общий WG не присваивается одному пользователю")
|
||||
assert.equal(resolveClient(topology, sid, "gre-owner")?.userId, alice)
|
||||
}
|
||||
const flow = { ...payloadFlow("8.8.8.8", 1000), inIface: "gre-owner", outIface: "uplink-a" }
|
||||
ingestClosed(sid, [flow, { ...flow, inIface: "wg-shared", srcPort: 49151 }], bucket - 60_000)
|
||||
const aliceMap = await buildFlowMapHops({serverId: sid, minutes: 5, userId: alice})
|
||||
const aliceTraffic = await buildFlowAnalytics({serverId: sid, minutes: 5, userId: alice})
|
||||
const bobTraffic = await buildFlowAnalytics({serverId: sid, minutes: 5, userId: bob})
|
||||
assert.equal(aliceMap.totalBytes, 1000)
|
||||
assert.equal(aliceTraffic.bytes, aliceMap.totalBytes)
|
||||
assert.equal(bobTraffic.bytes, 0)
|
||||
|
||||
await dbQuery(`INSERT INTO user_interface_bindings(id,user_id,server_id,interface_name,interface_type,peer_public_key)
|
||||
VALUES (?, ?, ?, 'wg-exclusive', 'wg', 'alice-exclusive')`, [alice + "-exclusive", alice, sid])
|
||||
assert.equal(resolveClient(await loadFlowTopology([sid]), sid, "wg-exclusive"), null)
|
||||
await dbQuery("UPDATE servers SET enabled=true WHERE id=?", [sid])
|
||||
const sampledAt = new Date().toISOString()
|
||||
await dbQuery(`INSERT INTO traffic_samples(server_id,interface_name,peer_public_key,sampled_at)
|
||||
VALUES (?, 'wg-exclusive', 'alice-exclusive', ?)`, [sid, sampledAt])
|
||||
await dbQuery(`INSERT INTO traffic_collection_state(server_id,server_updated_at,last_attempt_at,last_succeeded_at,status)
|
||||
SELECT id,updated_at,?,?,'ok' FROM servers WHERE id=?`, [sampledAt, sampledAt, sid])
|
||||
seedFlowTopologyForTests(null)
|
||||
assert.equal(resolveClient(await loadFlowTopology([sid]), sid, "wg-exclusive")?.userId, alice)
|
||||
const {users} = await readFlowClientInputs(5, {serverIds: [sid], allowedServerIds: [sid], offset: 0, limit: 10})
|
||||
assert.equal(users.find(u => u.id === alice)?.bindings.find(b => b.interfaceName === "wg-exclusive")?.attributable, true)
|
||||
ingestClosed(sid, [{ ...flow, inIface: "wg-exclusive", bytes: 2000, srcPort: 49155 }], bucket - 60_000)
|
||||
resetFlowMapHopsCacheForTests()
|
||||
assert.equal((await buildFlowMapHops({serverId: sid, minutes: 5, userId: alice})).totalBytes, 3000)
|
||||
assert.equal((await buildFlowAnalytics({serverId: sid, minutes: 5, userId: alice})).bytes, 3000)
|
||||
await dbQuery(`INSERT INTO traffic_samples(server_id,interface_name,peer_public_key,sampled_at)
|
||||
VALUES (?, 'wg-exclusive', 'unbound-peer', ?)`, [sid, sampledAt])
|
||||
seedFlowTopologyForTests(null)
|
||||
assert.equal(resolveClient(await loadFlowTopology([sid]), sid, "wg-exclusive"), null, "второй peer виден даже без привязки в приложении")
|
||||
} finally {
|
||||
await dbQuery("DELETE FROM app_users WHERE id IN (?,?)", [alice, bob])
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { FlowSourceWindowTooLarge, FlowSqlSourceTooLarge } from "./traffic-flow-read-window.js"
|
||||
import { flowReadDbAll } from "./traffic-flow-read-policy.js"
|
||||
import { isDeepStrictEqual } from "node:util"
|
||||
import { readFlowMapSourceLimits } from "./traffic-flow-source-limits.js"
|
||||
import { flowCounter, flowCounterSum } from "./traffic-flow-observed-values.js"
|
||||
import type { FlowMapInterfaceTraffic } from "@mmapp/contracts/traffic-flow"
|
||||
import type { FlowMapInterfaceTraffic, FlowServiceBasis } from "@mmapp/contracts/traffic-flow"
|
||||
import type { ScopedFlowAnalyticsRead } from "./traffic-flow-analytics.js"
|
||||
import type { FlowMapCountryServiceGroup, FlowMapHop, FlowMapHopsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import { flowRowMatchesFilter } from "./traffic-flow-apps.js"
|
||||
import { flowPortApplication, flowRowMatchesFilter } from "./traffic-flow-apps.js"
|
||||
import { OTHER_SERVICE, isNamedInternetService, mapCountryNodeId, mapCountryServiceNodeId, mapServiceNodeId, resolveRipeCountry } from "./traffic-flow-brands.js"
|
||||
import type { FlowIpMeta } from "./traffic-flow-ripe.js"
|
||||
import { refreshFlowCatalogInBackground } from "./traffic-flow-classify.js"
|
||||
@@ -13,12 +14,13 @@ import { collapseGreEspRows, dedupFlowRowsAcrossExporters, dedupFlowRowsMaxBytes
|
||||
import { getFlowListenerState, listStoredFlowRows } from "./traffic-flow-ingest.js"
|
||||
import { resolveIfaceName } from "./traffic-flow-ifaces.js"
|
||||
import { classifyFlowPlane, shouldKeepPlane } from "./traffic-flow-planes.js"
|
||||
import { destCtxForIface, flowRateDirection, mapInternetBrand } from "./traffic-flow-dest.js"
|
||||
import { destCtxForIface, flowRateDirection, mapInternetBrand, OTHER_BRAND } from "./traffic-flow-dest.js"
|
||||
import { protoName } from "./traffic-flow-parse.js"
|
||||
import { resolveFlowEndpoints } from "./traffic-flow-ip.js"
|
||||
import { geoipReadersStatus, resolveFlowIp } from "./traffic-flow-geoip.js"
|
||||
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
|
||||
import { loadFlowTopology, resolveClient, getServerCatalog, type FlowClientBinding, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM } from "./traffic-flow-engine.js"
|
||||
import { loadFlowTopology, resolveFlowClient, flowClientInterfaces, getServerCatalog, type FlowClientBinding } from "./traffic-flow-topology.js"
|
||||
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM, minuteBucketIso } from "./traffic-flow-engine.js"
|
||||
|
||||
export const DEFAULT_MAP_SERVICE_MIN_SHARE_PCT = 5
|
||||
export const MAP_SERVICE_NODE_CAP = 20
|
||||
@@ -73,9 +75,11 @@ interface FromAcc {
|
||||
interface DstAcc {
|
||||
dst: string
|
||||
bytes: number
|
||||
lastBucketAt: string
|
||||
proto: number
|
||||
dstPort: number
|
||||
srcPort: number
|
||||
application: string | null
|
||||
fromBytes: Map<string, FromAcc>
|
||||
}
|
||||
|
||||
@@ -83,6 +87,9 @@ interface DestTotal {
|
||||
label: string
|
||||
category: string
|
||||
bytes: number
|
||||
lastBucketAt: string
|
||||
trafficTypes?: Map<string, NonNullable<FlowMapService["trafficTypes"]>[number]>
|
||||
serviceEvidence?: Map<FlowServiceBasis, number>
|
||||
}
|
||||
|
||||
interface DestEdgeAcc {
|
||||
@@ -155,13 +162,22 @@ export function pickMapServices(
|
||||
.slice(0, cap)
|
||||
}
|
||||
|
||||
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number): void {
|
||||
const prev = totals.get(id)
|
||||
if (prev) {
|
||||
prev.bytes += bytes
|
||||
return
|
||||
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number, lastBucketAt: string,
|
||||
detail?: { transport: string; application: string | null; basis: FlowServiceBasis }): void {
|
||||
const total = totals.get(id) ?? { label, category, bytes: 0, lastBucketAt }
|
||||
total.bytes += bytes
|
||||
if (lastBucketAt > total.lastBucketAt) total.lastBucketAt = lastBucketAt
|
||||
if (detail && bytes > 0) {
|
||||
const { transport, application, basis } = detail
|
||||
const types = total.trafficTypes ??= new Map()
|
||||
const key = JSON.stringify([transport, application])
|
||||
const type = types.get(key) ?? { transport, application, bytes: 0 }
|
||||
type.bytes += bytes
|
||||
types.set(key, type)
|
||||
const evidence = total.serviceEvidence ??= new Map()
|
||||
evidence.set(basis, (evidence.get(basis) ?? 0) + bytes)
|
||||
}
|
||||
totals.set(id, { label, category, bytes })
|
||||
totals.set(id, total)
|
||||
}
|
||||
|
||||
function bumpDestFrom(
|
||||
@@ -237,8 +253,11 @@ function finalizeDestLayer(
|
||||
label: s.label,
|
||||
category: s.category,
|
||||
bytes: s.bytes,
|
||||
...(s.lastBucketAt ? { lastBucketAt: minuteBucketIso(Date.parse(s.lastBucketAt)) } : {}),
|
||||
bps: (s.bytes * 8) / windowSec,
|
||||
share: shareBase > 0 ? s.bytes / shareBase : 0,
|
||||
...(s.trafficTypes ? { trafficTypes: [...s.trafficTypes.values()].sort((a, b) => b.bytes - a.bytes).slice(0, 5) } : {}),
|
||||
...(s.serviceEvidence ? { serviceEvidence: [...s.serviceEvidence].map(([basis, bytes]) => ({ basis, bytes })).sort((a, b) => b.bytes - a.bytes) } : {}),
|
||||
}))
|
||||
.sort((a, b) => b.bytes - a.bytes),
|
||||
minSharePct,
|
||||
@@ -352,18 +371,6 @@ function ifaceUsable(name: string): boolean {
|
||||
return Boolean(name) && name !== "—"
|
||||
}
|
||||
|
||||
function resolveMapClient(
|
||||
topo: FlowTopology,
|
||||
serverId: number,
|
||||
inName: string,
|
||||
outName: string,
|
||||
): FlowClientBinding | null | undefined {
|
||||
const ingress = resolveClient(topo, serverId, inName)
|
||||
const egress = resolveClient(topo, serverId, outName)
|
||||
if (ingress && egress && ingress.userId !== egress.userId) return null
|
||||
return ingress ?? egress ?? undefined
|
||||
}
|
||||
|
||||
function bump(acc: Map<string, HopAcc>, key: string, seed: Omit<HopAcc, "bytes" | "bytesFwd" | "bytesRev">, bytes: number, dir: "fwd" | "rev" | "both"): void {
|
||||
const prev = acc.get(key)
|
||||
const addFwd = dir === "fwd" || dir === "both" ? bytes : 0
|
||||
@@ -442,16 +449,49 @@ async function readInterfaceTraffic(serverIds: number[], iface: string, q: FlowM
|
||||
}
|
||||
|
||||
// Interface names are local to the exporter; match them against the GRE inventory for the flow minute.
|
||||
async function readMapGrePeers(rows: { serverId: number; bucketAt: string; inIface: string; outIface: string }[]) {
|
||||
async function readMapGrePeers(rows: { serverId: number; bucketAt: string; inIface: string; outIface: string; nextHop: string }[]) {
|
||||
const peers = new Map<string, Map<string, string>>()
|
||||
if (!rows.length) return peers
|
||||
const buckets = new Set<string>(), names = new Set<string>()
|
||||
const nextHops = new Map<string, { serverId: number; iface: string; native: number | null; explicit: number | null } | null>()
|
||||
const ingress = new Map<string, { serverId: number; iface: string } | null>()
|
||||
const names = new Map<string, string>()
|
||||
const namespace = new Map<string, number>()
|
||||
const keyFor = (bucket: string, server: number | string) => JSON.stringify([bucket, String(server)])
|
||||
const ifaceName = (row: typeof rows[number], raw: string) => {
|
||||
const key = keyFor(row.bucketAt, row.serverId)
|
||||
const mode = namespace.get(key)
|
||||
const cached = resolveIfaceName(row.serverId, raw).name
|
||||
if (!/^[1-9][0-9]*$/.test(raw)) return cached
|
||||
const native = names.get(JSON.stringify([key, 1, Number(raw)]))
|
||||
const explicit = names.get(JSON.stringify([key, 2, Number(raw)]))
|
||||
if (mode === 1 || mode === 2) {
|
||||
const exact = mode === 1 ? native : explicit
|
||||
if (exact !== undefined) return exact || "#" + raw
|
||||
if (native !== undefined || explicit !== undefined) return "#" + raw
|
||||
}
|
||||
// The current alias cache cannot resolve conflicting historical interface identities.
|
||||
if ([native, explicit].some(name => name !== undefined && name !== cached)) return "#" + raw
|
||||
return cached
|
||||
}
|
||||
if (!rows.length) return { peers, nextHops, ingress, ifaceName }
|
||||
const buckets = new Set<string>()
|
||||
for (const row of rows) {
|
||||
buckets.add(row.bucketAt)
|
||||
for (const iface of [row.inIface, row.outIface]) names.add(row.serverId + "|" + resolveIfaceName(row.serverId, iface).name)
|
||||
}
|
||||
const bindings = await flowReadDbAll<{ bucket: string; key: string; remote: string }>(`
|
||||
SELECT b.bucket, (t->>'serverId') || '|' || (t->>'name') AS key, t->>'remoteAddress' AS remote
|
||||
const targets = new Set<string>()
|
||||
const hops = new Set<string>()
|
||||
for (const row of rows) {
|
||||
for (const raw of [row.inIface, row.outIface]) {
|
||||
targets.add(row.serverId + "|" + raw)
|
||||
targets.add(row.serverId + "|" + resolveIfaceName(row.serverId, raw).name)
|
||||
}
|
||||
if (row.nextHop && row.nextHop !== "0.0.0.0" && row.nextHop !== "::") hops.add(row.serverId + "|" + row.nextHop)
|
||||
}
|
||||
const bindings = await flowReadDbAll<{ bucket: string; key: string; remote: string; owner: string; iface: string; native: number | null; explicit: number | null; next_hops: Array<{ip: string; serverId: string}> }>(`
|
||||
SELECT b.bucket, (t->>'serverId') || '|' || (t->>'name') AS key, t->>'remoteAddress' AS remote,
|
||||
t->>'serverId' AS owner, t->>'name' AS iface, t->'nativeIndex' AS native, t->'ifIndex' AS explicit,
|
||||
(SELECT COALESCE(jsonb_agg(p), '[]'::jsonb) FROM jsonb_array_elements(CASE WHEN jsonb_typeof(t->'observedNextHops')='array'
|
||||
THEN t->'observedNextHops' ELSE '[]'::jsonb END) AS p
|
||||
WHERE p->>'serverId' ~ '^[1-9][0-9]*$' AND p->>'ip' <> '') AS next_hops
|
||||
FROM unnest(?::text[]) AS b(bucket)
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT payload_json FROM internet_path_snapshots
|
||||
@@ -462,15 +502,43 @@ async function readMapGrePeers(rows: { serverId: number; bucketAt: string; inIfa
|
||||
CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(payload_json->'greTunnels')='array'
|
||||
THEN payload_json->'greTunnels' ELSE '[]'::jsonb END) AS t
|
||||
WHERE payload_json->>'collectionComplete'='true' AND t->>'serverId' ~ '^[1-9][0-9]*$'
|
||||
AND ((t->>'serverId') || '|' || (t->>'name'))=ANY(?::text[])
|
||||
AND (EXISTS (SELECT 1 FROM unnest(ARRAY[t->>'name',t->>'nativeIndex',t->>'ifIndex']) AS idx
|
||||
WHERE (t->>'serverId') || '|' || idx = ANY(?::text[]))
|
||||
OR EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(t->'observedNextHops')='array'
|
||||
THEN t->'observedNextHops' ELSE '[]'::jsonb END) AS p WHERE (t->>'serverId') || '|' || (p->>'ip') = ANY(?::text[])))
|
||||
AND t->>'enabled'='true' AND t->>'name'<>'' AND t->>'remoteAddress'<>''
|
||||
`, [[...buckets], [...names]])
|
||||
`, [[...buckets], [...targets], [...hops]]).catch(error => {
|
||||
if (error instanceof FlowSqlSourceTooLarge) throw new FlowSourceWindowTooLarge()
|
||||
throw error
|
||||
})
|
||||
for (const row of bindings) {
|
||||
const interfaces = peers.get(row.bucket) ?? new Map<string, string>()
|
||||
interfaces.set(row.key, interfaces.has(row.key) ? "" : row.remote.trim().toLowerCase())
|
||||
peers.set(row.bucket, interfaces)
|
||||
const ownerKey = keyFor(row.bucket, row.owner)
|
||||
for (const [mode, index] of [[1, row.native], [2, row.explicit]] as const) {
|
||||
if (!index) continue
|
||||
const key = JSON.stringify([ownerKey, mode, index])
|
||||
names.set(key, names.has(key) ? "" : row.iface)
|
||||
}
|
||||
for (const peer of row.next_hops) {
|
||||
const key = JSON.stringify([row.bucket, row.owner, peer.ip])
|
||||
nextHops.set(key, nextHops.has(key) ? null : { serverId: Number(peer.serverId), iface: row.iface, native: row.native, explicit: row.explicit })
|
||||
}
|
||||
}
|
||||
return peers
|
||||
// Bind raw IPFIX indexes only to a directly observed next hop for this exporter and minute.
|
||||
for (const row of rows) {
|
||||
if (!/^[1-9][0-9]*$/.test(row.outIface)) continue
|
||||
const peer = nextHops.get(JSON.stringify([row.bucketAt, String(row.serverId), row.nextHop]))
|
||||
if (peer === undefined) continue
|
||||
const key = JSON.stringify([row.bucketAt, row.serverId, row.outIface])
|
||||
const prev = ingress.get(key)
|
||||
const mode = (peer?.native === Number(row.outIface) ? 1 : 0) | (peer?.explicit === Number(row.outIface) ? 2 : 0)
|
||||
const ownerKey = keyFor(row.bucketAt, row.serverId)
|
||||
namespace.set(ownerKey, (namespace.get(ownerKey) ?? 3) & mode)
|
||||
ingress.set(key, !peer || !mode || prev === null || prev && (prev.serverId !== peer.serverId || prev.iface !== peer.iface) ? null : peer)
|
||||
}
|
||||
return { peers, nextHops, ingress, ifaceName }
|
||||
}
|
||||
|
||||
async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number, scope?: ScopedFlowAnalyticsRead): Promise<FlowMapHopsDto> {
|
||||
@@ -496,43 +564,36 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const excludeOverlay = q.excludeOverlay !== false
|
||||
await authorize()
|
||||
const topo = await loadFlowTopology(scope?.serverIds, authorize)
|
||||
const allow = q.userId ? new Map<number, Set<string>>() : null
|
||||
if (allow) {
|
||||
for (const binding of topo.clientByIface.values()) if (binding.userId === q.userId) {
|
||||
const names = allow.get(binding.serverId) ?? new Set<string>()
|
||||
names.add(binding.interfaceName)
|
||||
allow.set(binding.serverId, names)
|
||||
}
|
||||
if (scope && !allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
|
||||
}
|
||||
const allow = q.userId ? flowClientInterfaces(topo, q.userId) : null
|
||||
if (scope && allow && !allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
|
||||
|
||||
const { peers, nextHops, ingress, ifaceName } = await readMapGrePeers(raw)
|
||||
|
||||
function rowClient(r: (typeof raw)[number]) {
|
||||
return resolveMapClient(topo, r.serverId, resolveIfaceName(r.serverId, r.inIface).name, resolveIfaceName(r.serverId, r.outIface).name)
|
||||
return resolveFlowClient(topo, r.serverId, ifaceName(r, r.inIface), ifaceName(r, r.outIface))
|
||||
}
|
||||
|
||||
const matches = (serverId: number, iface: string) =>
|
||||
flowRowMatchesFilter({ serverId, inIface: iface }, resolveIfaceName(serverId, iface).name, q, allow)
|
||||
const matches = (r: (typeof raw)[number], iface: string) =>
|
||||
flowRowMatchesFilter({ serverId: r.serverId, inIface: iface }, ifaceName(r, iface), q, allow)
|
||||
const selected = raw.filter(r => (!q.userId || rowClient(r)?.userId === q.userId) &&
|
||||
(matches(r.serverId, r.inIface) || matches(r.serverId, r.outIface)))
|
||||
(matches(r, r.inIface) || matches(r, r.outIface)))
|
||||
const { rows } = collapseGreEspRows(selected, r => {
|
||||
if (ifaceFilter) {
|
||||
const ingress = matches(r.serverId, r.inIface), egress = matches(r.serverId, r.outIface)
|
||||
const ingress = matches(r, r.inIface), egress = matches(r, r.outIface)
|
||||
return ingress === egress ? null : ingress ? "rx" : "tx"
|
||||
}
|
||||
return flowRateDirection(r.serverId, r, topo, catalog.byId.get(r.serverId)?.host)
|
||||
})
|
||||
const matched = []
|
||||
for (const r of rows) {
|
||||
const resolved = resolveIfaceName(r.serverId, r.inIface)
|
||||
const outResolved = resolveIfaceName(r.serverId, r.outIface)
|
||||
const plane = classifyFlowPlane({
|
||||
src: r.src,
|
||||
dst: r.dst,
|
||||
proto: r.proto,
|
||||
srcPort: r.srcPort,
|
||||
dstPort: r.dstPort,
|
||||
inIface: resolved.name,
|
||||
outIface: outResolved.name,
|
||||
inIface: ifaceName(r, r.inIface),
|
||||
outIface: ifaceName(r, r.outIface),
|
||||
}, topo.plane)
|
||||
if (!shouldKeepPlane(plane, { excludeMesh, excludeOverlay })) continue
|
||||
matched.push(r)
|
||||
@@ -550,7 +611,7 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
hostIds.set(key, previous === undefined || previous === node.id ? node.id : null)
|
||||
}
|
||||
await authorize()
|
||||
const peers = await readMapGrePeers(working)
|
||||
|
||||
const observed = new Map<(typeof working)[number], {
|
||||
endpoints: ReturnType<typeof resolveFlowEndpoints>; exitId?: number; viaIface?: string; reverse: boolean
|
||||
client: ReturnType<typeof rowClient>; nodeBytes: Map<number, number>
|
||||
@@ -560,10 +621,8 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
let totalBytes = 0
|
||||
|
||||
for (const r of working) {
|
||||
const inRes = resolveIfaceName(r.serverId, r.inIface)
|
||||
const outRes = resolveIfaceName(r.serverId, r.outIface)
|
||||
const inName = inRes.name
|
||||
const outName = outRes.name
|
||||
const inName = ifaceName(r, r.inIface)
|
||||
const outName = ifaceName(r, r.outIface)
|
||||
const fromId = String(r.serverId)
|
||||
const fromLabel = nameById.get(r.serverId) ?? fromId
|
||||
const wanSet = topo.wanIfaces.get(r.serverId)
|
||||
@@ -605,8 +664,13 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
|
||||
const bindings = peers.get(r.bucketAt)
|
||||
const outPeer = bindings?.get(fromId + "|" + outName)
|
||||
const outId = outPeer === undefined ? hostIds.get(r.nextHop) : hostIds.get(outPeer)
|
||||
const inId = hostIds.get(bindings?.get(fromId + "|" + inName) ?? "")
|
||||
const nextHop = nextHops.get(JSON.stringify([r.bucketAt, fromId, r.nextHop]))
|
||||
const verifiedOutput = nextHop && (r.outIface === nextHop.iface || ingress.get(JSON.stringify([r.bucketAt, r.serverId, r.outIface]))?.iface === nextHop.iface)
|
||||
const outId = nextHop === undefined ? (outPeer === undefined ? hostIds.get(r.nextHop) : hostIds.get(outPeer))
|
||||
: verifiedOutput && enIds.has(nextHop.serverId) ? nextHop.serverId : undefined
|
||||
const input = ingress.get(JSON.stringify([r.bucketAt, r.serverId, r.inIface]))
|
||||
const inId = input === undefined ? hostIds.get(bindings?.get(fromId + "|" + inName) ?? "")
|
||||
: input && enIds.has(input.serverId) ? input.serverId : undefined
|
||||
const peerId = outId && inId && outId !== inId ? null : outId ?? inId
|
||||
const endpoints = resolveFlowEndpoints({
|
||||
src: r.src,
|
||||
@@ -622,7 +686,7 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
}),
|
||||
})
|
||||
const reverse = !!endpoints.internetPeer && (endpoints.internetPeer === endpoints.packetSrc || endpoints.internetPeer === r.natSrc)
|
||||
const serviceSide = endpoints.internetPeer ? (reverse ? inId : outId) : peerId
|
||||
const serviceSide = endpoints.internetPeer ? (reverse ? inId : outId) : undefined
|
||||
const exitId = enIds.has(r.serverId) ? r.serverId : serviceSide ?? undefined
|
||||
const serviceIface = reverse ? inName : outName
|
||||
const otherIface = reverse ? outName : inName
|
||||
@@ -631,11 +695,11 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
: undefined
|
||||
const nodeBytes = new Map([[r.serverId, r.bytes]])
|
||||
if (exitId !== undefined) nodeBytes.set(exitId, r.bytes)
|
||||
observed.set(r, { endpoints, exitId, viaIface, reverse, client: resolveMapClient(topo, r.serverId, inName, outName), nodeBytes })
|
||||
observed.set(r, { endpoints, exitId, viaIface, reverse, client: resolveFlowClient(topo, r.serverId, inName, outName), nodeBytes })
|
||||
if (peerId && peerId !== r.serverId) {
|
||||
const toId = String(peerId)
|
||||
const dir = outId === peerId ? "fwd" : "rev"
|
||||
const greIface = dir === "fwd" && ifaceUsable(outName) ? outName : (ifaceUsable(inName) ? inName : undefined)
|
||||
const greIface = dir === "fwd" ? nextHop?.iface ?? (ifaceUsable(outName) ? outName : undefined) : input?.iface ?? (ifaceUsable(inName) ? inName : undefined)
|
||||
bump(hops, JSON.stringify(["gre", fromId, toId, greIface]), {
|
||||
fromId,
|
||||
fromLabel,
|
||||
@@ -707,9 +771,11 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const dst = ep.internetPeer
|
||||
const dstPort = ep.peerPort || r.dstPort
|
||||
const srcPort = ep.otherPort || r.srcPort
|
||||
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : ""
|
||||
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, proto: r.proto, dstPort, srcPort, fromBytes: new Map<string, FromAcc>() }
|
||||
const application = flowPortApplication(r.proto, dstPort) ?? flowPortApplication(r.proto, srcPort)
|
||||
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : JSON.stringify([r.proto, application])
|
||||
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, lastBucketAt: "", proto: r.proto, dstPort, srcPort, application, fromBytes: new Map<string, FromAcc>() }
|
||||
acc.bytes += bytes
|
||||
if (bytes > 0 && r.bucketAt > acc.lastBucketAt) acc.lastBucketAt = r.bucketAt
|
||||
bumpFrom(acc, String(r.serverId), exitId === undefined ? "" : String(exitId), viaIface, bytes, reverse, client)
|
||||
dstAcc.set(destKey, acc)
|
||||
}
|
||||
@@ -740,13 +806,14 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const ripe = dst ? resolveFlowIp(dst) : null
|
||||
const classified = dst
|
||||
? mapInternetBrand(dst, acc.proto, acc.dstPort, acc.srcPort, ripe)
|
||||
: { service: OTHER_SERVICE, category: OTHER_SERVICE }
|
||||
: OTHER_BRAND
|
||||
const svcId = mapServiceNodeId(classified.service)
|
||||
bumpDestTotal(svcTotals, svcId, classified.service, classified.category, acc.bytes)
|
||||
const detail = { transport: protoName(acc.proto), application: acc.application, basis: classified.basis }
|
||||
bumpDestTotal(svcTotals, svcId, classified.service, classified.category, acc.bytes, acc.lastBucketAt, detail)
|
||||
const country = countryDestFromRipe(ripe, dst)
|
||||
bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes)
|
||||
bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes, acc.lastBucketAt)
|
||||
const nestedId = mapCountryServiceNodeId(country.id, svcId)
|
||||
bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes)
|
||||
bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes, acc.lastBucketAt, detail)
|
||||
for (const from of acc.fromBytes.values()) {
|
||||
const { exporterId, enId: fromId } = from
|
||||
const enName = nodeName(fromId)
|
||||
|
||||
@@ -7,7 +7,7 @@ export const PLANE_LABEL: Record<FlowPlane, string> = {
|
||||
mgmt: "mgmt",
|
||||
}
|
||||
|
||||
const WG_PORTS = new Set([51820, 13232, 51821])
|
||||
const WG_PORTS = new Set([51820, 13231, 13232, 51821])
|
||||
const FLOW_PORTS = new Set([4739, 2055])
|
||||
|
||||
export function isRfc1918(ip: string): boolean {
|
||||
|
||||
@@ -165,6 +165,21 @@ try{
|
||||
assert.equal(series.rxSeries.reduce((sum,value)=>sum+value,0),50*8/60/1e6)
|
||||
assert.equal(series.txSeries.reduce((sum,value)=>sum+value,0),100*8/60/1e6)
|
||||
}
|
||||
const tuple = await client.callTool({name:'mm_netflow_analytics_report_get',arguments:{
|
||||
serverId:1, minutes:5, srcIp:'::ffff:198.18.1.1', dstIp:'8.8.8.8', srcPort:1, dstPort:443, protocol:6, limit:1,
|
||||
}})
|
||||
assert.ok(!tuple.isError,JSON.stringify(tuple))
|
||||
const filtered = (tuple.structuredContent as {result:{
|
||||
analytics:{bytes:number;admittedTotals?:unknown}; sourceWindow:unknown;
|
||||
pages:{conversationsList:{total:number;nextOffset:number|null}};
|
||||
historicalDetail:{rowLimitAppliedBeforeFilters:boolean;exactTupleTotalsVerified:boolean};
|
||||
}}).result
|
||||
assert.equal(filtered.analytics.bytes,100)
|
||||
assert.equal(filtered.analytics.admittedTotals,undefined)
|
||||
assert.deepEqual(filtered.pages.conversationsList,{total:1,nextOffset:null})
|
||||
assert.deepEqual(filtered.sourceWindow,{requestedMinutes:5,effectiveMinutes:5,incomplete:false})
|
||||
assert.equal(filtered.historicalDetail.rowLimitAppliedBeforeFilters,true)
|
||||
assert.equal(filtered.historicalDetail.exactTupleTotalsVerified,false)
|
||||
} finally {
|
||||
applyHeartbeatForTests(heartbeat)
|
||||
invalidateFlowAnalyticsCache()
|
||||
|
||||
@@ -42,6 +42,27 @@ export interface ServerCatalogEntry {
|
||||
|
||||
const CATALOG_TTL_MS = 5_000
|
||||
|
||||
// The latest completed RouterOS wave records all observed peers, including disabled peers.
|
||||
export const flowBindingAttributionSql = `
|
||||
NOT EXISTS (
|
||||
SELECT 1 FROM user_interface_bindings conflict
|
||||
WHERE conflict.server_id=b.server_id AND conflict.interface_name=b.interface_name AND conflict.id<>b.id
|
||||
) AND (b.peer_public_key='' OR (b.interface_type='wg' AND EXISTS (
|
||||
SELECT 1 FROM traffic_collection_state state
|
||||
JOIN servers source ON source.id=state.server_id AND source.enabled AND source.updated_at=state.server_updated_at
|
||||
JOIN traffic_samples peer ON peer.server_id=state.server_id AND peer.sampled_at=state.last_succeeded_at
|
||||
AND peer.interface_name=b.interface_name AND peer.peer_public_key=b.peer_public_key
|
||||
WHERE state.server_id=b.server_id AND state.status IN ('ok','pending')
|
||||
AND state.last_succeeded_at >= now() - make_interval(secs => 5 * greatest(5, COALESCE(
|
||||
(SELECT interval_sec FROM traffic_settings WHERE id=1), 30)))
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM traffic_samples sibling
|
||||
WHERE sibling.server_id=peer.server_id AND sibling.sampled_at=peer.sampled_at
|
||||
AND sibling.interface_name=peer.interface_name AND sibling.peer_public_key NOT IN ('',peer.peer_public_key)
|
||||
)
|
||||
)))
|
||||
`
|
||||
|
||||
let seeded: FlowTopology | null = null
|
||||
let topologyCache: { at: number; topo: FlowTopology } | null = null
|
||||
let serverCatalogCache: { at: number; list: ServerCatalogEntry[]; byId: Map<number, ServerCatalogEntry> } | null = null
|
||||
@@ -124,37 +145,30 @@ export async function loadFlowTopology(serverIds?: readonly number[], authorize:
|
||||
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=u.id AND NOT(hidden.server_id=ANY(?::bigint[]))) LIMIT 1001
|
||||
`, [serverIds, serverIds])
|
||||
await authorize()
|
||||
const binds = serverIds === undefined ? await flowReadDbAll<{userId:string;serverId:number;interfaceName:string;peerPublicKey?:string}>(
|
||||
'SELECT user_id AS "userId",server_id AS "serverId",interface_name AS "interfaceName",peer_public_key AS "peerPublicKey" FROM user_interface_bindings',
|
||||
) : await flowReadDbAll<{ userId: string; serverId: number; interfaceName: string; peerPublicKey?: string }>(`
|
||||
SELECT b.user_id AS "userId",b.server_id AS "serverId",b.interface_name AS "interfaceName" FROM user_interface_bindings b
|
||||
WHERE b.server_id=ANY(?::bigint[]) AND b.peer_public_key=''
|
||||
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=b.user_id AND NOT(hidden.server_id=ANY(?::bigint[])))
|
||||
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings conflict WHERE conflict.server_id=b.server_id
|
||||
AND conflict.interface_name=b.interface_name AND (conflict.peer_public_key<>'' OR conflict.user_id<>b.user_id))
|
||||
const binds = await flowReadDbAll<{ userId: string; serverId: number; interfaceName: string; attributable: boolean }>(`
|
||||
SELECT b.user_id AS "userId",b.server_id AS "serverId",b.interface_name AS "interfaceName",
|
||||
(${flowBindingAttributionSql}) AS attributable
|
||||
FROM user_interface_bindings b
|
||||
WHERE (?::bigint[] IS NULL OR (
|
||||
b.server_id=ANY(?::bigint[]) AND ${flowBindingAttributionSql}
|
||||
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=b.user_id AND NOT(hidden.server_id=ANY(?::bigint[])))
|
||||
))
|
||||
ORDER BY b.id
|
||||
LIMIT 1001
|
||||
`, [serverIds, serverIds])
|
||||
LIMIT ?
|
||||
`, [serverIds ?? null, serverIds ?? null, serverIds ?? null, serverIds === undefined ? null : 1001])
|
||||
if (serverIds !== undefined && (binds.length > 1000 || users.length > 1000)) throw new Error("Превышен предел топологии NetFlow")
|
||||
const loginById = new Map(users.map((u) => [u.id, u]))
|
||||
const clientIfaces = new Map<number, Set<string>>()
|
||||
const clientByIface = new Map<string, FlowClientBinding>()
|
||||
const ambiguousIfaces = new Set<string>()
|
||||
const allClientNames = new Set<string>()
|
||||
for (const b of binds) {
|
||||
const set = clientIfaces.get(b.serverId) ?? new Set<string>()
|
||||
set.add(b.interfaceName)
|
||||
clientIfaces.set(b.serverId, set)
|
||||
allClientNames.add(b.interfaceName)
|
||||
const key = ifaceKey(b.serverId, b.interfaceName)
|
||||
const previous = clientByIface.get(key)
|
||||
if (b.peerPublicKey || previous && previous.userId !== b.userId) {
|
||||
ambiguousIfaces.add(key)
|
||||
clientByIface.delete(key)
|
||||
}
|
||||
if (ambiguousIfaces.has(key)) continue
|
||||
if (!b.attributable) continue
|
||||
const user = loginById.get(b.userId)
|
||||
clientByIface.set(key, {
|
||||
clientByIface.set(ifaceKey(b.serverId, b.interfaceName), {
|
||||
userId: b.userId,
|
||||
login: user?.login || b.userId,
|
||||
name: user?.name || user?.login || b.userId,
|
||||
@@ -227,6 +241,24 @@ export function resolveClient(
|
||||
return topo.clientByIface.get(ifaceKey(serverId, inIfaceName)) ?? null
|
||||
}
|
||||
|
||||
/** null represents conflicting ownership; undefined means no attributable interface. */
|
||||
export function resolveFlowClient(topo: FlowTopology, serverId: number, inIface: string, outIface: string) {
|
||||
const ingress = resolveClient(topo, serverId, inIface)
|
||||
const egress = resolveClient(topo, serverId, outIface)
|
||||
if (ingress && egress && ingress.userId !== egress.userId) return null
|
||||
return ingress ?? egress ?? undefined
|
||||
}
|
||||
|
||||
export function flowClientInterfaces(topo: FlowTopology, userId: string) {
|
||||
const interfaces = new Map<number, Set<string>>()
|
||||
for (const binding of topo.clientByIface.values()) if (binding.userId === userId) {
|
||||
const names = interfaces.get(binding.serverId) ?? new Set<string>()
|
||||
names.add(binding.interfaceName)
|
||||
interfaces.set(binding.serverId, names)
|
||||
}
|
||||
return interfaces
|
||||
}
|
||||
|
||||
export function resolveEn(
|
||||
topo: FlowTopology,
|
||||
nextHop: string,
|
||||
|
||||
@@ -48,6 +48,17 @@ export async function verifyMcpFlowAnalytics(actor: AuthUser) {
|
||||
assert.equal((await read({offset:1,limit:1})).analytics.conversationsList.length,1)
|
||||
assert.equal((await read({interface:"analytics-in"})).analytics.bytes,100)
|
||||
assert.equal((await read({userId:users[0]})).analytics.bytes,100)
|
||||
const tuple = { srcIp: "::ffff:198.18.241.2", dstIp: "8.8.8.8", srcPort: 12345, dstPort: 443, protocol: 6 }
|
||||
result = await read({ ...tuple, limit: 1 })
|
||||
assert.equal(result.analytics.bytes, 200)
|
||||
assert.equal(result.analytics.admittedTotals, undefined)
|
||||
assert.equal(result.pages.conversationsList.total, 1)
|
||||
assert.equal(result.pages.conversationsList.nextOffset, null)
|
||||
assert.equal((await read({ ...tuple, offset: 1 })).analytics.conversationsList.length, 0)
|
||||
for (const mismatch of [{ srcIp: "198.18.241.9" }, { dstIp: "8.8.4.4" }, { srcPort: 12346 }, { dstPort: 0 }, { protocol: 17 }]) {
|
||||
assert.equal((await read({ ...tuple, ...mismatch })).analytics.bytes, 0)
|
||||
}
|
||||
for (const invalid of [{ srcIp: "198.18.241.0/24" }, { dstPort: 65536 }, { protocol: 256 }]) await assert.rejects(read(invalid))
|
||||
await put(110,"analytics-duplicate-in",50,"198.18.241.1")
|
||||
assert.equal((await read()).analytics.bytes,300)
|
||||
assert.equal((await read({dedup:false,excludeMesh:false,excludeOverlay:false})).analytics.bytes,350)
|
||||
|
||||
@@ -61,7 +61,18 @@ export async function verifyMcpTerminalDiagnostics(actor: AuthUser, app: Fastify
|
||||
assert.equal(fixture.requests.length, beforeDenied)
|
||||
await pool.query("UPDATE servers SET enabled=true WHERE id=$1", [sourceId])
|
||||
const interfaces = fixture.payloads["/interface"], logs = fixture.payloads["/log"], resource = fixture.payloads["/system/resource"]
|
||||
fixture.payloads["/interface"] = [{ ".id": "*1", name: "private-fixture", comment: `password=${password} token=NEVER_LOG_TOKEN`, type: "ether" }]
|
||||
fixture.payloads["/interface"] = [{ ".id": "*1", name: "private-fixture", comment: `password=${password} token=NEVER_LOG_TOKEN`, type: "ether", "rx-error": "7", "link-downs": "0" }]
|
||||
const typed = await invoke({ diagnostic: "interface_counters", interface: "private-fixture", limit: 1 }) as unknown as {
|
||||
interfaceCounters: { rows: { name: string; counters: { rxErrors: string; linkDowns: string } }[]; routerUptime: string; resetHistoryAvailable: boolean }
|
||||
}
|
||||
assert.equal(typed.interfaceCounters.rows[0].name, "private-fixture")
|
||||
assert.equal(typed.interfaceCounters.rows[0].counters.rxErrors, "7")
|
||||
assert.equal(typed.interfaceCounters.rows[0].counters.linkDowns, "0")
|
||||
assert.equal(typed.interfaceCounters.resetHistoryAvailable, false)
|
||||
assert.ok(typed.interfaceCounters.routerUptime)
|
||||
assert.ok(!JSON.stringify(typed).includes(password))
|
||||
await assert.rejects(invoke({ diagnostic: "interface_counters", count: 1 }))
|
||||
await assert.rejects(invoke({ diagnostic: "interfaces", interface: "private-fixture" }))
|
||||
const redacted = await invoke({ diagnostic: "interfaces" })
|
||||
assert.ok(!redacted.output.includes(password)); assert.ok(!redacted.output.includes("NEVER_LOG_TOKEN")); assert.ok(redacted.output.includes("[redacted]"))
|
||||
fixture.payloads["/log"] = [{ ".id": "*1", time: "0", topics: "system,info", message: `${password} password=NEVER_PRINT_LOG_PASSWORD token=NEVER_PRINT_LOG_TOKEN` }]
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing"
|
||||
import { pool } from "../db/index.js"
|
||||
import { PATH_PROOF_VERSION, pathProofTag } from "../modules/mcp/path-proof-purpose.js"
|
||||
import { fingerprint, privateFingerprinter } from "../modules/mcp/security.js"
|
||||
|
||||
export async function assertSignedResilienceHistory({ connectionId, foreignConnectionId, serverId, callReport }: {
|
||||
connectionId: string
|
||||
foreignConnectionId?: string
|
||||
serverId: number
|
||||
callReport: (input: Record<string, unknown>) => Promise<unknown>
|
||||
}) {
|
||||
const profileId = randomUUID()
|
||||
const profile = routeAiProfileSchema.parse({
|
||||
name: "Failover acceptance", serverId, community: "65000:911", family: "ipv4",
|
||||
candidates: ["primary", "backup"].map(id => ({
|
||||
id, wanInterface: id + "-wan", downstreamInterface: id + "-down", jumpHostId: serverId, exitNodeId: serverId,
|
||||
gateway: "192.0.2.1", gatewayRef: { resource: "ipv4_route", id: "*a" },
|
||||
controlProbe: { targetInterface: id + "-exit", expectedHops: [{ serverId, interface: id + "-exit" }] },
|
||||
})),
|
||||
})
|
||||
const profileHash = fingerprint(profile)
|
||||
const sign = await privateFingerprinter("route-control-path-context-v1")
|
||||
const base = Date.now() - 60000
|
||||
const time = (offset: number) => new Date(base + offset).toISOString()
|
||||
const window = { from: time(0), outageAt: time(10000), restoreAt: time(20000), to: time(30000) }
|
||||
const run = () => callReport({
|
||||
target: { kind: "route-ai", profileId },
|
||||
controlProbe: { primaryCandidateId: "primary", backupCandidateId: "backup" },
|
||||
window, targetFailoverMs: 1500, targetFailbackMs: 1500,
|
||||
})
|
||||
const fixtureIds: string[] = []
|
||||
async function store(candidateId: string, status: "passed" | "failed", started: number, ended: number, owner = connectionId, epoch = "1") {
|
||||
const id = randomUUID()
|
||||
const dependencyProof = "f".repeat(64)
|
||||
const payload = {
|
||||
id, connectionId: owner, profileHash, candidateId, status, dependencyProof,
|
||||
proofPurpose: "control-path", proofVersion: PATH_PROOF_VERSION,
|
||||
startedAt: time(started), observedAt: time(ended), sourceProofs: [{ serverId, proof: epoch.repeat(64) }],
|
||||
}
|
||||
const proof = sign(pathProofTag("control-path") + fingerprint({ dependencyProof, value: payload }))
|
||||
await pool.query(
|
||||
"INSERT INTO mcp_path_checks(id,connection_id,profile_hash,candidate_id,status,evidence,created_at) VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7)",
|
||||
[id, owner, profileHash, candidateId, status, JSON.stringify({ ...payload, proof }), payload.observedAt],
|
||||
)
|
||||
fixtureIds.push(id)
|
||||
return id
|
||||
}
|
||||
try {
|
||||
await pool.query(
|
||||
"INSERT INTO mcp_routing_profiles(id,connection_id,config,grant_expires_at) VALUES ($1,$2,$3::jsonb,$4)",
|
||||
[profileId, connectionId, JSON.stringify(profile), time(30000)],
|
||||
)
|
||||
const baseline = await store("primary", "passed", 8000, 9000)
|
||||
await store("primary", "failed", 10100, 10400)
|
||||
const firstGood = await store("backup", "passed", 10500, 11000)
|
||||
await store("primary", "passed", 20400, 20900)
|
||||
if (foreignConnectionId) await store("backup", "failed", 16000, 16500, foreignConnectionId)
|
||||
const passed = await run() as { status: string; baseline: { id: string }; failover: { firstGood: { id: string }; upperBoundMs: number }; serviceFailover: string; https: string; managementSsh: string }
|
||||
assert.equal(passed.status, "passed")
|
||||
assert.equal(passed.baseline.id, baseline)
|
||||
assert.equal(passed.failover.firstGood.id, firstGood)
|
||||
assert.equal(passed.failover.upperBoundMs, 1000)
|
||||
assert.equal(passed.serviceFailover, "inconclusive")
|
||||
assert.equal(passed.https, "inconclusive")
|
||||
assert.equal(passed.managementSsh, "inconclusive")
|
||||
|
||||
const moved = await store("backup", "passed", 13000, 13500, connectionId, "2")
|
||||
const changed = await run() as { status: string; reason: string }
|
||||
assert.equal(changed.status, "inconclusive")
|
||||
assert.equal(changed.reason, "SOURCE_IDENTITY_CHANGED")
|
||||
await pool.query("DELETE FROM mcp_path_checks WHERE id=$1", [moved])
|
||||
|
||||
await pool.query("UPDATE mcp_path_checks SET evidence=evidence-'proofPurpose' WHERE id=$1", [firstGood])
|
||||
const tampered = await run() as { status: string; reason: string }
|
||||
assert.equal(tampered.status, "inconclusive")
|
||||
assert.equal(tampered.reason, "INVALID_CONTROL_PATH_EVIDENCE")
|
||||
} finally {
|
||||
await pool.query("DELETE FROM mcp_path_checks WHERE id=ANY($1::uuid[])", [fixtureIds])
|
||||
await pool.query("DELETE FROM mcp_routing_profiles WHERE id=$1", [profileId])
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useEffect, useState, type ReactNode } from "react"
|
||||
import Link from "next/link"
|
||||
import { ChevronRightIcon, XIcon } from "lucide-react"
|
||||
import type { FlowAnalyticsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath, FlowMapUser } from "@mmapp/contracts/traffic-flow"
|
||||
import type { FlowAnalyticsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath, FlowMapUser, FlowServiceBasis } from "@mmapp/contracts/traffic-flow"
|
||||
import { flowMapHopsDtoSchema } from "@mmapp/contracts/traffic-flow"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Sparkline } from "@/components/sparkline"
|
||||
@@ -18,6 +18,15 @@ import { getFlowAnalytics, getFlowMapHops } from "@/shared/api/traffic-flow"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
import { matchesMapService } from "@/lib/flow-map-service-match"
|
||||
|
||||
const evidenceLabel: Record<FlowServiceBasis, string> = {
|
||||
catalog: "По каталогу",
|
||||
network: "По IP / ASN",
|
||||
port: "По протоколу / порту",
|
||||
heuristic: "Оценка по сети и порту",
|
||||
unknown: "Сервис не определён",
|
||||
}
|
||||
const percent = new Intl.NumberFormat("ru-RU", {style: "percent", maximumFractionDigits: 1})
|
||||
|
||||
export function InspectorMetrics({ rows }: { rows: [string, ReactNode, string?][] }) {
|
||||
return <dl className="grid grid-cols-2 gap-px overflow-hidden rounded-t-lg border-b bg-border">
|
||||
{rows.map(([name, value, title]) => <div key={name} title={title} className="flex min-w-0 flex-col gap-0.5 bg-card px-3.5 py-2.5">
|
||||
@@ -103,9 +112,11 @@ export function NodeHistory({ base, id, refresh, degraded }: { base: string | nu
|
||||
</>
|
||||
}
|
||||
|
||||
export function ServiceInspector({ service, paths, exits, exitName, country, base, refresh, windowLabel, flowAt, stale, activePath, onPath, onClose, filtered, onFilter, userId, ix, topology }: {
|
||||
export function ServiceInspector({ service, paths, exits, exitName, country, base, refresh, windowLabel, history, shareOfVisible, flowAt, stale, activePath, onPath, onClose, filtered, onFilter, userId, ix, topology }: {
|
||||
service: FlowMapService; paths: FlowMapServicePath[]; exits: FlowMapServiceEdge[]; exitName: (id: string) => string
|
||||
country?: string; base: string | null; refresh: number; windowLabel: string; flowAt: string | null; stale: boolean
|
||||
history?: {service?: FlowMapService; window: string}
|
||||
shareOfVisible: boolean
|
||||
activePath: FlowMapServicePath | null; onPath: (path: FlowMapServicePath) => void
|
||||
onClose: () => void; filtered: boolean; onFilter: () => void
|
||||
userId?: string; ix?: boolean; topology?: ReadonlySet<string>
|
||||
@@ -148,6 +159,13 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
|
||||
const remainder = Math.max(0, service.bytes - attributedBytes)
|
||||
const observed = service.bytes > 0 && !stale
|
||||
const currentVolume = base === null || scoped
|
||||
const average = history ? history.service : service
|
||||
const averageWindow = history?.window ?? windowLabel
|
||||
const volumeBytes = currentVolume ? average?.bytes : volume?.bytes
|
||||
const trafficTypes = service.trafficTypes ?? []
|
||||
const serviceEvidence = service.serviceEvidence ?? []
|
||||
const otherTypeBytes = Math.max(0, service.bytes - trafficTypes.reduce((sum, row) => sum + row.bytes, 0))
|
||||
const typeShare = (bytes: number) => percent.format(Math.min(1, bytes / service.bytes))
|
||||
const trafficQuery = new URLSearchParams({ view: "flows", service: service.label, serviceId: service.id, from: "map" })
|
||||
if (scopedUser) trafficQuery.set("user", scopedUser)
|
||||
else if (exporter) trafficQuery.set("server", exporter)
|
||||
@@ -168,13 +186,33 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
|
||||
</header>
|
||||
<div className="mx-0.5 mb-0.5 min-h-0 overflow-y-auto rounded-lg border">
|
||||
<InspectorMetrics rows={[
|
||||
["Скорость", formatNetflowRate({ bps: service.bps }), "Средняя скорость NetFlow за " + windowLabel],
|
||||
[country ? "Доля страны" : "Доля трафика", new Intl.NumberFormat("ru-RU", {style:"percent", maximumFractionDigits:1}).format(service.share)],
|
||||
["Объём · " + (currentVolume ? windowLabel : volume?.window ?? "24 ч"), <>{currentVolume ? formatBytes(service.bytes) : volume?.bytes == null ? "—" : formatBytes(volume.bytes)}{volume && <time dateTime={volume.at} title={new Date(volume.at).toLocaleString("ru-RU")} className="block text-[10px] font-normal text-muted-foreground">ответ {new Date(volume.at).toLocaleTimeString("ru-RU")}</time>}</>],
|
||||
["Средняя за " + averageWindow, average ? formatNetflowRate(average) : "—", "Скорость по сохранённым потокам IPFIX"],
|
||||
[shareOfVisible ? "Доля показанных сервисов" : country ? "Доля страны" : "Доля трафика", percent.format(service.share), "IPFIX · " + windowLabel],
|
||||
["Объём · " + (currentVolume ? averageWindow : volume?.window ?? "24 ч"), <>{volumeBytes == null ? "—" : formatBytes(volumeBytes)}{!currentVolume && volume && <time dateTime={volume.at} title={new Date(volume.at).toLocaleString("ru-RU")} className="block text-[10px] font-normal text-muted-foreground">ответ {new Date(volume.at).toLocaleTimeString("ru-RU")}</time>}</>],
|
||||
exitIds.length || !exporterIds.length
|
||||
? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined]
|
||||
: ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"],
|
||||
]} />
|
||||
{trafficTypes.length > 0 && service.bytes > 0 && <section className="space-y-2 border-b px-3.5 py-3 text-xs" aria-label="Состав трафика IPFIX">
|
||||
<h3 className="flex justify-between gap-2 font-medium"><span>Состав трафика</span><span className="font-normal text-muted-foreground">IPFIX · {windowLabel}</span></h3>
|
||||
<dl className="space-y-1">
|
||||
{trafficTypes.map(({transport, application, bytes}) => <div key={JSON.stringify([transport, application])} className="flex justify-between gap-2">
|
||||
<dt>{application ? `${application} · ${transport}` : transport}</dt>
|
||||
<dd className="shrink-0 font-mono tabular-nums">{typeShare(bytes)}</dd>
|
||||
</div>)}
|
||||
{otherTypeBytes > 0 && <div className="flex justify-between gap-2"><dt>Остальные типы</dt><dd className="font-mono tabular-nums">{typeShare(otherTypeBytes)}</dd></div>}
|
||||
</dl>
|
||||
{trafficTypes.some(row => row.application) && <p className="text-muted-foreground">Приложения определены по портам.</p>}
|
||||
{service.lastBucketAt && <p className="text-muted-foreground">Последняя минута с потоками <time dateTime={service.lastBucketAt} className="font-mono">{new Date(service.lastBucketAt).toLocaleTimeString("ru-RU", {hour: "2-digit", minute: "2-digit"})}</time></p>}
|
||||
{serviceEvidence.length ? <ul aria-label="Основание классификации" className="flex flex-wrap gap-1">
|
||||
{serviceEvidence.map(row => <li key={row.basis}>
|
||||
<Badge size="sm" variant={row.basis === "heuristic" ? "info-light" : "secondary"}
|
||||
title={row.basis === "heuristic" ? "Сервис предполагается по сети назначения и порту 443" : undefined}>
|
||||
{evidenceLabel[row.basis]}{serviceEvidence.length > 1 && ` · ${typeShare(row.bytes)}`}
|
||||
</Badge>
|
||||
</li>)}
|
||||
</ul> : null}
|
||||
</section>}
|
||||
<InspectorUsers users={serviceUsers(service, paths)} windowLabel={windowLabel} />
|
||||
<section className="space-y-2 border-b px-3.5 py-3"><h3 className="text-[11px] text-muted-foreground">Путь трафика</h3>
|
||||
{paths.map(p => {
|
||||
@@ -194,7 +232,20 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
|
||||
{!paths.length && !rates.length && !remainder && <p className="text-xs text-muted-foreground">Маршрут не определён</p>}
|
||||
</section>
|
||||
<section className="space-y-3 border-b px-3.5 py-3"><h3 className="flex items-center justify-between font-mono text-[11px] text-muted-foreground"><span>Крупные потоки · {recent?.data.sourceWindow?.effectiveMinutes ?? 5} мин</span><span title="Наблюдения экспортёров">{recent ? flows.length : "—"}</span></h3>
|
||||
{flows.map((f,i) => <div key={i} className="flex items-center gap-2 text-xs"><span aria-hidden className="size-1.5 shrink-0 rounded-full bg-[var(--status-online)]" /><div className="min-w-0 flex-1"><p className="font-medium [overflow-wrap:anywhere]">{f.src} → {f.dst}</p><p className="truncate text-[11px] text-muted-foreground" title={`Экспортёр: ${f.serverName || f.serverId}`}><span>{f.protoName}{f.dstPort ? "/" + f.dstPort : ""}</span> · {f.serverName || f.serverId}</p></div><span className="font-mono text-[11px] text-muted-foreground">{formatNetflowRate({bps:f.bps})}</span></div>)}
|
||||
{flows.map((f,i) => {
|
||||
const port = f.internetPeerPort || f.dstPort
|
||||
const transport = port ? `${f.protoName}/${port}` : f.protoName
|
||||
return <div key={i} className="flex items-center gap-2 text-xs">
|
||||
<span aria-hidden className="size-1.5 shrink-0 rounded-full bg-[var(--status-online)]" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="font-medium [overflow-wrap:anywhere]">{f.src} → {f.dst}</p>
|
||||
<p className="truncate text-[11px] text-muted-foreground" title={`Экспортёр: ${f.serverName || f.serverId}`}>
|
||||
{transport}{f.application && f.application !== transport && f.application !== f.protoName && ` · ${f.application}`} · {f.serverName || f.serverId}
|
||||
</p>
|
||||
</div>
|
||||
<span className="font-mono text-[11px] text-muted-foreground">{formatNetflowRate({bps:f.bps})}</span>
|
||||
</div>
|
||||
})}
|
||||
{!flows.length && <p className="text-xs text-muted-foreground">{recent ? "Сервис отсутствует в выборке крупных потоков" : "Нет подтверждённых записей"}</p>}
|
||||
{recent && <time dateTime={recent.at} title={new Date(recent.at).toLocaleString("ru-RU")} className="block font-mono text-[10px] text-muted-foreground">ответ {new Date(recent.at).toLocaleTimeString("ru-RU")}</time>}
|
||||
</section>
|
||||
|
||||
@@ -18,6 +18,7 @@ import { listAppUsers } from "@/shared/api/users"
|
||||
type AccessBinding = { id: string; node: string; name: string; kind: string; enabled?: boolean; peerScoped?: boolean; identity?: string }
|
||||
export type MapAccessUser = { id: string; name: string; login?: string; linux?: true; bindings: AccessBinding[] }
|
||||
type AccessRate = { rxNow: number | null; txNow: number | null }
|
||||
type UserTrafficSnapshot = { interfaces: Array<{ bindingId: string }>; observations?: { sampledAt?: string | null } }
|
||||
|
||||
const mapUsers = (users: typeof INIT_USERS): MapAccessUser[] => users.map(user => ({
|
||||
id: user.id, name: user.name || user.login, login: user.login,
|
||||
@@ -26,10 +27,10 @@ const mapUsers = (users: typeof INIT_USERS): MapAccessUser[] => users.map(user =
|
||||
}))
|
||||
const demoUsers = mapUsers(INIT_USERS)
|
||||
|
||||
export function useMapAccess(base: string | null, hasIx: boolean, refresh: number, userSelected: boolean) {
|
||||
export function useMapAccess(base: string | null, hasIx: boolean, refresh: number, userId: string | null) {
|
||||
const [directory, setDirectory] = useState<{ base: string; users: MapAccessUser[]; unavailable: boolean }>()
|
||||
const [linux, setLinux] = useState<{ base: string; users: MapAccessUser[]; unavailable: boolean }>()
|
||||
const [traffic, setTraffic] = useState<{ base: string; rates: Map<string, AccessRate> }>()
|
||||
const [traffic, setTraffic] = useState<{ base: string; userId: string; user?: UserTrafficSnapshot }>()
|
||||
useEffect(() => {
|
||||
if (base === null) return
|
||||
const controller = new AbortController()
|
||||
@@ -67,30 +68,35 @@ export function useMapAccess(base: string | null, hasIx: boolean, refresh: numbe
|
||||
return () => controller.abort()
|
||||
}, [base, hasIx, refresh])
|
||||
useEffect(() => {
|
||||
if (base === null || !userSelected) return
|
||||
if (base === null || !userId || userId.startsWith("ix:")) return
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
async function load() {
|
||||
const rates = new Map<string, AccessRate>()
|
||||
try {
|
||||
const payload = await requestJson<{ interfaces: Array<{ bindingId: string; status?: string }> }>(base!, "/api/traffic/bound-interfaces?range=5m", { signal: controller.signal })
|
||||
for (const row of payload.interfaces) {
|
||||
if (row.status === "offline") continue
|
||||
try { rates.set(row.bindingId, projectTrafficObservations(row)) } catch { /* Invalid measurements remain unknown. */ }
|
||||
}
|
||||
const { user } = await requestJson<{ user: UserTrafficSnapshot }>(base!, `/api/traffic/users/${encodeURIComponent(userId!)}?range=5m`, { signal: controller.signal })
|
||||
if (!controller.signal.aborted) setTraffic({ base: base!, userId: userId!, user })
|
||||
} catch {
|
||||
if (!controller.signal.aborted) setTraffic({ base: base!, userId: userId! })
|
||||
} finally {
|
||||
if (!controller.signal.aborted) {
|
||||
setTraffic({ base: base!, rates })
|
||||
timer = setTimeout(() => { void load().catch(() => {}) }, 15_000)
|
||||
timer = setTimeout(() => { void load() }, 15_000)
|
||||
}
|
||||
}
|
||||
}
|
||||
void load().catch(() => {})
|
||||
void load()
|
||||
return () => { controller.abort(); clearTimeout(timer) }
|
||||
}, [base, refresh, userSelected])
|
||||
}, [base, refresh, userId])
|
||||
|
||||
const users = base === null ? demoUsers : directory?.base === base ? directory.users : []
|
||||
const rates = new Map(base !== null && traffic?.base === base ? traffic.rates : undefined)
|
||||
const snapshot = traffic?.base === base && traffic.userId === userId ? traffic.user : undefined
|
||||
const rates = new Map<string, AccessRate>()
|
||||
let userRate: ReturnType<typeof projectTrafficObservations> | undefined
|
||||
if (snapshot) {
|
||||
try { userRate = projectTrafficObservations(snapshot) } catch { /* Invalid measurements remain unknown. */ }
|
||||
for (const row of snapshot.interfaces ?? []) {
|
||||
try { rates.set(row.bindingId, projectTrafficObservations(row)) } catch { /* Invalid measurements remain unknown. */ }
|
||||
}
|
||||
}
|
||||
const bindingsByInterface = new Map<string, { user: string; binding: AccessBinding }[]>()
|
||||
for (const user of users) for (const binding of user.bindings) {
|
||||
const key = JSON.stringify([binding.node, binding.name])
|
||||
@@ -109,6 +115,7 @@ export function useMapAccess(base: string | null, hasIx: boolean, refresh: numbe
|
||||
linuxPending: base !== null && hasIx && linux?.base !== base,
|
||||
linuxUnavailable: base !== null && hasIx && linux?.base === base && linux.unavailable,
|
||||
rates,
|
||||
userRate,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,8 +168,9 @@ export function MapUserPicker({ open, onOpenChange, users, pending, unavailable,
|
||||
</CommandDialog>
|
||||
}
|
||||
|
||||
export function MapUserDetails({ user, groups, paths, services, rates, windowLabel, onClose, onService, nodeName, trafficHref }: {
|
||||
export function MapUserDetails({ user, groups, paths, services, rates, userRate, windowLabel, onClose, onService, nodeName, trafficHref }: {
|
||||
user: MapAccessUser; groups: Map<string, AccessBinding[]>; paths: FlowMapServicePath[]; services: FlowMapService[]; rates?: Map<string, AccessRate>; windowLabel: string
|
||||
userRate?: ReturnType<typeof projectTrafficObservations>
|
||||
onClose: () => void; onService: (service: FlowMapService) => void; nodeName: (id: string) => string; trafficHref?: string
|
||||
}) {
|
||||
return <>
|
||||
@@ -172,6 +180,11 @@ export function MapUserDetails({ user, groups, paths, services, rates, windowLab
|
||||
<Button size="icon-xs" variant="ghost" onClick={onClose} aria-label="Закрыть детали пользователя"><XIcon /></Button>
|
||||
</header>
|
||||
<div className="flex flex-col gap-3 overflow-y-auto p-3">
|
||||
{!user.linux && <section className="grid gap-1 text-xs" aria-label="Трафик пользователя">
|
||||
<h3 className="text-muted-foreground">Счётчики подключений · RouterOS</h3>
|
||||
<p className="font-mono">RX {fmtRate(userRate?.rxNow ?? null)} · TX {fmtRate(userRate?.txNow ?? null)}</p>
|
||||
{userRate?.observations?.sampledAt && (userRate.rxNow !== null || userRate.txNow !== null) && <time className="text-muted-foreground" dateTime={userRate.observations.sampledAt}>{new Date(userRate.observations.sampledAt).toLocaleTimeString("ru-RU")}</time>}
|
||||
</section>}
|
||||
<section className="grid gap-2"><h3 className="text-xs text-muted-foreground">Подключения</h3>
|
||||
{[...groups].map(([node, bindings]) => {
|
||||
const rate = accessRate(bindings, rates)
|
||||
@@ -186,6 +199,7 @@ export function MapUserDetails({ user, groups, paths, services, rates, windowLab
|
||||
<section className="grid gap-1 border-t pt-3"><h3 className="text-xs text-muted-foreground">Сервисы · IPFIX · {windowLabel}</h3>
|
||||
{services.filter(service => paths.some(path => path.serviceId === service.id)).map(service => <Button key={service.id} variant="ghost" size="xs" className="w-full justify-between" onClick={() => onService(service)}>{service.label}<span className="font-mono">{formatNetflowRate(service)}</span></Button>)}
|
||||
{!paths.length && <p className="text-xs text-muted-foreground">Нет потоков с подтверждённой привязкой к пользователю.</p>}
|
||||
{!paths.length && user.bindings.some(binding => binding.peerScoped) && <p className="text-xs text-muted-foreground">Для привязки IPFIX к peer последний опрос RouterOS должен подтвердить, что на интерфейсе он один.</p>}
|
||||
</section>
|
||||
{trafficHref && <Link href={trafficHref} className={buttonVariants({size:"xs"})}>{user.linux ? "Открыть Linux-клиентов IX" : "Открыть в «Трафике»"}</Link>}
|
||||
</div>
|
||||
|
||||
@@ -80,7 +80,9 @@ export function FlowEntityCardView({
|
||||
{card.site}
|
||||
</span>
|
||||
</div>
|
||||
<TrafficMiniChart rx={card.rxSeries} tx={card.txSeries} />
|
||||
{card.rxNow === null && card.txNow === null
|
||||
? <p className="text-xs text-muted-foreground">Нет потоков с подтверждённой привязкой</p>
|
||||
: <TrafficMiniChart rx={card.rxSeries} tx={card.txSeries} />}
|
||||
<div className="flex justify-between mt-2 gap-2">
|
||||
<div className="flex items-center gap-1 text-xs">
|
||||
<ArrowDownIcon className="size-3 text-success" />
|
||||
@@ -360,7 +362,7 @@ export function FlowAnalyticsDetail({
|
||||
}) {
|
||||
const [slice, setSlice] = useState(initialService ? "sessions" : "applications")
|
||||
const [sessionFilter, setSessionFilter] = useState<SessionFilter | null>(initialService ? { kind: "map-service", label: initialService, country: initialCountry } : null)
|
||||
const rxNow = analytics ? analytics.bpsNow / 1_000_000 : (card?.rxNow ?? 0)
|
||||
const rxNow = analytics?.bytes ? analytics.bpsNow / 1_000_000 : (card?.rxNow ?? null)
|
||||
const bytes = analytics?.bytes ?? card?.bytes ?? 0
|
||||
const sessionRows = (analytics?.conversationsList ?? []).filter(row =>
|
||||
(!mapNodes || mapNodes.includes(row.enId || row.serverId)) && (!sessionFilter || talkerMatchesFilter(row, sessionFilter)))
|
||||
|
||||
+11
@@ -131,6 +131,17 @@ npm --prefix backend run mcp:stdio
|
||||
|
||||
Наличие инструмента не означает, что каждый сценарий раздела проверен на стенде. Статусы — в [манифесте](mcp-final-manifest.md).
|
||||
|
||||
### Разбор отказа и проверка резерва
|
||||
|
||||
1. Зафиксируйте источник, назначение, ожидаемый выход и максимальный допустимый перерыв. Проверьте доступ через `mm_capabilities_get` и давность наблюдений через `mm_telemetry_health_get`. Обрыв экспорта NetFlow оставляет пробел в наблюдениях.
|
||||
2. В `mm_incident_timeline_get` выберите окно до 24 часов, включающее последний успешный запрос перед отказом и первые успешные запросы после него. С правом чтения аудита параметр `includeManagerEvents: true` добавляет записи запросов текущего MCP-подключения, привязанных к одному выбранному серверу. Сопоставьте события с текущей конфигурацией.
|
||||
3. Через `mm_route_lookup_get` проверьте адрес в нужной таблице. Выбор таблицы клиентским пакетом дополнительно зависит от входного интерфейса, VRF, правил и маркировки. Проверьте обратный путь и маршрут управления. Если IP доступен, а имя не разрешается, посмотрите `mm_dns_state_get`.
|
||||
4. Для профиля Route AI или подключения IX изучите общие узлы двух путей в `mm_resilience_topology_get`. Разные туннели через один WAN или один exit разделяют эту точку отказа. Физическую независимость провайдера, трассы и питания подтверждает оператор. `mm_resilience_design_preview` помогает выбрать последующие проверки и профильные планы.
|
||||
5. До испытания включите независимые проверки нового клиентского соединения HTTPS, сохранения существующего соединения и доступа SSH к VPS. Задайте интервалы измерений согласно целевому времени восстановления. Испытайте отказ и возврат по отдельности.
|
||||
6. Сопоставьте `mm_failover_report_get` с результатами клиентских проверок. Для цели 10 секунд два измерения с интервалом 30 секунд могут дать только неопределённый результат. Смена маршрута и успешный ping от роутера подтверждают лишь соответствующие наблюдения.
|
||||
|
||||
Если метод отсутствует в клиенте, сравните реестр установленной версии в «Система» → «MCP» с операциями, выданными подключению, правами владельца и режимом подключения. После изменения допуска обновите каталог MCP-клиента. Видимый глобальный метод может вернуть `GLOBAL_DENIED` при запрете глобальной области.
|
||||
|
||||
## Route AI
|
||||
|
||||
Постоянный контроллер переключает маршруты по профилю через обычные планы MCP. Настройка, требования к допуску и причины остановки — в [инструкции](mcp-enable-guide.md#постоянный-контроллер-route-ai).
|
||||
|
||||
@@ -3,6 +3,7 @@ import assert from "node:assert/strict"
|
||||
import {buildServerResourceMap,greTunnelProbe} from "./network-map-layout"
|
||||
import {mergeGreMetricsWithSpeedProbe} from "./map-gre-speed-probe"
|
||||
import {servers,greTunnels} from "./data"
|
||||
import {scopeMapDestinations} from "./network-map-scope"
|
||||
test("live resources preserve zero, partial poll and unknowns without fake history",()=>{
|
||||
const base={...servers[0],cpuLoad:undefined,totalMemory:undefined,freeMemory:undefined,uptime:undefined,polledAt:undefined}
|
||||
const unknown=buildServerResourceMap([base])[base.id]
|
||||
@@ -19,3 +20,17 @@ test("live GRE does not hash metrics and probe values retain zero and fractions"
|
||||
const merged=mergeGreMetricsWithSpeedProbe({id:"p",srcServerId:"1",dstServerId:"2",lastPingRttMs:0,lastTxAvgMbps:0,lastRxAvgMbps:0.125},fallback)
|
||||
assert.deepEqual(merged,{pingMs:0,dlMbps:0,ulMbps:0.125,hasSpeedMonitor:true})
|
||||
})
|
||||
|
||||
test("a filtered topology does not inherit a service's full-network traffic composition", () => {
|
||||
const service = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 100, bps: 10, share: 0.4,
|
||||
trafficTypes: [{transport: "UDP", application: "DNS", bytes: 100}], lastBucketAt: "2026-11-26T18:30:00.000Z"}
|
||||
const edges = ["1", "2"].map(fromId => ({fromId, toId: service.id, bytes: 50, bps: 5, bpsFwd: 5, bpsRev: 0}))
|
||||
const partial = scopeMapDestinations([service], edges, [], id => id === "1").services[0]
|
||||
const complete = scopeMapDestinations([service], edges, [], () => true).services[0]
|
||||
assert.equal(partial?.trafficTypes, undefined)
|
||||
assert.equal(partial?.lastBucketAt, undefined)
|
||||
assert.deepEqual(complete?.trafficTypes, service.trafficTypes)
|
||||
assert.equal(complete?.lastBucketAt, service.lastBucketAt)
|
||||
assert.equal(complete.share, 0.4)
|
||||
assert.equal(partial.share, 1)
|
||||
})
|
||||
@@ -1,27 +1,30 @@
|
||||
import type { MapBox } from "./network-map-layout"
|
||||
import type { MapBox, MapLink } from "./network-map-layout"
|
||||
|
||||
type Point = { x: number; y: number }
|
||||
|
||||
/** Routes IPFIX around cards. A missing route leaves the observation available in service details. */
|
||||
export function mapObservationRoute(start: Point, end: Point, boxes: readonly MapBox[], usedTracks: readonly number[]) {
|
||||
if (end.x - start.x < 44) return null
|
||||
const padding = 8
|
||||
const obstacles = boxes.filter(box => box.x + box.w > start.x && box.x < end.x)
|
||||
const first = Math.min(start.x + 20, ...obstacles.map(box => box.x - padding))
|
||||
const last = Math.max(end.x - 20, ...obstacles.map(box => box.x + box.w + padding))
|
||||
if (first <= start.x || last >= end.x || last - first < 34) return null
|
||||
|
||||
const middle = (start.y + end.y) / 2
|
||||
const candidates = [middle, start.y, end.y, ...obstacles.flatMap(box => [box.y - 16, box.y + box.h + 16])]
|
||||
const legal = candidates.flatMap(y => [y, y - 14, y + 14, y - 28, y + 28])
|
||||
.filter(y => obstacles.every(box => y < box.y - padding || y > box.y + box.h + padding))
|
||||
/** Find a clear horizontal track between the sides facing the connection after dragging. */
|
||||
export function mapObservationRoute(link: MapLink, boxes: readonly MapBox[], usedTracks: readonly number[]) {
|
||||
const { x1, y1, x2, y2, cx } = link
|
||||
const stub = (x: number) => x + Math.sign(cx - x) * Math.min(20, Math.abs(cx - x))
|
||||
const first = stub(x1), last = stub(x2)
|
||||
const middle = (y1 + y2) / 2
|
||||
const obstacles = boxes.filter(box => box.x < Math.max(x1, first, last, x2) && box.x + box.w > Math.min(x1, first, last, x2))
|
||||
const crosses = (a: number, b: number, low: number, size: number) => Math.min(a, b) < low + size && Math.max(a, b) > low
|
||||
const horizontal = (a: number, b: number, y: number) =>
|
||||
obstacles.some(box => y > box.y && y < box.y + box.h && crosses(a, b, box.x, box.w))
|
||||
const vertical = (x: number, a: number, b: number) =>
|
||||
obstacles.some(box => x > box.x && x < box.x + box.w && crosses(a, b, box.y, box.h))
|
||||
if (horizontal(x1, first, y1) || horizontal(last, x2, y2)) return null
|
||||
const candidates = [middle, y1, y2, ...obstacles.flatMap(box => [box.y - 16, box.y + box.h + 16]),
|
||||
...usedTracks.flatMap(y => [y - 18, y + 18])]
|
||||
const legal = candidates.filter(y => !vertical(first, y1, y) && !horizontal(first, last, y) && !vertical(last, y, y2))
|
||||
.sort((a, b) => Math.abs(a - middle) - Math.abs(b - middle) || a - b)
|
||||
const y = legal.find(candidate => usedTracks.every(track => Math.abs(candidate - track) >= 18))
|
||||
const markerX = (first + last) / 2
|
||||
const markerFits = (y: number) => !boxes.some(box => crosses(markerX - 17, markerX + 17, box.x, box.w) && crosses(y - 7, y + 7, box.y, box.h))
|
||||
const y = legal.find(candidate => markerFits(candidate) && usedTracks.every(track => Math.abs(candidate - track) >= 18)) ?? legal[0]
|
||||
if (y === undefined) return null
|
||||
|
||||
return {
|
||||
d: `M ${start.x} ${start.y} H ${first} V ${y} H ${last} V ${end.y} H ${end.x}`,
|
||||
marker: { x: (first + last) / 2, y },
|
||||
d: `M ${x1} ${y1} H ${first} V ${y} H ${last} V ${y2} H ${x2}`,
|
||||
marker: markerFits(y) ? { x: markerX, y } : undefined,
|
||||
track: y,
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ test("network map refuses partial GRE and foreign failure/probe contexts",()=>{
|
||||
assert.throws(()=>validateNetworkMapSnapshot([server],{tunnels:[]},{probes:[probe]}),/неизвестному/)
|
||||
})
|
||||
|
||||
import {networkMapFlowSchema,validateNetworkMapDns} from "./network-map-response"
|
||||
import {networkMapFlowSchema,recentMapFlowSchema,validateNetworkMapDns} from "./network-map-response"
|
||||
test("map Flow envelope retains zeros and refuses missing metadata and contradictory totals",()=>{
|
||||
const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false}
|
||||
assert.equal(networkMapFlowSchema.parse(empty).totalBytes,0)
|
||||
@@ -46,9 +46,14 @@ test("map Flow envelope retains zeros and refuses missing metadata and contradic
|
||||
assert.throws(()=>networkMapFlowSchema.parse({...shorter,rangeMinutes:1,windowSec:60}))
|
||||
assert.throws(()=>networkMapFlowSchema.parse({...shorter,windowSec:300}))
|
||||
const recent={...empty,rangeMinutes:1,windowSec:90.125,includesCurrentMinute:true}
|
||||
assert.equal(networkMapFlowSchema.parse(recent).windowSec,90.125)
|
||||
assert.throws(()=>networkMapFlowSchema.parse(recent))
|
||||
assert.throws(()=>networkMapFlowSchema.parse({...recent,windowSec:120}))
|
||||
assert.throws(()=>networkMapFlowSchema.parse({...recent,includesCurrentMinute:undefined}))
|
||||
assert.equal(recentMapFlowSchema.parse(recent).windowSec,90.125)
|
||||
for (const windowSec of [60,119.999]) assert.equal(recentMapFlowSchema.parse({...recent,windowSec}).windowSec,windowSec)
|
||||
for (const invalid of [empty,{...recent,windowSec:59},{...recent,windowSec:120},{...recent,includesCurrentMinute:undefined},{...recent,sourceWindow:shorter.sourceWindow}]) {
|
||||
assert.throws(()=>recentMapFlowSchema.parse(invalid))
|
||||
}
|
||||
})
|
||||
test("map DNS matches exactly requested names and accepts explicit unresolved null",()=>{
|
||||
assert.deepEqual(validateNetworkMapDns({results:{"router.example":null}},["router.example"]),{"router.example":null})
|
||||
|
||||
@@ -27,14 +27,18 @@ export function validateNetworkMapSnapshot(servers:unknown,gre:unknown,probes:un
|
||||
|
||||
import {flowMapHopsDtoSchema} from "@mmapp/contracts/traffic-flow"
|
||||
import {isIpv4String} from "./gre-endpoint-resolve"
|
||||
export const networkMapFlowSchema = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true, includesCurrentMinute: true, nodeUsers: true }).refine(data =>
|
||||
(data.includesCurrentMinute
|
||||
? !data.sourceWindow && data.rangeMinutes === 1 && data.windowSec >= 60 && data.windowSec < 120
|
||||
: data.windowSec === data.rangeMinutes * 60 && (data.sourceWindow
|
||||
? data.sourceWindow.requestedMinutes === 5 && data.sourceWindow.effectiveMinutes === data.rangeMinutes
|
||||
: data.rangeMinutes === 5)) &&
|
||||
const mapFlowResponse = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true, includesCurrentMinute: true, nodeUsers: true }).refine(data =>
|
||||
data.namedBytes <= data.totalBytes && data.unclassifiedBytes <= data.totalBytes
|
||||
)
|
||||
export const networkMapFlowSchema = mapFlowResponse.refine(data =>
|
||||
!data.includesCurrentMinute && data.windowSec === data.rangeMinutes * 60 && (data.sourceWindow
|
||||
? data.sourceWindow.requestedMinutes === 5 && data.sourceWindow.effectiveMinutes === data.rangeMinutes
|
||||
: data.rangeMinutes === 5)
|
||||
)
|
||||
export const recentMapFlowSchema = mapFlowResponse.refine(data =>
|
||||
data.includesCurrentMinute === true && data.rangeMinutes === 1 && data.windowSec >= 60 && data.windowSec < 120 &&
|
||||
(!data.sourceWindow || data.sourceWindow.requestedMinutes === 1 && data.sourceWindow.effectiveMinutes === 1)
|
||||
)
|
||||
export function validateNetworkMapDns(raw:unknown,hosts:string[]){
|
||||
const data=z.object({results:z.record(z.string(),z.string().refine(isIpv4String).nullable())}).parse(raw)
|
||||
const requested=new Set(hosts.map(host=>host.toLowerCase()))
|
||||
|
||||
@@ -53,10 +53,16 @@ export function scopeMapDestinations(
|
||||
bytes += unassigned
|
||||
totals.set(service.id, total)
|
||||
}
|
||||
const shareOfVisible = Boolean(userId) || services.some(service => (totals.get(service.id)?.bytes ?? 0) !== service.bytes)
|
||||
return {
|
||||
shareOfVisible,
|
||||
services: services.flatMap(service => {
|
||||
const total = totals.get(service.id)
|
||||
return total ? [{ ...service, ...total, share: bytes ? total.bytes / bytes : 0 }] : []
|
||||
if (!total) return []
|
||||
const { trafficTypes, serviceEvidence, lastBucketAt, ...destination } = service
|
||||
const visibleShare = bytes ? total.bytes / bytes : 0
|
||||
return [{ ...destination, ...total, share: shareOfVisible ? visibleShare : service.share,
|
||||
...(total.bytes === service.bytes ? { trafficTypes, serviceEvidence, lastBucketAt } : {}) }]
|
||||
}).sort((a, b) => b.bytes - a.bytes || a.label.localeCompare(b.label)),
|
||||
edges: visibleEdges,
|
||||
paths: visiblePaths,
|
||||
|
||||
@@ -215,8 +215,8 @@ export const flowEntityCardSchema = z.object({
|
||||
site: z.string(),
|
||||
country: z.string(),
|
||||
status: z.enum(["online", "offline", "degraded"]),
|
||||
rxNow: z.number(),
|
||||
txNow: z.number(),
|
||||
rxNow: z.number().nullable(),
|
||||
txNow: z.number().nullable(),
|
||||
sessions: z.number().int().nonnegative(),
|
||||
rxSeries: z.array(z.number()),
|
||||
txSeries: z.array(z.number()),
|
||||
@@ -366,6 +366,9 @@ export const flowMapHopDtoSchema = z.object({
|
||||
bpsRev: z.number().nonnegative(),
|
||||
})
|
||||
|
||||
export const flowServiceBasisSchema = z.enum(["catalog", "network", "heuristic", "port", "unknown"])
|
||||
export type FlowServiceBasis = z.infer<typeof flowServiceBasisSchema>
|
||||
|
||||
export const flowMapServiceDtoSchema = z.object({
|
||||
id: z.string(),
|
||||
label: z.string(),
|
||||
@@ -373,6 +376,16 @@ export const flowMapServiceDtoSchema = z.object({
|
||||
bytes: z.number().nonnegative(),
|
||||
bps: z.number().nonnegative(),
|
||||
share: z.number().min(0).max(1),
|
||||
lastBucketAt: z.string().datetime().optional(),
|
||||
trafficTypes: z.array(z.object({
|
||||
transport: z.string(),
|
||||
application: z.string().nullable(),
|
||||
bytes: z.number().positive(),
|
||||
})).max(5).optional(),
|
||||
serviceEvidence: z.array(z.object({
|
||||
basis: flowServiceBasisSchema,
|
||||
bytes: z.number().positive(),
|
||||
})).max(flowServiceBasisSchema.options.length).optional(),
|
||||
})
|
||||
|
||||
export const flowMapServiceEdgeDtoSchema = z.object({
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
export function emptyMapFlow(requestUrl: string | URL) {
|
||||
const range = new URL(requestUrl).searchParams.get("range")
|
||||
const recent = range === "1m"
|
||||
const rangeMinutes = recent ? 1 : range === "24h" ? 1440 : 5
|
||||
return {
|
||||
hops: [], live: false, rangeMinutes, windowSec: recent ? 90 : rangeMinutes * 60, ...(recent ? {includesCurrentMinute: true} : {}),
|
||||
totalBytes: 0, namedBytes: 0, unclassifiedBytes: 0, asnLoaded: false, countryLoaded: false,
|
||||
services: [], serviceEdges: [], servicePaths: [], countries: [], countryEdges: [], countryPaths: [], countryServiceGroups: [],
|
||||
mapServiceMinSharePct: 5, dedupApplied: false, excludeMeshApplied: false, excludeOverlayApplied: false,
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { openSettings } from "./fixtures/open-settings"
|
||||
import {test,expect} from "@playwright/test"
|
||||
const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false}
|
||||
import { emptyMapFlow } from "./fixtures/map-flow"
|
||||
const headers={"access-control-allow-origin":"*","access-control-allow-methods":"GET,POST,OPTIONS","access-control-allow-headers":"Content-Type,Authorization"}
|
||||
const wan={id:"w",name:"WAN",iface:"ether1",isp:"ISP",ip:"router.example",maxDl:100,maxUl:100}
|
||||
const row=(name:string)=>({id:1,name,host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online",wanUplinks:[wan]})
|
||||
@@ -9,30 +9,30 @@ for(const change of ["backend","mode"])for(const part of ["snapshot","flow","dns
|
||||
await page.route("**/health",r=>r.fulfill({headers,json:{ok:true}}))
|
||||
await page.route("**/api/**",r=>{
|
||||
const u=new URL(r.request().url()),p=u.pathname;if(u.port==="8101")newReads++
|
||||
return r.fulfill({headers,json:p==="/api/auth/config"?{required:false}:p==="/api/servers"?[row(u.port==="8101"?"Новая карта":"Прежняя карта")]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/network/resolve-hosts"?{results:{"router.example":"192.0.2.2"}}:{}})
|
||||
return r.fulfill({headers,json:p==="/api/auth/config"?{required:false}:p==="/api/servers"?[row(u.port==="8101"?"Новая карта":"Прежняя карта")]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(u):p==="/api/network/resolve-hosts"?{results:{"router.example":"192.0.2.2"}}:{}})
|
||||
})
|
||||
await page.goto("/settings");await page.getByRole("link",{name:/^Карта сети/}).click()
|
||||
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Прежняя карта",{exact:true})).toBeVisible()
|
||||
await expect(page.getByTitle(/NetFlow · 5 мин · ответ/)).toBeVisible()
|
||||
await expect(page.getByRole("button",{name:"Устройство Прежняя карта",exact:true})).toBeVisible({timeout:20_000})
|
||||
await expect(page.getByText(/IPFIX · среднее за 1 мин 30 с/)).toBeVisible()
|
||||
const path=part==="snapshot"?"/api/servers":part==="flow"?"/api/traffic/flow/map-hops":"/api/network/resolve-hosts"
|
||||
await page.route("**/api/**",async r=>{
|
||||
const u=new URL(r.request().url());if(u.port!=="8000"||u.pathname!==path||started)return r.fallback()
|
||||
started=true;await gate
|
||||
try{await r.fulfill(fails?{headers,status:503,json:{error:"Старая ошибка карты"}}:{headers,json:part==="snapshot"?[row("Поздняя карта")]:part==="flow"?{...empty,services:[{id:"svc:late",label:"Поздний сервис",category:"Web",bytes:1,bps:1,share:1}]}:{results:{"router.example":null}}})}catch{}finally{completed=true}
|
||||
try{await r.fulfill(fails?{headers,status:503,json:{error:"Старая ошибка карты"}}:{headers,json:part==="snapshot"?[row("Поздняя карта")]:part==="flow"?{...emptyMapFlow(u),services:[{id:"svc:late",label:"Поздний сервис",category:"Web",bytes:1,bps:1,share:1}]}:{results:{"router.example":null}}})}catch{}finally{completed=true}
|
||||
})
|
||||
await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
||||
await expect.poll(()=>started).toBe(true);await openSettings(page)
|
||||
if(change==="backend"){const input=page.getByPlaceholder("http://localhost:8000");await input.fill("http://localhost:8101");await input.press("Enter")}
|
||||
else await page.getByRole("button",{name:"Моковые",exact:true}).click()
|
||||
await page.getByRole("link",{name:/^Карта сети/}).click()
|
||||
if(change==="backend"){await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Новая карта",{exact:true})).toBeVisible();await expect(page.getByTitle(/NetFlow · 5 мин · ответ/)).toBeVisible()}
|
||||
if(change==="backend"){await expect(page.getByRole("button",{name:"Устройство Новая карта",exact:true})).toBeVisible();await expect(page.getByText(/IPFIX · среднее за 1 мин 30 с/)).toBeVisible()}
|
||||
else await expect(page.getByText("Демонстрационные данные",{exact:true})).toBeVisible()
|
||||
const before=newReads;release();await expect.poll(()=>completed).toBe(true)
|
||||
await page.evaluate(()=>new Promise<void>(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve()))))
|
||||
await expect(page.getByText("Старая ошибка карты",{exact:false})).toHaveCount(0)
|
||||
await expect(page.getByText("Поздняя карта",{exact:false})).toHaveCount(0)
|
||||
await expect(page.getByRole("button",{name:"Устройство Поздняя карта",exact:true})).toHaveCount(0)
|
||||
await expect(page.getByText("Поздний сервис",{exact:false})).toHaveCount(0)
|
||||
await expect(page.getByRole("alert").filter({hasText:"DNS не разрешён"})).toHaveCount(0)
|
||||
if(change==="backend")await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Новая карта",{exact:true})).toBeVisible()
|
||||
if(change==="backend")await expect(page.getByRole("button",{name:"Устройство Новая карта",exact:true})).toBeVisible()
|
||||
expect(newReads).toBe(before)
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
import {test,expect} from "@playwright/test"
|
||||
const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false}
|
||||
import { emptyMapFlow } from "./fixtures/map-flow"
|
||||
const wan={id:"w",name:"WAN",iface:"ether1",isp:"ISP",ip:"192.0.2.1",maxDl:100,maxUl:100}
|
||||
const home={id:1,name:"Домашний",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online",latency:2,wanUplinks:[wan]}
|
||||
const jh={id:2,name:"Jump",host:"192.0.2.2",type:"jump-host",country:"RU",enabled:true,status:"online",latency:3}
|
||||
@@ -7,7 +7,7 @@ const tunnel={id:"t1",serverId:"1",name:"gre-home",localAddress:"192.0.2.1",remo
|
||||
test.beforeEach(async({page})=>{await page.route("**/health",r=>r.fulfill({json:{ok:true}}))})
|
||||
test("Карта: открытые детали обновляются вместе со снимком",async({page})=>{
|
||||
let changed=false
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...jh,name:changed?"Новый Jump":"Jump",status:changed?null:"online",cpuLoad:changed?0:20}]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...jh,name:changed?"Новый Jump":"Jump",status:changed?null:"online",cpuLoad:changed?0:20}]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.goto("/network-map");await page.getByRole("button",{name:"Устройство Jump",exact:true}).click()
|
||||
const metrics=page.getByText("CPU · RAM",{exact:true}).locator("..")
|
||||
await expect(metrics).toContainText("20% · —")
|
||||
@@ -18,7 +18,7 @@ test("Карта: открытые детали обновляются вмес
|
||||
await expect(page.getByText("Jump",{exact:true})).toHaveCount(0);await expect(page.getByText("Новый Jump",{exact:true}).last()).toBeVisible()
|
||||
})
|
||||
test("Карта: модель WAN не утверждает активный маршрут и RTT линии",async({page})=>{
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.goto("/network-map")
|
||||
const legend = page.getByRole("button", {name:"Легенда",exact:true})
|
||||
await legend.click()
|
||||
@@ -31,7 +31,7 @@ test("Карта: модель WAN не утверждает активный м
|
||||
})
|
||||
test("Карта: выбранный GRE обновляется и неизвестный IPsec не означает Plain",async({page})=>{
|
||||
let changed=false
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[{...tunnel,name:changed?"gre-new":"gre-home",status:changed?"down":"up"}],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[{...tunnel,name:changed?"gre-new":"gre-home",status:changed?"down":"up"}],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.goto("/network-map")
|
||||
await page.locator("g").filter({has:page.locator("title",{hasText:"RTT неизвестен."})}).last().click()
|
||||
await expect(page.getByText("gre-home",{exact:true}).last()).toBeVisible();await expect(page.getByText("Ping неизвестен",{exact:true})).toBeVisible()
|
||||
@@ -42,7 +42,7 @@ test("Карта: выбранный GRE обновляется и неизве
|
||||
|
||||
test("Карта: GRE сохраняет частичное измерение, ноль Ping и дату пробы",async({page})=>{
|
||||
const probe={id:"measured-probe",srcServerId:"1",dstServerId:"2",srcInterface:"gre-home",dstInterface:"",enabled:true,lastPingRttMs:0,lastPingLossPct:0,lastTxAvgMbps:0.125,lastRxAvgMbps:null,lastPingAt:"2020-01-01T00:00:00Z"}
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[probe]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[probe]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.goto("/network-map")
|
||||
await page.locator("g").filter({has:page.locator("title",{hasText:"Проба measured-probe"})}).last().click()
|
||||
await expect(page.getByText("0 мс",{exact:true}).last()).toBeVisible()
|
||||
@@ -68,7 +68,7 @@ test("Карточки Exit, JumpHost и сервиса показывают и
|
||||
const data = endpoint === "/api/servers" ? [exit, jump]
|
||||
: endpoint === "/api/filters/gre-tunnels" ? { tunnels: [], failures: [] }
|
||||
: endpoint === "/api/uptime/speed-probes" ? {probes: []}
|
||||
: endpoint === "/api/traffic/flow/map-hops" ? {...empty,rangeMinutes:daily?1440:5,windowSec:daily?86400:300,totalBytes:daily?4100000000:3103448,namedBytes:daily?4100000000:service.bytes,services:[{...service,bytes:daily?4100000000:service.bytes}],servicePaths:[path],serviceEdges:[edge],countries:[country],countryServiceGroups:[{countryId:country.id,services:[dns],paths:[{...path,serviceId:dns.id,bytes:100000,bps:100000*8/300}],edges:[]}]}
|
||||
: endpoint === "/api/traffic/flow/map-hops" ? {...emptyMapFlow(url),totalBytes:daily?4100000000:3103448,namedBytes:daily?4100000000:service.bytes,services:[{...service,bytes:daily?4100000000:service.bytes}],servicePaths:[path],serviceEdges:[edge],countries:[country],countryServiceGroups:[{countryId:country.id,services:[dns],paths:[{...path,serviceId:dns.id,bytes:100000,bps:100000*8/300}],edges:[]}]}
|
||||
: endpoint === "/api/traffic/flow/analytics" ? {bpsNow:8000,bytes:1000,packets:1,conversations:3,uniqueSrc:1,uniqueDst:3,topProto:"TCP",rxSeries:[],txSeries:[],applications:[],protocols:[],sources:[],destinations:[],interfaces:[],conversationsList:[record,...["unknown","US"].map(dstCountry=>({...record,service:"Прочее",category:"DNS",dstCountry,dst:dstCountry==="US"?"192.0.2.53":"198.51.100.53",dstPort:53}))],ifaces:[],live:true}
|
||||
: endpoint === "/api/traffic/servers/3" ? {server:{...sample,id:"3"}}
|
||||
: endpoint === "/api/traffic/servers/2" ? {server:{...sample,id:"2",observations:{...sample.observations,currentState:"error",error:"RouterOS API 401 на /interface",lastAttemptAt:"2026-11-25T09:31:08Z"}}}
|
||||
@@ -85,7 +85,7 @@ test("Карточки Exit, JumpHost и сервиса показывают и
|
||||
await card.getByRole("button",{name:/YouTube/}).click()
|
||||
await expect(card.getByText("Объём · 24 ч",{exact:true}).locator("..")).toContainText("4.10 ГБ")
|
||||
await expect(card.getByText("10.20.4.18 → 142.250.74.14",{exact:true})).toBeVisible()
|
||||
await expect(card.getByText("TCP/443",{exact:true})).toBeVisible()
|
||||
await expect(card.getByText("TCP/443 · " + exit.name,{exact:true})).toBeVisible()
|
||||
await card.screenshot({path:info.outputPath("service.png")})
|
||||
await card.getByRole("button",{name:"Фильтр по сервису"}).click()
|
||||
await expect(page.getByText(/фильтр: YouTube/)).toBeVisible()
|
||||
@@ -105,11 +105,11 @@ test("Карточки Exit, JumpHost и сервиса показывают и
|
||||
|
||||
test("Обновление NetFlow отображается внутри кнопки", async ({page}) => {
|
||||
let release!: () => void
|
||||
const wait = new Promise<void>(resolve => { release = resolve })
|
||||
let wait = new Promise<void>(resolve => { release = resolve })
|
||||
await page.route("**/api/**", async route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
if (path === "/api/traffic/flow/map-hops") await wait
|
||||
return route.fulfill({json:path === "/api/traffic/flow/map-hops" ? empty : path === "/api/servers" ? [jh] : path === "/api/filters/gre-tunnels" ? {tunnels:[],failures:[]} : path === "/api/uptime/speed-probes" ? {probes:[]} : path === "/api/auth/config" ? {required:false} : {}})
|
||||
const url = new URL(route.request().url()), path = url.pathname
|
||||
if (path === "/api/traffic/flow/map-hops" && url.searchParams.get("range") === "1m") await wait
|
||||
return route.fulfill({json:path === "/api/traffic/flow/map-hops" ? emptyMapFlow(route.request().url()) : path === "/api/servers" ? [jh] : path === "/api/filters/gre-tunnels" ? {tunnels:[],failures:[]} : path === "/api/uptime/speed-probes" ? {probes:[]} : path === "/api/auth/config" ? {required:false} : {}})
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
const refresh = page.getByRole("button",{name:"Обновить",exact:true})
|
||||
@@ -118,4 +118,10 @@ test("Обновление NetFlow отображается внутри кно
|
||||
release()
|
||||
await expect(refresh).toBeEnabled()
|
||||
await expect(refresh.locator("[data-slot=spinner]")).toHaveCount(0)
|
||||
wait = new Promise<void>(resolve => { release = resolve })
|
||||
await Promise.all([page.waitForResponse("**/api/traffic/flow/map-hops?range=5m"), refresh.click()])
|
||||
await expect(refresh).toBeDisabled()
|
||||
await expect(refresh.locator("[data-slot=spinner]")).toBeVisible()
|
||||
release()
|
||||
await expect(refresh).toBeEnabled()
|
||||
})
|
||||
@@ -1,18 +1,22 @@
|
||||
import {test,expect} from "@playwright/test"
|
||||
import { installOpenLiveStream } from "./live-stream-fixture"
|
||||
import { observedTrafficFixturePayload } from "./traffic-observation-fixture"
|
||||
const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false}
|
||||
import { emptyMapFlow } from "./fixtures/map-flow"
|
||||
const flowPath="/api/traffic/flow/map-hops"
|
||||
test.beforeEach(async({page})=>{await page.route("**/health",r=>r.fulfill({json:{ok:true}}))})
|
||||
const server={id:1,name:"Router",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online"}
|
||||
|
||||
test("Карта и трафик сохраняют пользователя и сервис, IX остаётся отдельным", async ({page}) => {
|
||||
const clientId = "alice"
|
||||
function mapUser(clientId: string, name: string) {
|
||||
const timestamps = { createdAt: "2026-11-26T12:00:00Z", updatedAt: "2026-11-26T12:00:00Z" }
|
||||
const binding = { ...timestamps, userId: clientId, id: "a1", serverId: 1,
|
||||
serverName: "Вход", serverSite: "MSK", serverCountry: "RU", interfaceName: "gre-alice", interfaceType: "gre", comment: "" }
|
||||
const user = { ...timestamps, id: clientId, name: "Алиса", login: "alice", email: "alice@example.test", role: "viewer", active: true,
|
||||
avatar: "A", lastSeen: null, sections: [], servers: [], bindings: [binding, {...binding, id: "a2", interfaceName: "gre-alice-2"}] }
|
||||
serverName: "Вход", serverSite: "MSK", serverCountry: "RU", interfaceName: "gre-" + clientId, interfaceType: "gre", comment: "" }
|
||||
return { ...timestamps, id: clientId, name, login: clientId, email: clientId + "@example.test", role: "viewer", active: true,
|
||||
avatar: name[0], lastSeen: null, sections: [], servers: [], bindings: [binding, {...binding, id: "a2", interfaceName: binding.interfaceName + "-2"}] }
|
||||
}
|
||||
|
||||
test("Карта и трафик сохраняют пользователя и сервис, IX остаётся отдельным", async ({page}) => {
|
||||
const clientId = "alice"
|
||||
const user = mapUser(clientId, "Алиса")
|
||||
const counters = ["a1", "a2"].map(bindingId => ({bindingId, status: "online", rxNow: 4, txNow: 6, rxPeak: 4, txPeak: 6, rxTotal: 0, txTotal: 0, rxSeries: [4], txSeries: [6]}))
|
||||
const dns = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 300000, bps: 8000, share: 1}
|
||||
const path = {clientId, clientName: "Алиса", viaId: "1", viaName: "Вход", enId: "", enName: "", serviceId: dns.id, bytes: dns.bytes, bps: dns.bps}
|
||||
@@ -27,10 +31,11 @@ test("Карта и трафик сохраняют пользователя и
|
||||
"/api/filters/gre-tunnels": {tunnels: [], failures: []}, "/api/uptime/speed-probes": {probes: []},
|
||||
"/api/ix/topology": {links: []}, "/api/ix/segments": {items: [{id: "segment", appliedRevision: 1}]},
|
||||
"/api/ix/segments/segment/linux": {items: [{serverId: 9, interfaceName: "wg-linux", kind: "wireguard", name: "Linux VPS", enabled: true}]},
|
||||
"/api/users": {users: [user]}, "/api/traffic/bound-interfaces": observedTrafficFixturePayload({interfaces: counters}),
|
||||
"/api/users": {users: [user]},
|
||||
[`/api/traffic/users/${clientId}`]: observedTrafficFixturePayload({user: {...counters[0], rxNow: 8, txNow: 12, interfaces: counters}}),
|
||||
"/api/traffic/flow/exporters": {exporters: []}, "/api/traffic/flow/clients": {clients: [clientCard]},
|
||||
"/api/traffic/flows": {exportersOnline: 0, bytesPerMin: 0, uniqueSrc: 0, uniqueDst: 0, topProto: "TCP", talkers: [], listenerBound: true},
|
||||
[flowPath]: {...empty, totalBytes: dns.bytes, namedBytes: dns.bytes, services: [dns], servicePaths: [path],
|
||||
[flowPath]: {...emptyMapFlow(url), totalBytes: dns.bytes, namedBytes: dns.bytes, services: [dns], servicePaths: [path],
|
||||
serviceEdges: [{fromId: "1", toId: dns.id, observedOnly: true, bytes: dns.bytes, bps: dns.bps, bpsFwd: 0, bpsRev: dns.bps}]},
|
||||
}
|
||||
return route.fulfill({json: replies[url.pathname] ?? {}})
|
||||
@@ -46,10 +51,12 @@ test("Карта и трафик сохраняют пользователя и
|
||||
await page.getByRole("combobox", {name: "Поиск пользователей"}).fill("Вход")
|
||||
await expect(page.getByRole("option", {name:/Алиса.*Вход/})).toBeVisible()
|
||||
await page.getByRole("option", {name: /Алиса/}).click()
|
||||
await expect.poll(() => requests.some(request => request === `${flowPath}?range=1m&userId=${clientId}`)).toBe(true)
|
||||
await expect.poll(() => requests.includes(`${flowPath}?range=1m&userId=${clientId}`)).toBe(true)
|
||||
await expect(panel.getByRole("heading", {name: "Алиса", exact: true})).toBeVisible()
|
||||
await expect(panel.getByText(/gre-alice · gre, gre-alice-2/)).toBeVisible()
|
||||
await expect(panel.getByText(/RX 8.*TX 12.*2\/2/)).toBeVisible()
|
||||
await expect(panel.getByRole("region", {name: "Трафик пользователя"})).toContainText("RX 8.00 Мбит/с · TX 12.0 Мбит/с")
|
||||
await expect(map.getByRole("button", {name: "Пользователь Алиса"}).locator('rect[fill="var(--card)"]')).toHaveAttribute("stroke", "var(--border)")
|
||||
await panel.getByRole("button", {name: /DNS/}).click()
|
||||
await panel.getByRole("link", {name: "Открыть в «Трафике»"}).click()
|
||||
await expect(page).toHaveURL(/\/traffic\?.*user=alice/)
|
||||
@@ -65,26 +72,104 @@ test("Карта и трафик сохраняют пользователя и
|
||||
await expect(panel.getByText("Нет потоков с подтверждённой привязкой к пользователю.")).toBeVisible()
|
||||
})
|
||||
|
||||
test("Карта показывает скорость и долю за короткое окно и отдельные пять минут для выбранного пользователя", async ({page}) => {
|
||||
const users = [mapUser("alice", "Алиса"), mapUser("boris", "Борис")]
|
||||
const ratesByScope: Record<string, {recent: number; average: number}> = {
|
||||
alice: {recent: 32_000, average: 8_000},
|
||||
boris: {recent: 48_000, average: 12_000},
|
||||
network: {recent: 72_000, average: 16_000},
|
||||
}
|
||||
let borisRead: "failed" | "populated" | "empty" = "failed"
|
||||
await page.route("**/api/**", route => {
|
||||
const url = new URL(route.request().url())
|
||||
if (url.pathname === flowPath) {
|
||||
const userId = url.searchParams.get("userId")
|
||||
const recent = url.searchParams.get("range") === "1m"
|
||||
if (recent && userId === "boris" && borisRead !== "populated") {
|
||||
return route.fulfill(borisRead === "empty" ? {json: {...emptyMapFlow(url), live: true}}
|
||||
: {status: 503, json: {error: "Не удалось получить минуту Бориса"}})
|
||||
}
|
||||
const snapshot = emptyMapFlow(url)
|
||||
const ratesForUser = ratesByScope[userId ?? "network"]
|
||||
const dnsBps = recent ? ratesForUser.recent : ratesForUser.average
|
||||
const totalBps = recent ? 100_000 : 40_000
|
||||
const rates = {DNS: dnsBps, HTTPS: totalBps - dnsBps}
|
||||
const services = Object.entries(rates).map(([label, bps]) => ({
|
||||
id: "svc:" + label.toLowerCase(), label, category: label, bps, bytes: bps * snapshot.windowSec / 8, share: bps / totalBps,
|
||||
}))
|
||||
const totalBytes = totalBps * snapshot.windowSec / 8
|
||||
return route.fulfill({json: {...snapshot, live: true, totalBytes, namedBytes: totalBytes, services,
|
||||
serviceEdges: services.map(s => ({fromId: "1", toId: s.id, observedOnly: true, bytes: s.bytes, bps: s.bps, bpsFwd: 0, bpsRev: s.bps})),
|
||||
servicePaths: services.map(s => ({clientId: userId ?? "boris", clientName: userId === "alice" ? "Алиса" : "Борис", viaId: "1", viaName: "Вход", enId: "", enName: "", serviceId: s.id, bytes: s.bytes, bps: s.bps})),
|
||||
}})
|
||||
}
|
||||
const responses: Record<string, unknown> = {
|
||||
"/api/auth/config": {required: false}, "/api/servers": [{...server, name: "Вход", type: "jump-host"}], "/api/users": {users},
|
||||
"/api/filters/gre-tunnels": {tunnels: [], failures: []}, "/api/uptime/speed-probes": {probes: []},
|
||||
}
|
||||
return route.fulfill({json: responses[url.pathname] ?? {}})
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
const map = page.getByRole("group", {name: "Интерактивная карта сети"})
|
||||
const dns = map.getByRole("button", {name: "Сервис DNS", exact: true})
|
||||
const card = page.getByRole("complementary", {name: "Детали объекта карты"})
|
||||
await expect(dns).toContainText("72 Кбит/с")
|
||||
await expect(dns).toContainText("72%")
|
||||
await dns.press("Enter")
|
||||
await expect(card.getByText("Средняя за 5 мин", {exact: true}).locator("..")).toContainText("16 Кбит/с")
|
||||
await expect(card.getByText("Объём · 24 ч", {exact: true}).locator("..")).toContainText("172.8 МБ")
|
||||
await page.getByRole("button", {name: "Пользователи", exact: true}).click()
|
||||
await page.getByRole("option", {name: /Алиса/}).click()
|
||||
await expect(dns).toContainText("32 Кбит/с")
|
||||
await expect(dns).toContainText("32%")
|
||||
await dns.press("Enter")
|
||||
await expect(card.getByText("Средняя за 5 мин", {exact: true}).locator("..")).toContainText("8 Кбит/с")
|
||||
await expect(card.getByText("Объём · 5 мин", {exact: true}).locator("..")).toContainText("300.0 КБ")
|
||||
const borisResponse = (status: number) => page.waitForResponse(response => {
|
||||
const url = new URL(response.url())
|
||||
return url.pathname === flowPath && url.searchParams.get("range") === "1m" && url.searchParams.get("userId") === "boris" && response.status() === status
|
||||
})
|
||||
await page.getByRole("button", {name: "Алиса", exact: true}).click()
|
||||
await Promise.all([borisResponse(503), page.getByRole("option", {name: /Борис/}).click()])
|
||||
await expect(card.getByRole("heading", {name: "Борис", exact: true})).toBeVisible()
|
||||
await expect(page.getByRole("status").filter({hasText: "Скорости сервисов пока недоступны"})).toBeVisible()
|
||||
await expect(dns).toHaveCount(0)
|
||||
const refresh = page.getByRole("button", {name: "Обновить", exact: true})
|
||||
borisRead = "populated"
|
||||
await Promise.all([borisResponse(200), refresh.click()])
|
||||
await expect(dns).toContainText("48 Кбит/с")
|
||||
borisRead = "empty"
|
||||
await Promise.all([borisResponse(200), refresh.click()])
|
||||
await expect(dns).toHaveCount(0)
|
||||
await page.getByRole("button", {name: "Вся схема пользователей"}).click()
|
||||
await expect(dns).toContainText("72 Кбит/с")
|
||||
})
|
||||
|
||||
test("Карта не приписывает весь YouTube единственному выходу ARN", async ({page}) => {
|
||||
const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1}
|
||||
const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1,
|
||||
trafficTypes: [{transport: "UDP", application: "QUIC", bytes: 900000}],
|
||||
serviceEvidence: [{basis: "heuristic", bytes: 900000}], lastBucketAt: "2026-11-26T18:30:00.000Z"}
|
||||
const edge = {fromId: "1", toId: service.id, bytes: 300000, bps: 8000, bpsFwd: 2000, bpsRev: 6000}
|
||||
let known = false
|
||||
await page.route("**/api/**", route => {
|
||||
const url = new URL(route.request().url())
|
||||
const path = url.pathname
|
||||
if (path === flowPath && url.searchParams.get("range") === "24h") {
|
||||
return route.fulfill({ json: { ...empty, rangeMinutes: 1440, windowSec: 86400, totalBytes: service.bytes, namedBytes: service.bytes, services: [service] } })
|
||||
return route.fulfill({ json: { ...emptyMapFlow(url), totalBytes: service.bytes, namedBytes: service.bytes, services: [service] } })
|
||||
}
|
||||
if (path === flowPath) expect(url.searchParams.get("range")).toBe("1m")
|
||||
const responses: Record<string, unknown> = {
|
||||
"/api/auth/config": {required: false}, "/api/servers": [{...server, type: "exit-node", name: "ARN"}],
|
||||
"/api/filters/gre-tunnels": {tunnels: [], failures: []}, "/api/uptime/speed-probes": {probes: []},
|
||||
[flowPath]: {...empty, totalBytes: service.bytes, namedBytes: service.bytes, services: [service], serviceEdges: known ? [edge] : []},
|
||||
[flowPath]: {...emptyMapFlow(url), totalBytes: service.bytes, namedBytes: service.bytes, services: [service], serviceEdges: known ? [edge] : []},
|
||||
}
|
||||
return route.fulfill({json: responses[path] ?? {}})
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
await page.getByRole("button", {name: "Сервис YouTube", exact: true}).press("Enter")
|
||||
const composition = page.getByRole("region", {name: "Состав трафика IPFIX"})
|
||||
await expect(composition.getByText("Оценка по сети и порту")).toBeVisible()
|
||||
await expect(composition.locator("time")).toHaveAttribute("datetime", service.lastBucketAt)
|
||||
await expect(page.getByText("IPFIX · среднее за 1 мин 30 с")).toBeVisible()
|
||||
const unknown = page.getByText("Выход не определён", {exact: true}).locator("..")
|
||||
const badges = page.locator("[data-map-ribbon] > title")
|
||||
await expect(unknown).toContainText("24 Кбит/с")
|
||||
@@ -99,7 +184,9 @@ test("Карта не приписывает весь YouTube единствен
|
||||
|
||||
test("Карта: DNS виден от экспортёра, пользователи разбиты в обеих карточках", async ({page}) => {
|
||||
const router = {...server, name: "MSK", type: "jump-host"}
|
||||
const dns = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 300000, bps: 8000, share: 1}
|
||||
const dns = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 300000, bps: 8000, share: 1,
|
||||
trafficTypes: [{transport: "UDP", application: "DNS", bytes: 225000}, {transport: "TCP", application: "DNS over TLS", bytes: 75000}],
|
||||
serviceEvidence: [{basis: "port", bytes: 300000}]}
|
||||
const users = [
|
||||
{clientId: "u1", clientName: "Алиса", bytes: 225000, bps: 6000},
|
||||
{clientId: "—", clientName: "—", bytes: 75000, bps: 2000},
|
||||
@@ -111,16 +198,30 @@ test("Карта: DNS виден от экспортёра, пользовате
|
||||
return route.fulfill({json: path === "/api/auth/config" ? {required: false}
|
||||
: path === "/api/servers" ? [router] : path === "/api/filters/gre-tunnels" ? {tunnels: [], failures: []}
|
||||
: path === "/api/uptime/speed-probes" ? {probes: []} : path === flowPath ? {
|
||||
...empty,
|
||||
...(url.searchParams.get("range") === "24h" ? {rangeMinutes: 1440, windowSec: 86400} : {}),
|
||||
...emptyMapFlow(url),
|
||||
totalBytes: dns.bytes, services: [dns], servicePaths, nodeUsers: {"1": users},
|
||||
serviceEdges: [{fromId: "1", toId: dns.id, observedOnly: true, bytes: dns.bytes, bps: dns.bps, bpsFwd: 0, bpsRev: dns.bps}],
|
||||
} : {}})
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
await expect(page.locator("[data-map-ribbon][data-observation] > title")).toContainText("MSK → DNS")
|
||||
await page.getByRole("button", {name: "Слои", exact: true}).click()
|
||||
const auxiliary = page.getByRole("button", {name: "Вспомогательные серые линии"})
|
||||
await auxiliary.click()
|
||||
await expect(auxiliary).toHaveAttribute("aria-pressed", "false")
|
||||
await expect(page.locator("[data-map-ribbon][data-observation]")).toHaveCount(0)
|
||||
await auxiliary.press("Escape")
|
||||
await expect(page.getByRole("button", {name: "Сервис DNS", exact: true})).toBeVisible()
|
||||
await page.getByRole("button", {name: "Слои", exact: true}).click()
|
||||
await auxiliary.click()
|
||||
await expect(page.locator("[data-map-ribbon][data-observation]")).toHaveCount(1)
|
||||
await auxiliary.press("Escape")
|
||||
await page.getByRole("button", {name: "Сервис DNS", exact: true}).press("Enter")
|
||||
const panel = page.getByRole("complementary", {name: "Детали объекта карты"})
|
||||
const composition = panel.getByRole("region", {name: "Состав трафика IPFIX"})
|
||||
await expect(composition.getByText("DNS · UDP").locator("..")).toContainText("75")
|
||||
await expect(composition.getByText("DNS over TLS · TCP").locator("..")).toContainText("25")
|
||||
await expect(composition.getByText("По протоколу / порту")).toBeVisible()
|
||||
const breakdown = panel.getByRole("region", {name: "Трафик по пользователям"})
|
||||
await expect(breakdown.getByText("Алиса", {exact: true}).locator("..")).toContainText("6 Кбит/с")
|
||||
await expect(breakdown.getByText("Без привязки к пользователю")).toBeVisible()
|
||||
@@ -169,7 +270,7 @@ for (const reverse of [false, true]) test(`Карта: малый NetFlow и т
|
||||
"/api/servers": [exit, jump],
|
||||
"/api/filters/gre-tunnels": { tunnels: reverse ? [tunnel, opposite] : [tunnel], failures: [] },
|
||||
"/api/uptime/speed-probes": { probes: [] },
|
||||
[flowPath]: { ...empty, live: true, hops: [estimate, { ...exact, fromId: String(peer.id), fromLabel: peer.name }],
|
||||
[flowPath]: { ...emptyMapFlow(url), live: true, hops: [estimate, { ...exact, fromId: String(peer.id), fromLabel: peer.name }],
|
||||
interfaceTraffic: [{ serverId: observer.serverId, iface: observer.name, rxBytes: exactNetflow && !reverse ? 525 : 0,
|
||||
txBytes: exactNetflow && reverse ? 525 : 0, rxPackets: exactNetflow && !reverse ? 3 : 0, txPackets: exactNetflow && reverse ? 3 : 0,
|
||||
inWindow: exactNetflow, lastBucketAt: "2026-11-23T07:00:00Z" }] },
|
||||
@@ -229,7 +330,7 @@ test("Карта: параллельные GRE с разными владель
|
||||
}
|
||||
return route.fulfill({ json: path === "/api/servers" ? [{ ...server, type: "jump-host" }, peer]
|
||||
: path === "/api/filters/gre-tunnels" ? { tunnels, failures: [] }
|
||||
: path === flowPath ? { ...empty, live: true, interfaceTraffic }
|
||||
: path === flowPath ? { ...emptyMapFlow(url), live: true, interfaceTraffic }
|
||||
: path === "/api/uptime/speed-probes" ? { probes: [] } : path === "/api/auth/config" ? { required: false } : {} })
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
@@ -245,7 +346,7 @@ test("Карта: параллельные GRE с разными владель
|
||||
test("Карта: карточка узла показывает отдельно фактические RX/TX RouterOS", async ({ page }) => {
|
||||
await page.route("**/api/**", route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
return route.fulfill({ json: path === "/api/servers" ? [server] : path === flowPath ? empty
|
||||
return route.fulfill({ json: path === "/api/servers" ? [server] : path === flowPath ? emptyMapFlow(route.request().url())
|
||||
: path === "/api/filters/gre-tunnels" ? { tunnels: [], failures: [] }
|
||||
: path === "/api/uptime/speed-probes" ? { probes: [] } : path === "/api/auth/config" ? { required: false } : {} })
|
||||
})
|
||||
@@ -263,25 +364,29 @@ test("Карта: карточка узла показывает отдельн
|
||||
|
||||
for(const malformed of [false,true])test("Карта: NetFlow отказ и повтор "+malformed,async({page})=>{
|
||||
let failing=true
|
||||
const recovered=malformed?{...empty,rangeMinutes:2,windowSec:120,sourceWindow:{requestedMinutes:5,effectiveMinutes:2}}:empty
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill(p===flowPath?(failing?(malformed?{json:{}}:{status:503,json:{error:"NetFlow недоступен"}}):{json:recovered}):{json:p==="/api/servers"?[server]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill(p===flowPath?(failing?(malformed?{json:{}}:{status:503,json:{error:"NetFlow недоступен"}}):{json:{...emptyMapFlow(r.request().url()),...(malformed && new URL(r.request().url()).searchParams.get("range") === "5m" ? {rangeMinutes:2,windowSec:120,sourceWindow:{requestedMinutes:5,effectiveMinutes:2}} : {})}}):{json:p==="/api/servers"?[server]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.goto("/network-map")
|
||||
await expect(page.getByRole("alert").filter({hasText:"Первоначальная загрузка NetFlow"})).toBeVisible()
|
||||
await expect(page.getByText("Данные NetFlow неизвестны",{exact:true})).toBeVisible()
|
||||
failing=false;await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
||||
await expect(page.getByTitle(malformed?/NetFlow · 2 мин из 5 запрошенных · ответ/:/NetFlow · 5 мин · ответ/)).toContainText("приёмник выключен")
|
||||
await expect(page.getByText("IPFIX · среднее за 1 мин 30 с · приёмник выключен")).toBeVisible()
|
||||
if (malformed) {
|
||||
await page.getByRole("button", {name: "Страны", exact: true}).click()
|
||||
await expect(page.getByText(/IPFIX · среднее за 2 мин/)).toHaveAttribute("title", /2 мин из 5 запрошенных/)
|
||||
}
|
||||
await expect(page.getByRole("alert").filter({hasText:"NetFlow:"})).toHaveCount(0)
|
||||
})
|
||||
test("Карта: NetFlow сохраняет сервис при фоновом сбое",async({page})=>{
|
||||
let failing=false
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill(p===flowPath?(failing?{status:403,json:{error:"Нет доступа к NetFlow"}}:{json:{...empty,live:true,totalBytes:100,namedBytes:100,services:[{id:"svc:one",label:"Сервис сохранён",category:"Web",bytes:100,bps:0,share:1}]}}):{json:p==="/api/servers"?[server]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill(p===flowPath?(failing?{status:403,json:{error:"Нет доступа к NetFlow"}}:{json:{...emptyMapFlow(r.request().url()),live:true,totalBytes:100,namedBytes:100,services:[{id:"svc:one",label:"Сервис сохранён",category:"Web",bytes:100,bps:0,share:1}]}}):{json:p==="/api/servers"?[server]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.goto("/network-map");await expect(page.getByText("Сервис сохранён",{exact:true}).first()).toBeVisible()
|
||||
failing=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
||||
await expect(page.getByRole("alert").filter({hasText:"Сохранён предыдущий снимок NetFlow"})).toBeVisible()
|
||||
await expect(page.getByRole("status").filter({hasText:"Показан предыдущий снимок сервисов"})).toBeVisible()
|
||||
await expect(page.getByText("Сервис сохранён",{exact:true}).first()).toBeVisible()
|
||||
})
|
||||
for(const result of ["missing","foreign","unresolved","success"])test("Карта: DNS "+result,async({page})=>{
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p===flowPath?empty:p==="/api/servers"?[{...server,wanUplinks:[{id:"w",name:"WAN",iface:"ether1",isp:"ISP",ip:"router.example",maxDl:100,maxUl:100}]}]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/network/resolve-hosts"?(result==="missing"?{}:{results:result==="foreign"?{"foreign.example":"192.0.2.2"}:{"router.example":result==="unresolved"?null:"192.0.2.2"}}):p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p===flowPath?emptyMapFlow(r.request().url()):p==="/api/servers"?[{...server,wanUplinks:[{id:"w",name:"WAN",iface:"ether1",isp:"ISP",ip:"router.example",maxDl:100,maxUl:100}]}]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/network/resolve-hosts"?(result==="missing"?{}:{results:result==="foreign"?{"foreign.example":"192.0.2.2"}:{"router.example":result==="unresolved"?null:"192.0.2.2"}}):p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.goto("/network-map")
|
||||
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Router",{exact:true})).toBeVisible()
|
||||
if(result==="success")await expect(page.getByRole("alert").filter({hasText:"DNS:"})).toHaveCount(0)
|
||||
@@ -289,10 +394,10 @@ for(const result of ["missing","foreign","unresolved","success"])test("Карт
|
||||
})
|
||||
|
||||
test("Карта: медленный NetFlow не прерывается периодическим опросом",async({page})=>{
|
||||
let requests=0,release!:()=>void;const gate=new Promise<void>(resolve=>{release=resolve})
|
||||
const ranges: string[] = [];let release!:()=>void;const gate=new Promise<void>(resolve=>{release=resolve})
|
||||
await page.clock.install()
|
||||
await page.route("**/api/**",async r=>{const p=new URL(r.request().url()).pathname;if(p===flowPath){requests++;await gate;return r.fulfill({json:empty})}return r.fulfill({json:p==="/api/servers"?[server]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.goto("/network-map");await expect.poll(()=>requests).toBe(1)
|
||||
await page.clock.runFor(5000);expect(requests).toBe(1)
|
||||
release();await expect(page.getByTitle(/NetFlow · 5 мин · ответ/)).toBeVisible()
|
||||
await page.route("**/api/**",async r=>{const p=new URL(r.request().url()).pathname;if(p===flowPath){ranges.push(new URL(r.request().url()).searchParams.get("range")!);await gate;return r.fulfill({json:emptyMapFlow(r.request().url())})}return r.fulfill({json:p==="/api/servers"?[server]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.goto("/network-map");await expect.poll(()=>[...ranges].sort()).toEqual(["1m","5m"])
|
||||
await page.clock.runFor(5000);expect([...ranges].sort()).toEqual(["1m","5m"])
|
||||
release();await expect(page.getByText(/IPFIX · среднее за 1 мин 30 с/)).toBeVisible()
|
||||
})
|
||||
@@ -1,12 +1,12 @@
|
||||
import {test,expect} from "@playwright/test"
|
||||
const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false}
|
||||
import { emptyMapFlow } from "./fixtures/map-flow"
|
||||
const wan={id:"w",name:"WAN",iface:"ether1",isp:"ISP",ip:"192.0.2.1",maxDl:100,maxUl:100}
|
||||
const home={id:1,name:"Домашний",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online",latency:2,wanUplinks:[wan]}
|
||||
const jh={id:2,name:"Jump",host:"192.0.2.2",type:"jump-host",country:"RU",enabled:true,status:"online",latency:3}
|
||||
const tunnel={id:"t1",serverId:"1",name:"gre-home",localAddress:"192.0.2.1",remoteAddress:"192.0.2.2",localInnerIp:"10.0.0.1",remoteInnerIp:"10.0.0.2",poolId:"",ipsec:null,mtu:1476,keepaliveInterval:10,keepaliveRetries:3,dscp:"inherit",clampTcpMss:true,allowFastPath:false,comment:"",enabled:true,status:"up"}
|
||||
test.beforeEach(async({page})=>{
|
||||
await page.route("**/health",r=>r.fulfill({json:{ok:true}}))
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...home,name:"Домашний роутер с очень длинным названием и описанием устройства"},{...jh,name:"Промежуточный узел с длинной подписью"}]:p==="/api/filters/gre-tunnels"?{tunnels:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...home,name:"Домашний роутер с очень длинным названием и описанием устройства"},{...jh,name:"Промежуточный узел с длинной подписью"}]:p==="/api/filters/gre-tunnels"?{tunnels:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})})
|
||||
})
|
||||
for(const width of [1440,390,320])test("Карта: доступные детали и адаптивная оболочка "+width,async({page},testInfo)=>{
|
||||
await page.setViewportSize({width,height:900});await page.goto("/network-map")
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { test, expect } from "@playwright/test"
|
||||
const emptyFlow = { hops: [], live: false, rangeMinutes: 5, windowSec: 300, totalBytes: 0, namedBytes: 0, unclassifiedBytes: 0, asnLoaded: false, countryLoaded: false, services: [], serviceEdges: [], servicePaths: [], countries: [], countryEdges: [], countryPaths: [], countryServiceGroups: [], mapServiceMinSharePct: 5, dedupApplied: false, excludeMeshApplied: false, excludeOverlayApplied: false }
|
||||
import { emptyMapFlow } from "./fixtures/map-flow"
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.route("**/health", r => r.fulfill({ json: { ok: true } }))
|
||||
@@ -10,7 +10,7 @@ test.beforeEach(async ({ page }) => {
|
||||
{ id: 2, name: "Тест EN", host: "192.0.2.2", type: "exit-node", country: "SE", enabled: true, status: "online" },
|
||||
] : path === "/api/filters/gre-tunnels" ? { tunnels: [], failures: [] }
|
||||
: path === "/api/uptime/speed-probes" ? { probes: [] }
|
||||
: path === "/api/traffic/flow/map-hops" ? emptyFlow
|
||||
: path === "/api/traffic/flow/map-hops" ? emptyMapFlow(r.request().url())
|
||||
: path === "/api/auth/config" ? { required: false } : {} })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { test, expect, type Page } from "@playwright/test"
|
||||
|
||||
// Подписи и карточки холста не наезжают друг на друга: проверяем видимые тела (data-map-box), а не фоновые полосы.
|
||||
const empty = { hops: [], live: true, rangeMinutes: 5, windowSec: 300, totalBytes: 0, namedBytes: 0, unclassifiedBytes: 0, asnLoaded: false, countryLoaded: false, services: [], serviceEdges: [], servicePaths: [], countries: [], countryEdges: [], countryPaths: [], countryServiceGroups: [], mapServiceMinSharePct: 0, dedupApplied: false, excludeMeshApplied: false, excludeOverlayApplied: false }
|
||||
import { emptyMapFlow } from "./fixtures/map-flow"
|
||||
const srv = (id: number, name: string, type: string, country = "RU", status = "online") =>
|
||||
({ id, name, host: `192.0.2.${id}`, type, country, enabled: true, status, latency: 10 + id })
|
||||
const gre = (id: string, owner: number, peer: number, status = "up") => ({
|
||||
@@ -14,7 +14,7 @@ async function serve(page: Page, servers: unknown[], tunnels: ReturnType<typeof
|
||||
await page.route("**/api/**", (r) => {
|
||||
const p = new URL(r.request().url()).pathname
|
||||
const json = p === "/api/servers" ? servers : p === "/api/filters/gre-tunnels" ? { tunnels, failures: [] }
|
||||
: p === "/api/uptime/speed-probes" ? { probes: [] } : p === "/api/traffic/flow/map-hops" ? { ...empty, ...flow }
|
||||
: p === "/api/uptime/speed-probes" ? { probes: [] } : p === "/api/traffic/flow/map-hops" ? { ...emptyMapFlow(r.request().url()), live: true, mapServiceMinSharePct: 0, ...flow }
|
||||
: p === "/api/ix/topology" ? { links: [] } : p === "/api/auth/config" ? { required: false } : {}
|
||||
return r.fulfill({ json })
|
||||
})
|
||||
@@ -105,6 +105,51 @@ test("Карта: группа сервисов сворачивается на
|
||||
await page.screenshot({path:info.outputPath("карта-сети.png")})
|
||||
})
|
||||
|
||||
test("Связи Cloudflare остаются на гранях экспортёра и подтверждённого выхода при перетаскивании", async ({ page }) => {
|
||||
const service = { id: "svc:cloudflare", label: "Cloudflare", category: "Cloud", bytes: 10000, bps: 800, share: 1 }
|
||||
const edge = { toId: service.id, bytes: 5000, bps: 400, bpsFwd: 400, bpsRev: 0 }
|
||||
await serve(page, [srv(1, "nov-gw01", "jump-host"), srv(2, "ARN", "exit-node")], [], {
|
||||
services: [service], serviceEdges: [{ ...edge, fromId: "1", observedOnly: true }, { ...edge, fromId: "2" }],
|
||||
namedBytes: service.bytes, totalBytes: service.bytes,
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
const map = page.getByRole("group", { name: "Интерактивная карта сети" })
|
||||
const arn = map.getByRole("button", { name: "Устройство ARN" })
|
||||
const cloudflare = map.getByRole("button", { name: "Сервис Cloudflare" })
|
||||
const exporter = map.getByRole("button", { name: "Устройство nov-gw01" })
|
||||
await expect(cloudflare).toBeVisible()
|
||||
async function attached() {
|
||||
const connections = await map.evaluate(svg => {
|
||||
const card = (name: string) => svg.querySelector(`[aria-label="${name}"] [data-map-box]`)!.getBoundingClientRect()
|
||||
const atSide = (p: DOMPoint, r: DOMRect) =>
|
||||
Math.min(Math.abs(p.x - r.left), Math.abs(p.x - r.right)) < 1 && Math.abs(p.y - (r.top + r.bottom) / 2) < 1
|
||||
return [...svg.querySelectorAll<SVGPathElement>("[data-map-route]")].map(path => {
|
||||
const transform = path.getScreenCTM()!
|
||||
const start = path.getPointAtLength(0).matrixTransform(transform)
|
||||
const end = path.getPointAtLength(path.getTotalLength()).matrixTransform(transform)
|
||||
const source = path.dataset.mapRoute === "observation" ? "Устройство nov-gw01" : "Устройство ARN"
|
||||
return atSide(start, card(source)) && atSide(end, card("Сервис Cloudflare"))
|
||||
})
|
||||
})
|
||||
expect(connections).toEqual([true, true])
|
||||
}
|
||||
await attached()
|
||||
async function center(node: typeof arn) {
|
||||
const rect = (await node.boundingBox())!
|
||||
return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }
|
||||
}
|
||||
const a = await center(arn)
|
||||
await arn.dragTo(map, { targetPosition: { x: a.x - (await map.boundingBox())!.x + 30, y: a.y - (await map.boundingBox())!.y - 65 } })
|
||||
expect(Math.abs((await center(arn)).y - a.y)).toBeGreaterThan(20)
|
||||
await attached()
|
||||
// Same column: before the fix the IPFIX route was replaced by a disconnected dot.
|
||||
const jh = await center(exporter)
|
||||
const bounds = (await map.boundingBox())!
|
||||
await cloudflare.dragTo(map, {targetPosition: {x: jh.x - bounds.x, y: jh.y - bounds.y + 85}})
|
||||
expect(Math.abs((await center(cloudflare)).x - (await center(exporter)).x)).toBeLessThan(15)
|
||||
await attached()
|
||||
})
|
||||
|
||||
test("Карта: сетка JH × Exit и аплинки WAN без наложений подписей", async ({ page }) => {
|
||||
const wan = (i: number) => ({ id: "w" + i, name: "WAN" + i, iface: "ether" + i, isp: "ISP-" + i, ip: `198.51.100.${i}`, maxDl: 100, maxUl: 50 })
|
||||
const servers = [
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {test,expect} from "@playwright/test"
|
||||
const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false}
|
||||
import { emptyMapFlow } from "./fixtures/map-flow"
|
||||
const server={id:1,name:"Router URL",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:null,wanUplinks:[{id:"w",name:"WAN URL",iface:"ether1",isp:"ISP",ip:"192.0.2.1",maxDl:100,maxUl:100}]}
|
||||
test.beforeEach(async({page})=>{
|
||||
await page.route("**/health",r=>r.fulfill({json:{ok:true}}))
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[server]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[server]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})})
|
||||
})
|
||||
test("Карта URL: устройство/WAN, фильтр, поиск, назначения, reload и история",async({page})=>{
|
||||
await page.goto("/network-map?server=1&wan=0&filter=unknown&q=Router&dest=countries&tag=keep#anchor")
|
||||
|
||||
@@ -41,15 +41,39 @@ test('Список трафика: поздний период не заменя
|
||||
await started
|
||||
await expect(page.getByText('Загрузка списка трафика…', { exact: true })).toBeVisible()
|
||||
await expect(page.getByRole('button').filter({ hasText: 'Список 1h' })).toHaveCount(0)
|
||||
const cancelled = page.waitForEvent('requestfailed', {predicate: r => new URL(r.url()).pathname === '/api/traffic/servers' && r.url().includes('range=24h')})
|
||||
await page.getByRole('button', { name: '15м', exact: true }).click()
|
||||
await expect(page.getByRole('button').filter({ hasText: 'Список 15m' })).toBeVisible()
|
||||
const late = page.waitForResponse(r => new URL(r.url()).pathname === '/api/traffic/servers' && r.url().includes('range=24h'))
|
||||
control.release()
|
||||
await late
|
||||
await cancelled
|
||||
await expect(page.getByRole('button').filter({ hasText: 'Список 15m' })).toBeVisible()
|
||||
await expect(page.getByRole('button').filter({ hasText: 'Список 24h' })).toHaveCount(0)
|
||||
})
|
||||
|
||||
test("Трафик клиента обновляет счётчики без перезагрузки", async ({page}) => {
|
||||
await page.clock.install()
|
||||
let txNow = 12
|
||||
await page.route("**/health", route => route.fulfill({json: {ok: true}}))
|
||||
await page.route("**/api/**", route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
const rates = {rxNow: 8, txNow, rxPeak: 20, txPeak: 30, rxTotal: 1, txTotal: 1, rxSeries: [8], txSeries: [txNow]}
|
||||
const iface = {id: "alice-gre", bindingId: "alice-gre", userId: "alice", interfaceName: "gre-alice",
|
||||
serverId: "1", serverName: "MSK", interfaceType: "gre", status: "online", ...rates}
|
||||
const user = {id: "alice", login: "alice", displayName: "Алиса", role: "viewer", active: true, interfaces: [iface], ...rates}
|
||||
const json = path === "/api/auth/config" ? {required: false}
|
||||
: path === "/api/traffic/users" ? {users: [user]}
|
||||
: path === "/api/traffic/servers" ? {servers: []}
|
||||
: path === "/api/traffic/bound-interfaces" ? {interfaces: []} : {}
|
||||
return route.fulfill({json: observedTrafficFixturePayload(json)})
|
||||
})
|
||||
await page.goto("/traffic?user=alice")
|
||||
const card = page.getByRole("button").filter({hasText: "Алиса"})
|
||||
await expect(card).toContainText("12.0 Мбит/с")
|
||||
txNow = 26
|
||||
await page.clock.fastForward(16_000)
|
||||
await expect(card).toContainText("26.0 Мбит/с")
|
||||
})
|
||||
|
||||
test('Список трафика: ошибка обновления скрывает сводку; повтор восстанавливает список', async ({ page }) => {
|
||||
const control = await setup(page)
|
||||
control.failList = true
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { test } from "node:test"
|
||||
import assert from "node:assert/strict"
|
||||
import { MAP_CARD_H, MAP_CARD_W, MAP_PILL_H, mapLinkPath, mapLinkPoint, mapRibbons, placeMapLinkLabels, type MapBox } from "../../lib/network-map-layout"
|
||||
import { mapObservationRoute } from "../../lib/network-map-observation-route"
|
||||
|
||||
const card = (x: number, y: number): MapBox => ({ x: x - MAP_CARD_W / 2, y: y - MAP_CARD_H / 2, w: MAP_CARD_W, h: MAP_CARD_H })
|
||||
const hit = (a: MapBox, b: MapBox) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
|
||||
@@ -13,6 +14,17 @@ test("кривая связи проходит через концы и сере
|
||||
assert.deepEqual(mapLinkPoint(l, 0.5), { x: 100, y: 50 })
|
||||
})
|
||||
|
||||
test("наблюдение IPFIX огибает промежуточный узел в обоих направлениях", () => {
|
||||
const blocker = card(400, 100)
|
||||
for (const [sourceX, serviceX] of [[100, 800], [800, 100]]) {
|
||||
const link = mapLinkPath({x: sourceX, y: 100}, 80, {x: serviceX, y: 100}, 140)
|
||||
const route = mapObservationRoute(link, [blocker], [])
|
||||
assert.ok(route)
|
||||
assert.ok(route.d.startsWith(`M ${link.x1} 100 `) && route.d.endsWith(`H ${link.x2}`))
|
||||
assert.ok(route.track < blocker.y || route.track > blocker.y + blocker.h)
|
||||
}
|
||||
})
|
||||
|
||||
test("подписи не наезжают на карточки и друг на друга, длинная — укорачивается или пропадает", () => {
|
||||
// Три JH слева сходятся в один EN справа; у каждой пары — длинный и короткий вариант подписи.
|
||||
const jh = [100, 180, 260].map((y) => ({ x: 542, y }))
|
||||
|
||||
Reference in new issue
Block a user