fix(devices): resolve customLabelsMap shadowing bug for Superadmin and unify DeviceStat+Flow enrichment

This commit is contained in:
ypratama committed 2026-11-10 13:30:08 +07:00
1 parent 7c70d7c001
commit d7be4c3031
1 file changed
+98 -141
+98 -141
View File
@@ -1,7 +1,6 @@
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const { DeviceStat, CustomDeviceLabel, Flow } = require('../../models/Schemas');
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');
@@ -12,82 +11,95 @@ router.get('/devices', async (req, res) => {
const limit = req.query.limit !== undefined ? parseInt(req.query.limit) : 0;
const skip = parseInt(req.query.skip ?? 0);
const timeFilter = getTimeFilter(req);
const query = getBaseFilter(req, timeFilter);
const subnetsMap = await applySubnetFilterToQuery(query, query.agent_uuid ? 'src_ip' : 'ip_address');
const devQuery = getBaseFilter(req, timeFilter);
const flowQuery = getBaseFilter(req, timeFilter);
let data;
let customLabelsMap;
const [subnetsMap] = await Promise.all([
applySubnetFilterToQuery(devQuery, 'ip_address'),
applySubnetFilterToQuery(flowQuery, 'src_ip'),
]);
if (query.agent_uuid) {
const flowPipeline = [
{ $match: query },
{ $group: {
_id: { ip: "$src_ip", agent: "$agent_uuid" },
download: { $sum: "$download" },
upload: { $sum: "$upload" },
flows: { $sum: 1 },
last_seen_at: { $max: "$timestamp" },
mac_address: { $first: "$src_mac" },
agent_uuid: { $first: "$agent_uuid" },
site_uuid: { $first: "$site_uuid" }
}},
{ $sort: { download: -1 } },
{ $project: {
_id: 1, // needed for mapping later
ip_address: "$_id.ip",
download: 1,
upload: 1,
flows: 1,
last_seen: "$last_seen_at",
mac_address: 1,
agent_uuid: 1,
site_uuid: 1
}}
];
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 } }
];
if (skip > 0) flowPipeline.push({ $skip: skip });
if (limit > 0) flowPipeline.push({ $limit: limit });
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' }
}}
];
[data, customLabelsMap] = await Promise.all([
Flow.aggregate(flowPipeline),
getCustomLabelsMap()
]);
} else {
const pipeline = [
{ $match: query },
{ $sort: { timestamp: -1 } },
{ $group: { _id: { ip: "$ip_address", agent: "$agent_uuid" }, doc: { $first: "$$ROOT" } } },
{ $replaceRoot: { newRoot: "$doc" } },
{ $sort: { timestamp: -1, download: -1 } }
];
const [rawDevs, customLabelsMap, flowRecent] = await Promise.all([
DeviceStat.aggregate(devPipeline),
getCustomLabelsMap(),
Flow.aggregate(flowPipeline)
]);
if (skip > 0) pipeline.push({ $skip: skip });
if (limit > 0) pipeline.push({ $limit: limit });
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 flowSeenQuery = query.site_uuid ? { site_uuid: query.site_uuid } : {};
const [rawDevs, customLabelsMap, flowRecent] = await Promise.all([
DeviceStat.aggregate(pipeline),
getCustomLabelsMap(),
Flow.aggregate([
{ $match: flowSeenQuery },
{ $group: { _id: { agent: "$agent_uuid", ip: "$src_ip" }, maxTs: { $max: "$timestamp" } } }
])
]);
const flowSeenMap = {};
for (const fr of flowRecent) {
if (fr._id?.ip && fr.maxTs) {
flowSeenMap[`${fr._id.agent || ''}:${fr._id.ip}`] = fr.maxTs;
}
}
data = filterRowsByAgentSubnets(rawDevs, subnetsMap, 'ip_address', 'agent_uuid').map(d => {
const fTs = flowSeenMap[`${d.agent_uuid || ''}:${d.ip_address}`];
const dTs = d.last_seen || d.timestamp;
const bestSeen = (fTs && (!dTs || new Date(fTs) > new Date(dTs))) ? fTs : dTs;
return { ...d, last_seen: bestSeen };
}).sort((a, b) => new Date(b.last_seen || 0) - new Date(a.last_seen || 0) || (b.download || 0) - (a.download || 0));
const devMap = new Map();
for (const d of validDevs) {
const key = `${d.agent_uuid || ''}:${d.ip_address}`;
devMap.set(key, { ...d });
}
const mapped = data.map(obj => {
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);
@@ -110,14 +122,13 @@ router.get('/devices', async (req, res) => {
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 {
@@ -129,7 +140,7 @@ router.get('/mac-bandwidth', async (req, res) => {
const raw = await DeviceStat.aggregate([
{ $match: { ...matchBase } },
{ $group: {
_id: { $ifNull: [ '$mac_address', '$ip_address' ] },
_id: { $ifNull: ['$mac_address', '$ip_address'] },
download: { $sum: '$download' },
upload: { $sum: '$upload' },
ip: { $last: '$ip_address' },
@@ -138,14 +149,8 @@ router.get('/mac-bandwidth', async (req, res) => {
manufacturer: { $last: '$manufacturer' }
}},
{ $project: {
mac_address: 1,
download: 1,
upload: 1,
ip: 1,
label: 1,
manufacturer: 1,
total: { $add: [ '$download', '$upload' ] },
_id: 0
mac_address: 1, download: 1, upload: 1, ip: 1, label: 1, manufacturer: 1,
total: { $add: ['$download', '$upload'] }, _id: 0
}},
{ $sort: { total: -1 } },
{ $limit: limit },
@@ -153,12 +158,7 @@ router.get('/mac-bandwidth', async (req, res) => {
const data = raw.map(d => {
const mac = d.mac_address && d.mac_address !== '-' ? d.mac_address : generateMacFromIp(d.ip);
const man = resolveVendorFromIp(d.ip, mac);
return {
...d,
mac_address: mac,
manufacturer: man
};
return { ...d, mac_address: mac, manufacturer: resolveVendorFromIp(d.ip, mac) };
});
res.json({ ok: true, data });
@@ -168,17 +168,14 @@ router.get('/mac-bandwidth', async (req, res) => {
});
// GET /api/dashboard/devices/mac-details?mac=xx:xx:xx:xx:xx:xx
// Returns IP history + bandwidth stats per MAC address (used by DeviceMacDetailsModal)
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);
// Aggregate IP history for this MAC: group by IP, sum bandwidth, track first/last seen
const raw = await DeviceStat.aggregate([
{ $match: { ...matchBase, mac_address: { $regex: new RegExp(`^${safeMac}$`, 'i') } } },
{ $group: {
@@ -189,12 +186,7 @@ router.get('/devices/mac-details', async (req, res) => {
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
}},
{ $project: { _id: 0, ip_address: '$_id', download: 1, upload: 1, flows: 1, first_seen: 1, last_seen: 1 } },
{ $sort: { last_seen: -1 } },
{ $limit: 50 }
]);
@@ -205,7 +197,6 @@ router.get('/devices/mac-details', async (req, res) => {
}
});
router.get('/security-devices', async (req, res) => {
try {
const timeFilter = getTimeFilter(req);
@@ -215,12 +206,11 @@ router.get('/security-devices', async (req, res) => {
const rawUniqueDevices = await DeviceStat.aggregate([
{ $match: baseFilter },
{ $sort: { timestamp: -1 } },
{ $group: {
_id: '$ip_address',
latestDoc: { $first: '$$ROOT' }
}}
{ $group: { _id: '$ip_address', latestDoc: { $first: '$$ROOT' } } }
]);
const uniqueDevices = rawUniqueDevices.filter(d => filterRowsByAgentSubnets([d.latestDoc], subnetsMap, 'ip_address', 'agent_uuid').length > 0);
const uniqueDevices = rawUniqueDevices.filter(d =>
filterRowsByAgentSubnets([d.latestDoc], subnetsMap, 'ip_address', 'agent_uuid').length > 0
);
const flowStats = await Flow.aggregate([
{ $match: baseFilter },
@@ -228,27 +218,13 @@ router.get('/security-devices', async (req, res) => {
_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
]
}
$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
};
}
});
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 => {
@@ -263,32 +239,16 @@ router.get('/security-devices', async (req, res) => {
? 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;
let risk_level = 'Safe';
if (fStat.total > 0) {
if (encrypted_pct < 50) risk_level = 'Vulnerable';
else if (encrypted_pct < 80) risk_level = 'Moderate';
}
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
_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
};
});
@@ -298,7 +258,4 @@ router.get('/security-devices', async (req, res) => {
}
});
module.exports = router;