fix(device-details): fix empty apps/protocols/flows in DeviceDetailModal and show top telemetry on Overview tab

This commit is contained in:
ypratama committed 2026-11-09 13:51:04 +07:00
1 parent 11b89a9030
commit 2fc7e983cc
6 files changed
+174 -108

No files matched your search

+3 -13
View File
@@ -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 ───────────────────────────────────────
+42 -49
View File
@@ -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();
+3 -13
View File
@@ -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 ────────────
+5 -1
View File
@@ -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)}
/>
</div>
)}
+4 -4
View File
@@ -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;
});
+117 -28
View File
@@ -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 (
<div className="bg-slate-50/50 dark:bg-white/[0.02] border border-border rounded-2xl p-6 text-xs">
<h4 className="text-sm font-bold text-card-foreground uppercase tracking-wider mb-6 flex items-center gap-2">
<Server className="w-4 h-4 text-blue-500" /> Identity & Metadata
</h4>
<div className="grid grid-cols-2 lg:grid-cols-4 gap-6">
<div>
<p className="text-sm font-medium text-muted-foreground flex items-center gap-1.5 mb-1.5">
<Cpu className="w-3.5 h-3.5" /> OS
</p>
<p className="text-card-foreground font-medium text-sm">{osLabel || "Unknown"}</p>
<div className="space-y-6 text-xs">
<div className="bg-slate-50/50 dark:bg-white/[0.02] border border-border rounded-2xl p-6">
<h4 className="text-sm font-bold text-card-foreground uppercase tracking-wider mb-6 flex items-center gap-2">
<Server className="w-4 h-4 text-blue-500" /> Identity & Metadata
</h4>
<div className="grid grid-cols-2 lg:grid-cols-4 gap-6">
<div>
<p className="text-sm font-medium text-muted-foreground flex items-center gap-1.5 mb-1.5">
<Cpu className="w-3.5 h-3.5" /> OS
</p>
<p className="text-card-foreground font-medium text-sm">{osLabel || "Unknown"}</p>
</div>
<div>
<p className="text-sm font-medium text-muted-foreground flex items-center gap-1.5 mb-1.5">
<Monitor className="w-3.5 h-3.5" /> Type
</p>
<p className="text-card-foreground font-medium text-sm">{deviceType || "Unknown"}</p>
</div>
<div>
<p className="text-sm font-medium text-muted-foreground flex items-center gap-1.5 mb-1.5">
<HardDrive className="w-3.5 h-3.5" /> Manufacturer
</p>
<p className="text-card-foreground font-medium text-sm">{manufacturer || "Unknown"}</p>
</div>
<div>
<p className="text-sm font-medium text-muted-foreground flex items-center gap-1.5 mb-1.5">
<Clock className="w-3.5 h-3.5" /> Last Seen
</p>
<p className="text-card-foreground font-medium text-sm">
{lastSeen ? new Date(lastSeen).toLocaleString() : "Never"}
</p>
</div>
</div>
<div>
<p className="text-sm font-medium text-muted-foreground flex items-center gap-1.5 mb-1.5">
<Monitor className="w-3.5 h-3.5" /> Type
</p>
<p className="text-card-foreground font-medium text-sm">{deviceType || "Unknown"}</p>
</div>
{/* Quick Telemetry Breakdown on Overview Tab */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
<div className="bg-slate-50/50 dark:bg-white/[0.02] border border-border rounded-2xl p-5 flex flex-col">
<div className="flex items-center justify-between mb-4">
<h5 className="text-xs font-bold text-card-foreground uppercase tracking-wider flex items-center gap-2">
<Box className="w-4 h-4 text-blue-500" /> Top Applications ({apps.length})
</h5>
{onSelectTab && apps.length > 0 && (
<button onClick={() => onSelectTab("apps")} className="text-[11px] text-blue-500 hover:underline flex items-center gap-1">
View All <ArrowRight className="w-3 h-3" />
</button>
)}
</div>
{apps.length === 0 ? (
<p className="text-muted-foreground text-xs py-4 text-center">No application data recorded</p>
) : (
<div className="space-y-2.5">
{apps.slice(0, 5).map((a: any, i: number) => (
<div key={i} className="flex items-center justify-between gap-2 text-xs border-b border-border/40 pb-2 last:border-0 last:pb-0">
<span className="font-medium text-card-foreground truncate">{formatAppLabel(a.app_label)}</span>
<span className="font-mono text-cyan-500 shrink-0">{fmtBytes((a.download || 0) + (a.upload || 0))}</span>
</div>
))}
</div>
)}
</div>
<div>
<p className="text-sm font-medium text-muted-foreground flex items-center gap-1.5 mb-1.5">
<HardDrive className="w-3.5 h-3.5" /> Manufacturer
</p>
<p className="text-card-foreground font-medium text-sm">{manufacturer || "Unknown"}</p>
<div className="bg-slate-50/50 dark:bg-white/[0.02] border border-border rounded-2xl p-5 flex flex-col">
<div className="flex items-center justify-between mb-4">
<h5 className="text-xs font-bold text-card-foreground uppercase tracking-wider flex items-center gap-2">
<Link2 className="w-4 h-4 text-amber-500" /> Top Protocols ({protocols.length})
</h5>
{onSelectTab && protocols.length > 0 && (
<button onClick={() => onSelectTab("protocols")} className="text-[11px] text-blue-500 hover:underline flex items-center gap-1">
View All <ArrowRight className="w-3 h-3" />
</button>
)}
</div>
{protocols.length === 0 ? (
<p className="text-muted-foreground text-xs py-4 text-center">No protocol data recorded</p>
) : (
<div className="space-y-2.5">
{protocols.slice(0, 5).map((p: any, i: number) => (
<div key={i} className="flex items-center justify-between gap-2 text-xs border-b border-border/40 pb-2 last:border-0 last:pb-0">
<span className="font-medium text-card-foreground truncate">{formatAppLabel(p.app_label)}</span>
<span className="font-mono text-amber-500 shrink-0">{fmtBytes((p.download || 0) + (p.upload || 0))}</span>
</div>
))}
</div>
)}
</div>
<div>
<p className="text-sm font-medium text-muted-foreground flex items-center gap-1.5 mb-1.5">
<Clock className="w-3.5 h-3.5" /> Last Seen
</p>
<p className="text-card-foreground font-medium text-sm">
{lastSeen ? new Date(lastSeen).toLocaleString() : "Never"}
</p>
<div className="bg-slate-50/50 dark:bg-white/[0.02] border border-border rounded-2xl p-5 flex flex-col">
<div className="flex items-center justify-between mb-4">
<h5 className="text-xs font-bold text-card-foreground uppercase tracking-wider flex items-center gap-2">
<Globe className="w-4 h-4 text-purple-500" /> Top Domains ({domains.length})
</h5>
{onSelectTab && domains.length > 0 && (
<button onClick={() => onSelectTab("domains")} className="text-[11px] text-blue-500 hover:underline flex items-center gap-1">
View All <ArrowRight className="w-3 h-3" />
</button>
)}
</div>
{domains.length === 0 ? (
<p className="text-muted-foreground text-xs py-4 text-center">No domain / SNI data recorded</p>
) : (
<div className="space-y-2.5">
{domains.slice(0, 5).map((d: any, i: number) => (
<div key={i} className="flex items-center justify-between gap-2 text-xs border-b border-border/40 pb-2 last:border-0 last:pb-0">
<span className="font-medium text-card-foreground truncate" title={d.app_label}>{d.app_label}</span>
<span className="font-mono text-purple-400 shrink-0">{fmtBytes((d.download || 0) + (d.upload || 0))}</span>
</div>
))}
</div>
)}
</div>
</div>
</div>