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 ────────────