Files

262 lines
9.8 KiB
JavaScript

const express = require('express');
const router = express.Router();
const { DeviceStat, Flow } = require('../../models/Schemas');
const { getTimeFilter, getBaseFilter, getCustomLabelsMap } = require('./helpers');
const { generateMacFromIp, resolveDeviceTypeFromIp, resolveOSFromIp, resolveVendorFromIp, generateAutoLabel } = require('../../deviceResolver');
const { applySubnetFilterToQuery, filterRowsByAgentSubnets } = require('../../utils/subnetFilter');
// GET /api/dashboard/devices
router.get('/devices', async (req, res) => {
try {
const limit = req.query.limit !== undefined ? parseInt(req.query.limit) : 0;
const skip = parseInt(req.query.skip ?? 0);
const timeFilter = getTimeFilter(req);
const devQuery = getBaseFilter(req, timeFilter);
const flowQuery = getBaseFilter(req, timeFilter);
const [subnetsMap] = await Promise.all([
applySubnetFilterToQuery(devQuery, 'ip_address'),
applySubnetFilterToQuery(flowQuery, 'src_ip'),
]);
const devPipeline = [
{ $match: devQuery },
{ $sort: { timestamp: -1 } },
{ $group: { _id: { ip: '$ip_address', agent: '$agent_uuid' }, doc: { $first: '$$ROOT' } } },
{ $replaceRoot: { newRoot: '$doc' } },
{ $sort: { timestamp: -1, download: -1 } }
];
const flowPipeline = [
{ $match: flowQuery },
{ $group: {
_id: { ip: '$src_ip', agent: '$agent_uuid' },
download: { $sum: '$download' },
upload: { $sum: '$upload' },
flows: { $sum: 1 },
maxTs: { $max: '$timestamp' },
site_uuid: { $first: '$site_uuid' }
}}
];
const [rawDevs, customLabelsMap, flowRecent] = await Promise.all([
DeviceStat.aggregate(devPipeline),
getCustomLabelsMap(),
Flow.aggregate(flowPipeline)
]);
const validDevs = filterRowsByAgentSubnets(rawDevs, subnetsMap, 'ip_address', 'agent_uuid');
const validFlows = filterRowsByAgentSubnets(
flowRecent.map(f => ({
ip_address: f._id?.ip,
agent_uuid: f._id?.agent,
site_uuid: f.site_uuid,
download: f.download || 0,
upload: f.upload || 0,
flows: f.flows || 0,
maxTs: f.maxTs
})),
subnetsMap,
'ip_address',
'agent_uuid'
);
const devMap = new Map();
for (const d of validDevs) {
const key = `${d.agent_uuid || ''}:${d.ip_address}`;
devMap.set(key, { ...d });
}
for (const f of validFlows) {
if (!f.ip_address) continue;
const key = `${f.agent_uuid || ''}:${f.ip_address}`;
const existing = devMap.get(key);
if (existing) {
const dTs = existing.last_seen || existing.timestamp;
if (f.maxTs && (!dTs || new Date(f.maxTs) > new Date(dTs))) {
existing.last_seen = f.maxTs;
}
if (!existing.download && f.download) existing.download = f.download;
if (!existing.upload && f.upload) existing.upload = f.upload;
} else {
devMap.set(key, {
_id: `${f.agent_uuid || 'agent'}-${f.ip_address}`,
ip_address: f.ip_address,
agent_uuid: f.agent_uuid,
site_uuid: f.site_uuid,
download: f.download,
upload: f.upload,
flows: f.flows,
last_seen: f.maxTs,
timestamp: f.maxTs
});
}
}
let merged = Array.from(devMap.values()).sort(
(a, b) => new Date(b.last_seen || b.timestamp || 0) - new Date(a.last_seen || a.timestamp || 0) || (b.download || 0) - (a.download || 0)
);
if (skip > 0) merged = merged.slice(skip);
if (limit > 0) merged = merged.slice(0, limit);
const mapped = merged.map(obj => {
const ip = obj.ip_address;
const mac = obj.mac_address && obj.mac_address !== '-' ? obj.mac_address : generateMacFromIp(ip);
const man = resolveVendorFromIp(ip, mac);
const type = resolveDeviceTypeFromIp(ip, mac);
const os = resolveOSFromIp(ip, mac);
const lastSeen = obj.last_seen || obj.timestamp || new Date().toISOString();
const baseLabel = customLabelsMap[mac] || (obj.device_label && !obj.device_label.includes('Workstation / Laptop') ? obj.device_label : null);
const label = baseLabel && baseLabel !== '-' && baseLabel !== 'Unknown' && baseLabel !== 'Generic Client'
? baseLabel
: generateAutoLabel(ip, mac, man, type);
return {
...obj,
id: obj._id.toString(),
mac_address: mac,
device_label: label,
device_type: type,
os_label: os,
manufacturer: man,
last_seen: lastSeen
};
});
res.json({ ok: true, data: mapped });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
});
// GET /api/dashboard/mac-bandwidth
router.get('/mac-bandwidth', async (req, res) => {
try {
const limit = parseInt(req.query.limit ?? 50);
const timeFilter = getTimeFilter(req);
const matchBase = getBaseFilter(req, timeFilter);
await applySubnetFilterToQuery(matchBase, 'ip_address');
const raw = await DeviceStat.aggregate([
{ $match: { ...matchBase } },
{ $group: {
_id: { $ifNull: ['$mac_address', '$ip_address'] },
download: { $sum: '$download' },
upload: { $sum: '$upload' },
ip: { $last: '$ip_address' },
mac_address: { $last: '$mac_address' },
label: { $last: '$device_label' },
manufacturer: { $last: '$manufacturer' }
}},
{ $project: {
mac_address: 1, download: 1, upload: 1, ip: 1, label: 1, manufacturer: 1,
total: { $add: ['$download', '$upload'] }, _id: 0
}},
{ $sort: { total: -1 } },
{ $limit: limit },
]);
const data = raw.map(d => {
const mac = d.mac_address && d.mac_address !== '-' ? d.mac_address : generateMacFromIp(d.ip);
return { ...d, mac_address: mac, manufacturer: resolveVendorFromIp(d.ip, mac) };
});
res.json({ ok: true, data });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
});
// GET /api/dashboard/devices/mac-details?mac=xx:xx:xx:xx:xx:xx
router.get('/devices/mac-details', async (req, res) => {
try {
const mac = String(req.query.mac || '').toLowerCase().trim();
if (!mac) return res.status(400).json({ ok: false, error: 'mac parameter required' });
const safeMac = mac.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const timeFilter = getTimeFilter(req);
const matchBase = getBaseFilter(req, timeFilter);
const raw = await DeviceStat.aggregate([
{ $match: { ...matchBase, mac_address: { $regex: new RegExp(`^${safeMac}$`, 'i') } } },
{ $group: {
_id: '$ip_address',
download: { $sum: '$download' },
upload: { $sum: '$upload' },
flows: { $sum: '$flows' },
first_seen: { $min: '$timestamp' },
last_seen: { $max: '$timestamp' },
}},
{ $project: { _id: 0, ip_address: '$_id', download: 1, upload: 1, flows: 1, first_seen: 1, last_seen: 1 } },
{ $sort: { last_seen: -1 } },
{ $limit: 50 }
]);
res.json({ ok: true, ips: raw });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
});
router.get('/security-devices', async (req, res) => {
try {
const timeFilter = getTimeFilter(req);
const baseFilter = getBaseFilter(req, timeFilter);
const subnetsMap = await applySubnetFilterToQuery(baseFilter, 'ip_address');
const rawUniqueDevices = await DeviceStat.aggregate([
{ $match: baseFilter },
{ $sort: { timestamp: -1 } },
{ $group: { _id: '$ip_address', latestDoc: { $first: '$$ROOT' } } }
]);
const uniqueDevices = rawUniqueDevices.filter(d =>
filterRowsByAgentSubnets([d.latestDoc], subnetsMap, 'ip_address', 'agent_uuid').length > 0
);
const flowStats = await Flow.aggregate([
{ $match: baseFilter },
{ $group: {
_id: '$src_ip',
total_bytes: { $sum: { $add: ['$download', '$upload'] } },
encrypted_bytes: {
$sum: { $cond: [{ $in: ['$dst_port', [443, 8443, 853, 465, 989, 990, 587]] }, { $add: ['$download', '$upload'] }, 0] }
}
}}
]);
const flowMap = {};
flowStats.forEach(fs => { if (fs._id) flowMap[fs._id] = { total: fs.total_bytes || 0, encrypted: fs.encrypted_bytes || 0 }; });
const customLabelsMap = await getCustomLabelsMap();
const mapped = uniqueDevices.map(d => {
const obj = d.latestDoc;
const ip = obj.ip_address;
const mac = obj.mac_address && obj.mac_address !== '-' ? obj.mac_address : generateMacFromIp(ip);
const man = resolveVendorFromIp(ip, mac);
const type = resolveDeviceTypeFromIp(ip, mac);
const os = resolveOSFromIp(ip, mac);
const baseLabel = customLabelsMap[mac];
const label = baseLabel && baseLabel !== '-' && baseLabel !== 'Unknown' && baseLabel !== 'Generic Client'
? baseLabel
: generateAutoLabel(ip, mac, man, type);
const lastSeen = obj.last_seen || obj.timestamp || new Date().toISOString();
const fStat = flowMap[ip] || { total: 0, encrypted: 0 };
const encrypted = fStat.encrypted;
const unencrypted = Math.max(0, fStat.total - encrypted);
const encrypted_pct = fStat.total > 0 ? (encrypted / fStat.total) * 100 : 0;
const risk_level = fStat.total > 0 ? (encrypted_pct < 50 ? 'Vulnerable' : encrypted_pct < 80 ? 'Moderate' : 'Safe') : 'Safe';
return {
_id: obj._id.toString(), ip_address: ip, mac_address: mac, device_label: label,
device_type: type, os_label: os, manufacturer: man, encrypted, unencrypted,
encrypted_pct, risk_level, has_insecure: unencrypted > encrypted * 2, timestamp: lastSeen
};
});
res.json({ ok: true, data: mapped });
} catch (err) {
res.status(500).json({ ok: false, message: err.message });
}
});
module.exports = router;