// backend/routes/deviceDetailsHandler.js // Device Detail Handler — reads from MongoDB (DeviceStat, DeviceAppStat, Flow, Threat) const { DeviceStat, DeviceAppStat, Flow, Threat, CustomDeviceLabel } = require('../models/Schemas'); const User = require('../models/User'); // Domain → App label for protocol/domain tab enrichment only (NOT for apps tab) const DOMAIN_APP_MAP = { 'youtube.com': 'YouTube', 'googlevideo.com': 'YouTube', 'yt.be': 'YouTube', 'facebook.com': 'Facebook', 'fbcdn.net': 'Facebook', 'instagram.com': 'Instagram', 'whatsapp.com': 'WhatsApp', 'wa.me': 'WhatsApp', 'tiktok.com': 'TikTok', 'tiktokv.com': 'TikTok', 'cloudflare.com': 'Cloudflare', 'cloudflare-dns.com': 'Cloudflare', 'google.com': 'Google', 'googleapis.com': 'Google', 'gstatic.com': 'Google', 'microsoft.com': 'Microsoft', 'microsoftonline.com': 'Microsoft', 'windows.com': 'Microsoft', 'office.com': 'Microsoft', 'live.com': 'Microsoft', 'azure.com': 'Microsoft', 'netflix.com': 'Netflix', 'nflximg.net': 'Netflix', 'twitter.com': 'X (Twitter)', 'twimg.com': 'X (Twitter)', 'telegram.org': 'Telegram', 'telegram.me': 'Telegram', 'zoom.us': 'Zoom', 'zoomgov.com': 'Zoom', 'amazon.com': 'Amazon', 'amazonaws.com': 'Amazon AWS', 'apple.com': 'Apple', 'icloud.com': 'iCloud', 'spotify.com': 'Spotify', 'wazuh.com': 'Wazuh (Security)', 'adobe.com': 'Adobe', 'dropbox.com': 'Dropbox', }; function inferAppFromDomain(domain) { if (!domain) return null; const lower = domain.toLowerCase().replace(/^www\./, ''); if (DOMAIN_APP_MAP[lower]) return DOMAIN_APP_MAP[lower]; for (const [key, app] of Object.entries(DOMAIN_APP_MAP)) { if (lower.endsWith('.' + key) || lower === key) return app; } return null; } module.exports = async function deviceDetailsHandler(req, res, helpers) { const t0 = Date.now(); try { const { getTimeFilter, getBaseFilter, generateMacFromIp, resolveDeviceTypeFromIp, resolveOSFromIp, resolveVendorFromIp, generateAutoLabel } = helpers; const baseFilter = getBaseFilter(req); let ip = String(req.query.ip ?? ''); const mac = String(req.query.mac ?? ''); if (!ip && mac) { const dev = await DeviceStat.findOne({ mac_address: mac, ...baseFilter }).sort({ timestamp: -1 }).lean(); if (dev) { ip = dev.ip_address; } else { const flow = await Flow.findOne({ src_mac: mac, ...baseFilter }).sort({ timestamp: -1 }).lean(); if (flow) ip = flow.src_ip; } } if (!ip && !mac) return res.status(400).json({ ok: false, message: 'ip or mac required' }); // 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({ download: -1, timestamp: -1 }).lean(); if (!ip && device?.ip_address) { ip = device.ip_address; } 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 } : {}; // ── 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'); let tf = null; if (rawTimeRange !== 'all') { tf = getTimeFilter(req); if (tf) flowFilter.timestamp = tf; } // 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 = { ...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 = { ...siteFilter, ...strictAgentFilter, ip_address: ip }; if (tf) { appFilter.timestamp = tf; threatQuery.timestamp = tf; } const [deviceAppStats, flowsQuery, rawThreats] = await Promise.all([ ip ? DeviceAppStat.find(appFilter).sort({ timestamp: -1 }).lean() : [], flowQueryConditions.length > 0 ? Flow.find({ ...flowFilter, $or: flowQueryConditions }).sort({ timestamp: -1 }).limit(5000).lean() : [], Threat.find(threatQuery).sort({ detected_at: -1 }).lean(), ]); // Aggregate by app_label and sum download and upload const appLatest = {}; for (const a of deviceAppStats) { const key = a.app_label; if (!appLatest[key]) { appLatest[key] = { app_label: a.app_label, download: 0, upload: 0, flows: 0, first_seen: a.created_at || a.timestamp, last_seen: a.updated_at || a.timestamp, }; } appLatest[key].download += a.download || 0; appLatest[key].upload += a.upload || 0; appLatest[key].flows += a.flows || 0; if (new Date(a.timestamp) > new Date(appLatest[key].last_seen)) { appLatest[key].last_seen = a.timestamp; } } // ── Protocol / Domain tabs — from Flow collection ──────────────────────── const protocolsMap = {}, domainsMap = {}, destinationsMap = {}; const bump = (map, key, down, up, ls) => { if (!map[key]) map[key] = { app_label: key, download: 0, upload: 0, last_seen: ls }; else if (new Date(ls) > new Date(map[key].last_seen)) map[key].last_seen = ls; map[key].download += down; map[key].upload += up; }; for (const f of flowsQuery) { const isOutbound = ip ? (f.src_ip === ip) : (mac ? (f.src_mac === mac) : false); if (!isOutbound) continue; // outbound only const down = f.download || 0; const up = f.upload || 0; const ls = f.last_seen || (f.timestamp ? new Date(f.timestamp).toISOString() : new Date().toISOString()); 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); let totalDownload = appsDl; let totalUpload = appsUl; if (rawTimeRange === 'all') { totalDownload = Math.max(device?.download || 0, appsDl); totalUpload = Math.max(device?.upload || 0, appsUl); } else { const flowsDl = flowsQuery.filter(f => (ip ? f.src_ip === ip : f.src_mac === mac)).reduce((s, f) => s + (f.download || 0), 0); const flowsUl = flowsQuery.filter(f => (ip ? f.src_ip === ip : f.src_mac === mac)).reduce((s, f) => s + (f.upload || 0), 0); totalDownload = Math.max(appsDl, flowsDl); totalUpload = Math.max(appsUl, flowsUl); } // ── 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); 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 rawCandidates = [ flowsQuery[0]?.last_seen, flowsQuery[0]?.timestamp, deviceAppStats[0]?.timestamp, device?.last_seen, device?.timestamp ].filter(Boolean).map(t => new Date(t).getTime()).filter(n => !isNaN(n)); const lastSeen = rawCandidates.length > 0 ? new Date(Math.max(...rawCandidates)).toISOString() : new Date().toISOString(); const oldestFlow = flowsQuery[flowsQuery.length - 1]; const firstSeen = oldestFlow?.first_seen || oldestFlow?.timestamp || device?.created_at || lastSeen; const customLabelDoc = await CustomDeviceLabel.findOne({ mac_address: targetMac }).lean(); const baseLabel = customLabelDoc?.device_label; const finalLabel = baseLabel && !['−', 'Unknown', 'Generic Client', '-'].includes(baseLabel) ? baseLabel : generateAutoLabel(ip, targetMac, man, type); let agent_label = agentUuid; if (agentUuid) { const agentUser = await User.findOne({ agent_uuid: agentUuid, role: 'AGENT_VIEWER' }).lean(); if (agentUser?.account_name) agent_label = agentUser.account_name; } const threats = rawThreats.map(t => ({ id: t._id?.toString(), threat_type: t.threat_type, severity: t.severity, ip_address: t.ip_address || t.src_ip, dst_ip: t.dst_ip, mac_address: t.mac_address || t.src_mac || null, app_label: t.app_label || null, domain: t.domain || null, detected_at: t.detected_at || t.timestamp, description: t.description || `Suspicious activity detected from ${t.ip_address || t.src_ip}`, agent_uuid: t.agent_uuid, })); const flows = flowsQuery .filter(f => ip ? (f.src_ip === ip) : (mac ? (f.src_mac === mac) : false)) .map(f => ({ flow_id: f.flow_id || f._id.toString(), src_ip: f.src_ip, dst_ip: f.dst_ip, dst_port: f.dst_port, protocol: f.protocol, app_label: inferAppFromDomain(f.sni_hostname || f.domain) || f.app_label || 'Other', domain: f.sni_hostname || f.domain || null, download: f.download || 0, upload: f.upload || 0, last_seen: f.last_seen || (f.timestamp ? new Date(f.timestamp).toISOString() : null), })); const elapsed = Date.now() - t0; console.log(`[DeviceDetails] ip=${ip} agent=${agentUuid} appsFromDB=${apps.length} flows=${flowsQuery.length} dl=${(totalDownload/1e9).toFixed(2)}GB time=${elapsed}ms`); return res.json({ ok: true, data: { ip_address: ip, mac_address: targetMac, device_label: finalLabel, device_type: type, os_label: os, manufacturer: man, first_seen: firstSeen, last_seen: lastSeen, total_download: totalDownload, total_upload: totalUpload, agent_uuid: agentUuid, agent_label, flows, apps, protocols: Object.values(protocolsMap).sort((a, b) => b.download - a.download), domains: Object.values(domainsMap).sort((a, b) => b.download - a.download), destinations: Object.values(destinationsMap).sort((a, b) => b.download - a.download), threats, }, }); } catch (err) { console.error('[DeviceDetailsHandler] Error:', err); return res.status(500).json({ ok: false, message: err.message }); } };