From 2fc7e983cc2499c103c51e67b4ca268c8eaa38d9 Mon Sep 17 00:00:00 2001 From: Yoga Pratama Date: Mon, 9 Nov 2026 13:51:04 +0700 Subject: [PATCH] fix(device-details): fix empty apps/protocols/flows in DeviceDetailModal and show top telemetry on Overview tab --- backend/routes/categoryDetail.js | 16 +-- backend/routes/deviceDetailsHandler.js | 91 +++++++------- backend/routes/metadataDetail.js | 16 +-- src/components/ui/DeviceDetailModal.tsx | 6 +- src/components/ui/DeviceFlowsTab.tsx | 8 +- src/components/ui/DeviceIdentityCard.tsx | 145 ++++++++++++++++++----- 6 files changed, 174 insertions(+), 108 deletions(-) diff --git a/backend/routes/categoryDetail.js b/backend/routes/categoryDetail.js index 0a6eedf..0366352 100644 --- a/backend/routes/categoryDetail.js +++ b/backend/routes/categoryDetail.js @@ -9,20 +9,10 @@ const express = require('express'); const router = express.Router(); const { DeviceAppStat, DeviceStat, LookupApp } = require('../models/Schemas'); -// ─── Helper: build base filter from request user/time ────────────────────────── +const { getTimeFilter, getBaseFilter } = require('./dashboard/helpers'); + function buildBaseFilter(req) { - const range = req.query.timeRange || 'all'; - const filter = {}; - if (req.user?.site_uuid) filter.site_uuid = req.user.site_uuid; - if (req.user?.role === 'AGENT_VIEWER' && req.user?.agent_uuid) { - filter.agent_uuid = req.user.agent_uuid; - } - if (range !== 'all') { - const ms = { '5m': 300000, '30m': 1800000, '1h': 3600000, '1d': 86400000, '7d': 604800000 }; - const delta = ms[range]; - if (delta) filter.timestamp = { $gte: new Date(Date.now() - delta) }; - } - return filter; + return getBaseFilter(req, getTimeFilter(req)); } // ─── GET /api/dashboard/category-detail ─────────────────────────────────────── diff --git a/backend/routes/deviceDetailsHandler.js b/backend/routes/deviceDetailsHandler.js index d93986f..48d27be 100644 --- a/backend/routes/deviceDetailsHandler.js +++ b/backend/routes/deviceDetailsHandler.js @@ -1,15 +1,5 @@ // backend/routes/deviceDetailsHandler.js -// ───────────────────────────────────────────────────────────────────────────── -// Device Detail Handler — reads 100% from MongoDB (no live DPI API calls) -// -// Architecture: -// 1. Total download/upload → DeviceStat (latest, DPI API cumulative per-IP) -// 2. Apps tab → DeviceAppStat (DPI API per-IP per-app, collected -// by proxy every 5min for top 30 devices) -// 3. Protocols + Domains → Flow collection (sampled, enriched with domain map) -// 4. Network Flows tab → Flow collection -// 5. Threats tab → Threat collection -// ───────────────────────────────────────────────────────────────────────────── +// Device Detail Handler — reads from MongoDB (DeviceStat, DeviceAppStat, Flow, Threat) const { DeviceStat, DeviceAppStat, Flow, Threat, CustomDeviceLabel } = require('../models/Schemas'); const User = require('../models/User'); @@ -70,21 +60,18 @@ module.exports = async function deviceDetailsHandler(req, res, helpers) { // Find device stats by ip if set, else by mac const deviceQuery = ip ? { ip_address: ip } : { mac_address: mac }; - const device = await DeviceStat.findOne({ ...deviceQuery, ...baseFilter }).sort({ timestamp: -1 }).lean(); + const device = await DeviceStat.findOne({ ...deviceQuery, ...baseFilter }).sort({ download: -1, timestamp: -1 }).lean(); if (!ip && device?.ip_address) { ip = device.ip_address; } - const agentUuid = baseFilter.agent_uuid || device?.agent_uuid || null; + let agentUuid = baseFilter.agent_uuid || device?.agent_uuid || null; + const isRestrictedRole = ['AGENT_VIEWER', 'COMPANY_ADMIN', 'COMPANY_OPERATOR', 'COMPANY_VIEWER'].includes(req.user?.role); + const strictAgentFilter = isRestrictedRole && baseFilter.agent_uuid ? { agent_uuid: baseFilter.agent_uuid } : {}; - // ── PRIMARY bandwidth source ───────────────────────────────────────────── - const totalDownload = device?.download || 0; - const totalUpload = device?.upload || 0; - - // ── Flow filter ────────────────────────────────────────────────────────── - const flowFilter = {}; - if (agentUuid) flowFilter.agent_uuid = agentUuid; - if (req.user?.site_uuid) flowFilter.site_uuid = req.user.site_uuid; + // ── Flow & App filters (respecting baseFilter site & role isolation) ──── + const siteFilter = baseFilter.site_uuid ? { site_uuid: baseFilter.site_uuid } : {}; + const flowFilter = { ...siteFilter, ...strictAgentFilter }; const rawTimeRange = String(req.query.timeRange ?? 'all'); if (rawTimeRange !== 'all') { @@ -92,31 +79,18 @@ module.exports = async function deviceDetailsHandler(req, res, helpers) { if (tf) flowFilter.timestamp = tf; } - // ── Parallel queries ───────────────────────────────────────────────────── - const flowQueryConditions = []; - if (ip) { - flowQueryConditions.push({ src_ip: ip }, { dst_ip: ip }); - } - if (mac) { - flowQueryConditions.push({ src_mac: mac }, { dst_mac: mac }); - } + // Query Flow by IP when IP is known; only fall back to MAC if IP is absent + const flowQueryConditions = ip + ? [{ src_ip: ip }, { dst_ip: ip }] + : (mac ? [{ src_mac: mac }, { dst_mac: mac }] : []); - const threatQuery = { - ...(agentUuid ? { agent_uuid: agentUuid } : {}) - }; - if (ip && mac) { - threatQuery.$or = [{ ip_address: ip }, { mac_address: mac }, { src_mac: mac }]; - } else if (ip) { - threatQuery.ip_address = ip; - } else if (mac) { - threatQuery.$or = [{ mac_address: mac }, { src_mac: mac }]; - } + const threatQuery = { ...siteFilter, ...strictAgentFilter }; + if (ip) threatQuery.$or = [{ ip_address: ip }, { src_ip: ip }]; + else if (mac) threatQuery.$or = [{ mac_address: mac }, { src_mac: mac }]; - const appFilter = agentUuid ? { agent_uuid: agentUuid, ip_address: ip } : { ip_address: ip }; - if (req.user?.site_uuid) appFilter.site_uuid = req.user.site_uuid; + const appFilter = { ...siteFilter, ...strictAgentFilter, ip_address: ip }; const [deviceAppStats, flowsQuery, rawThreats] = await Promise.all([ - // Only query DeviceAppStat if we have an IP ip ? DeviceAppStat.find(appFilter).sort({ timestamp: -1 }).lean() : [], flowQueryConditions.length > 0 ? Flow.find({ ...flowFilter, $or: flowQueryConditions }).sort({ timestamp: -1 }).limit(5000).lean() @@ -145,9 +119,6 @@ module.exports = async function deviceDetailsHandler(req, res, helpers) { appLatest[key].last_seen = a.timestamp; } } - const apps = Object.values(appLatest) - .filter(a => (a.download || 0) + (a.upload || 0) > 0) - .sort((a, b) => (b.download || 0) - (a.download || 0)); // ── Protocol / Domain tabs — from Flow collection ──────────────────────── const protocolsMap = {}, domainsMap = {}, destinationsMap = {}; @@ -165,21 +136,43 @@ module.exports = async function deviceDetailsHandler(req, res, helpers) { const up = f.upload || 0; const ls = f.last_seen || (f.timestamp ? new Date(f.timestamp).toISOString() : new Date().toISOString()); - if (f.app_label) bump(protocolsMap, f.app_label, down, up, ls); - else if (f.protocol) bump(protocolsMap, f.protocol, down, up, ls); - + const protoKey = f.protocol || f.app_label; + if (protoKey) bump(protocolsMap, protoKey, down, up, ls); + + // Fallback: if DeviceAppStat was not collected for this IP (outside top 30), populate apps from flows + if (deviceAppStats.length === 0) { + const appName = inferAppFromDomain(f.sni_hostname || f.domain) || f.app_label || f.protocol; + if (appName) bump(appLatest, appName, down, up, ls); + } + const domainVal = f.sni_hostname || f.domain; if (domainVal) bump(domainsMap, domainVal, down, up, ls); if (f.dst_ip) bump(destinationsMap, f.dst_ip, down, up, ls); } + const apps = Object.values(appLatest) + .filter(a => (a.download || 0) + (a.upload || 0) > 0) + .sort((a, b) => (b.download || 0) - (a.download || 0)); + + agentUuid = deviceAppStats[0]?.agent_uuid || flowsQuery[0]?.agent_uuid || agentUuid; + const appsDl = apps.reduce((s, a) => s + (a.download || 0), 0); + const appsUl = apps.reduce((s, a) => s + (a.upload || 0), 0); + const totalDownload = Math.max(device?.download || 0, appsDl); + const totalUpload = Math.max(device?.upload || 0, appsUl); + // ── Device metadata ─────────────────────────────────────────────────────── const flowMac = flowsQuery.find(f => f.src_ip === ip && f.src_mac && !f.src_mac.startsWith('00:16:3e:'))?.src_mac; const rawDevMac = device?.mac_address && !device.mac_address.startsWith('00:16:3e:') ? device.mac_address : null; const targetMac = rawDevMac || flowMac || mac || device?.mac_address || generateMacFromIp(ip); const man = resolveVendorFromIp(ip, targetMac); const type = resolveDeviceTypeFromIp(ip, targetMac); - const os = resolveOSFromIp(ip, targetMac); + let os = resolveOSFromIp(ip, targetMac); + if (os === 'Windows / Linux' && apps.length > 0) { + const appNames = apps.map(a => String(a.app_label || '').toLowerCase()).join(' '); + if (appNames.includes('microsoft') || appNames.includes('windows') || appNames.includes('office')) os = 'Windows 10 / 11'; + else if (appNames.includes('apple') || appNames.includes('icloud')) os = 'macOS / iOS'; + else if (appNames.includes('android') || appNames.includes('google-play')) os = 'Android OS'; + } const lastSeen = device?.last_seen || device?.timestamp || new Date().toISOString(); const customLabelDoc = await CustomDeviceLabel.findOne({ mac_address: targetMac }).lean(); diff --git a/backend/routes/metadataDetail.js b/backend/routes/metadataDetail.js index 6cbb3b9..3fcd0e0 100644 --- a/backend/routes/metadataDetail.js +++ b/backend/routes/metadataDetail.js @@ -24,20 +24,10 @@ const { SshClientStat, SshServerStat, MdnsHostnameStat, } = require('../models/SchemasTelemetry'); -// ─── Helper: build base filter from request user/time ────────────────────────── +const { getTimeFilter, getBaseFilter } = require('./dashboard/helpers'); + function buildBaseFilter(req) { - const range = req.query.timeRange || 'all'; - const filter = {}; - if (req.user?.site_uuid) filter.site_uuid = req.user.site_uuid; - if (req.user?.role === 'AGENT_VIEWER' && req.user?.agent_uuid) { - filter.agent_uuid = req.user.agent_uuid; - } - if (range !== 'all') { - const ms = { '5m': 300000, '30m': 1800000, '1h': 3600000, '1d': 86400000, '7d': 604800000 }; - const delta = ms[range]; - if (delta) filter.timestamp = { $gte: new Date(Date.now() - delta) }; - } - return filter; + return getBaseFilter(req, getTimeFilter(req)); } // ─── Helper: get per-device breakdown from Flow using a domain value ──────────── diff --git a/src/components/ui/DeviceDetailModal.tsx b/src/components/ui/DeviceDetailModal.tsx index 4258f76..a6f097e 100644 --- a/src/components/ui/DeviceDetailModal.tsx +++ b/src/components/ui/DeviceDetailModal.tsx @@ -49,7 +49,7 @@ export function DeviceDetailModal({ ip, mac = '', deviceData, onClose }: Props) setError(null); try { const agentUuid = deviceData?.agent_uuid || ''; - const res = await fetchDeviceDetails(ip, '1d', mac, agentUuid); + const res = await fetchDeviceDetails(ip, 'all', mac, agentUuid); setData(res); } catch (e: any) { if (!silent) setError(e.message); @@ -206,6 +206,10 @@ export function DeviceDetailModal({ ip, mac = '', deviceData, onClose }: Props) deviceType={data.device_type || deviceData?.device_type || ""} manufacturer={data.manufacturer || deviceData?.manufacturer || ""} lastSeen={data.last_seen || deviceData?.last_seen || ""} + apps={data.apps} + protocols={data.protocols} + domains={data.domains} + onSelectTab={(tab) => setActiveTab(tab)} /> )} diff --git a/src/components/ui/DeviceFlowsTab.tsx b/src/components/ui/DeviceFlowsTab.tsx index 97fee0a..68d3ffc 100644 --- a/src/components/ui/DeviceFlowsTab.tsx +++ b/src/components/ui/DeviceFlowsTab.tsx @@ -66,13 +66,13 @@ export default function DeviceFlowsTab({ flows, ip }: Props) { }; const filterConfigs: FilterConfig[] = [ - { id: "app_name", label: "App", type: "select", value: filters.app_name, options: opts("app_name"), formatter: formatAppLabel }, - { id: "protocol_name", label: "Protocol", type: "select", value: filters.protocol_name, options: opts("protocol_name"), formatter: formatAppLabel }, + { id: "app_label", label: "App", type: "select", value: filters.app_label, options: opts("app_label"), formatter: formatAppLabel }, + { id: "protocol", label: "Protocol", type: "select", value: filters.protocol, options: opts("protocol"), formatter: formatAppLabel }, ]; const filteredData = flows.filter((row: any) => { - if (filters.app_name && filters.app_name !== "All" && row.app_name !== filters.app_name) return false; - if (filters.protocol_name && filters.protocol_name !== "All" && row.protocol_name !== filters.protocol_name) return false; + if (filters.app_label && filters.app_label !== "All" && row.app_label !== filters.app_label) return false; + if (filters.protocol && filters.protocol !== "All" && row.protocol !== filters.protocol) return false; return true; }); diff --git a/src/components/ui/DeviceIdentityCard.tsx b/src/components/ui/DeviceIdentityCard.tsx index 3e86ea8..0c7a985 100644 --- a/src/components/ui/DeviceIdentityCard.tsx +++ b/src/components/ui/DeviceIdentityCard.tsx @@ -1,13 +1,18 @@ "use client"; import React from "react"; -import { Server, Cpu, Monitor, HardDrive, Clock } from "lucide-react"; +import { Server, Cpu, Monitor, HardDrive, Clock, Box, Link2, Globe, ArrowRight } from "lucide-react"; +import { fmtBytes, formatAppLabel } from "@/lib/utils"; interface DeviceIdentityCardProps { osLabel: string; deviceType: string; manufacturer: string; lastSeen: string; + apps?: any[]; + protocols?: any[]; + domains?: any[]; + onSelectTab?: (tab: "apps" | "protocols" | "domains" | "flows") => void; } export default function DeviceIdentityCard({ @@ -15,38 +20,122 @@ export default function DeviceIdentityCard({ deviceType, manufacturer, lastSeen, + apps = [], + protocols = [], + domains = [], + onSelectTab, }: DeviceIdentityCardProps) { return ( -
-

- Identity & Metadata -

-
-
-

- OS -

-

{osLabel || "Unknown"}

+
+
+

+ Identity & Metadata +

+
+
+

+ OS +

+

{osLabel || "Unknown"}

+
+
+

+ Type +

+

{deviceType || "Unknown"}

+
+
+

+ Manufacturer +

+

{manufacturer || "Unknown"}

+
+
+

+ Last Seen +

+

+ {lastSeen ? new Date(lastSeen).toLocaleString() : "Never"} +

+
-
-

- Type -

-

{deviceType || "Unknown"}

+
+ + {/* Quick Telemetry Breakdown on Overview Tab */} +
+
+
+
+ Top Applications ({apps.length}) +
+ {onSelectTab && apps.length > 0 && ( + + )} +
+ {apps.length === 0 ? ( +

No application data recorded

+ ) : ( +
+ {apps.slice(0, 5).map((a: any, i: number) => ( +
+ {formatAppLabel(a.app_label)} + {fmtBytes((a.download || 0) + (a.upload || 0))} +
+ ))} +
+ )}
-
-

- Manufacturer -

-

{manufacturer || "Unknown"}

+ +
+
+
+ Top Protocols ({protocols.length}) +
+ {onSelectTab && protocols.length > 0 && ( + + )} +
+ {protocols.length === 0 ? ( +

No protocol data recorded

+ ) : ( +
+ {protocols.slice(0, 5).map((p: any, i: number) => ( +
+ {formatAppLabel(p.app_label)} + {fmtBytes((p.download || 0) + (p.upload || 0))} +
+ ))} +
+ )}
-
-

- Last Seen -

-

- {lastSeen ? new Date(lastSeen).toLocaleString() : "Never"} -

+ +
+
+
+ Top Domains ({domains.length}) +
+ {onSelectTab && domains.length > 0 && ( + + )} +
+ {domains.length === 0 ? ( +

No domain / SNI data recorded

+ ) : ( +
+ {domains.slice(0, 5).map((d: any, i: number) => ( +
+ {d.app_label} + {fmtBytes((d.download || 0) + (d.upload || 0))} +
+ ))} +
+ )}