Compare commits
7
Commits
main
...
API_Backone
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74cf627fb8 | ||
|
|
7abb56e328 | ||
|
|
1a2b58c707 | ||
|
|
08a328a21c | ||
|
|
bd16f19345 | ||
|
|
d7be4c3031 | ||
|
|
7c70d7c001 |
No files matched your search
@@ -66,14 +66,20 @@ module.exports = async function agentDetailsHandler(req, res, helpers) {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
// 1d. Enrich apps with category and favicon from LookupApp
|
// 1d. Enrich apps with category and favicon from LookupApp
|
||||||
|
const { resolveAppCategory } = require('../utils/categoryDictionary');
|
||||||
const appLabels = rawAppsFromFlow.map(a => a._id);
|
const appLabels = rawAppsFromFlow.map(a => a._id);
|
||||||
const lookups = await LookupApp.find({ label: { $in: appLabels } }).lean();
|
const lookups = await LookupApp.find({
|
||||||
|
$or: [
|
||||||
|
{ tag: { $in: appLabels } },
|
||||||
|
{ label: { $in: appLabels } }
|
||||||
|
]
|
||||||
|
}).lean();
|
||||||
const lookupMap = {};
|
const lookupMap = {};
|
||||||
for (const app of lookups) {
|
for (const app of lookups) {
|
||||||
lookupMap[app.label] = {
|
const fav = app.favicon || app.logo || null;
|
||||||
favicon: app.favicon || app.logo || null,
|
const cat = app.application_category?.label || app.category?.label || null;
|
||||||
category: app.application_category?.label || 'Web'
|
if (app.tag) lookupMap[app.tag] = { favicon: fav, category: cat };
|
||||||
};
|
if (app.label) lookupMap[app.label] = { favicon: fav, category: cat };
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Map devices from Flow aggregation (already unique by src_ip)
|
// 2. Map devices from Flow aggregation (already unique by src_ip)
|
||||||
@@ -127,7 +133,7 @@ module.exports = async function agentDetailsHandler(req, res, helpers) {
|
|||||||
const top_apps = rawAppsFromFlow.map((a, index) => ({
|
const top_apps = rawAppsFromFlow.map((a, index) => ({
|
||||||
app_id: index + 1,
|
app_id: index + 1,
|
||||||
app_label: a._id,
|
app_label: a._id,
|
||||||
category: lookupMap[a._id]?.category || 'Web',
|
category: lookupMap[a._id]?.category || resolveAppCategory(a._id, lookupMap),
|
||||||
favicon: lookupMap[a._id]?.favicon || null,
|
favicon: lookupMap[a._id]?.favicon || null,
|
||||||
download: a.download || 0,
|
download: a.download || 0,
|
||||||
upload: a.upload || 0,
|
upload: a.upload || 0,
|
||||||
|
|||||||
@@ -23,17 +23,45 @@ router.get('/', async (req, res) => {
|
|||||||
const base = buildBaseFilter(req);
|
const base = buildBaseFilter(req);
|
||||||
try {
|
try {
|
||||||
// Lookup all application labels that belong to this category
|
// Lookup all application labels that belong to this category
|
||||||
const appsInCategory = await LookupApp.find({ 'application_category.label': category }).lean();
|
const appsInCategory = await LookupApp.find({
|
||||||
const appLabels = appsInCategory.map(app => app.label);
|
$or: [
|
||||||
|
{ 'application_category.label': category },
|
||||||
|
{ 'category.label': category }
|
||||||
|
]
|
||||||
|
}).lean();
|
||||||
|
|
||||||
if (appLabels.length === 0) {
|
const appLabels = new Set();
|
||||||
|
for (const app of appsInCategory) {
|
||||||
|
if (app.tag) {
|
||||||
|
appLabels.add(app.tag);
|
||||||
|
appLabels.add(app.tag.replace(/^netify\./i, 'backone.'));
|
||||||
|
appLabels.add(app.tag.replace(/^netify\./i, 'siab.'));
|
||||||
|
appLabels.add(app.tag.replace(/^netify\./i, ''));
|
||||||
|
}
|
||||||
|
if (app.label) {
|
||||||
|
appLabels.add(app.label);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const { APP_CATEGORY_MAP } = require('../utils/categoryDictionary');
|
||||||
|
for (const [appKey, catName] of Object.entries(APP_CATEGORY_MAP)) {
|
||||||
|
if (catName.toLowerCase() === category.toLowerCase()) {
|
||||||
|
appLabels.add(appKey);
|
||||||
|
appLabels.add(`netify.${appKey}`);
|
||||||
|
appLabels.add(`backone.${appKey}`);
|
||||||
|
appLabels.add(`siab.${appKey}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const labelList = Array.from(appLabels);
|
||||||
|
if (labelList.length === 0) {
|
||||||
return res.json({ ok: true, category, apps: [], devices: [] });
|
return res.json({ ok: true, category, apps: [], devices: [] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const filter = { ...base, app_label: { $in: appLabels } };
|
const filter = { ...base, app_label: { $in: labelList } };
|
||||||
|
|
||||||
// 1. Get Top Apps for this category
|
// 1. Get Top Apps for this category
|
||||||
const topAppsData = await DeviceAppStat.aggregate([
|
let topAppsData = await DeviceAppStat.aggregate([
|
||||||
{ $match: filter },
|
{ $match: filter },
|
||||||
{ $group: {
|
{ $group: {
|
||||||
_id: '$app_label',
|
_id: '$app_label',
|
||||||
@@ -47,6 +75,24 @@ router.get('/', async (req, res) => {
|
|||||||
{ $limit: 200 }
|
{ $limit: 200 }
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
// Fallback to Flow if DeviceAppStat is empty
|
||||||
|
if (topAppsData.length === 0) {
|
||||||
|
const { Flow } = require('../models/Schemas');
|
||||||
|
topAppsData = await Flow.aggregate([
|
||||||
|
{ $match: filter },
|
||||||
|
{ $group: {
|
||||||
|
_id: '$app_label',
|
||||||
|
download: { $sum: '$download' },
|
||||||
|
upload: { $sum: '$upload' },
|
||||||
|
flows: { $sum: 1 },
|
||||||
|
agent_uuid: { $first: '$agent_uuid' },
|
||||||
|
last_seen: { $max: '$timestamp' }
|
||||||
|
}},
|
||||||
|
{ $sort: { download: -1 } },
|
||||||
|
{ $limit: 200 }
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
const apps = topAppsData.map(r => ({
|
const apps = topAppsData.map(r => ({
|
||||||
app_label: r._id,
|
app_label: r._id,
|
||||||
download: r.download,
|
download: r.download,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ const mongoose = require('mongoose');
|
|||||||
const { AppStat, ProtocolStat, AppCategoryStat, LookupApp } = require('../../models/Schemas');
|
const { AppStat, ProtocolStat, AppCategoryStat, LookupApp } = require('../../models/Schemas');
|
||||||
const { getTimeFilter, getBaseFilter } = require('./helpers');
|
const { getTimeFilter, getBaseFilter } = require('./helpers');
|
||||||
const { applySubnetFilterToQuery } = require('../../utils/subnetFilter');
|
const { applySubnetFilterToQuery } = require('../../utils/subnetFilter');
|
||||||
|
const { resolveAppCategory } = require('../../utils/categoryDictionary');
|
||||||
|
|
||||||
// GET /api/dashboard/apps
|
// GET /api/dashboard/apps
|
||||||
router.get('/apps', async (req, res) => {
|
router.get('/apps', async (req, res) => {
|
||||||
@@ -31,24 +32,32 @@ router.get('/apps', async (req, res) => {
|
|||||||
|
|
||||||
// Fetch lookup metadata (category and favicon) to enrich apps list
|
// Fetch lookup metadata (category and favicon) to enrich apps list
|
||||||
const labels = result.map(r => r._id);
|
const labels = result.map(r => r._id);
|
||||||
const lookups = await LookupApp.find({ label: { $in: labels } }).lean();
|
const lookups = await LookupApp.find({
|
||||||
|
$or: [
|
||||||
|
{ tag: { $in: labels } },
|
||||||
|
{ label: { $in: labels } }
|
||||||
|
]
|
||||||
|
}).lean();
|
||||||
const lookupMap = {};
|
const lookupMap = {};
|
||||||
for (const app of lookups) {
|
for (const app of lookups) {
|
||||||
lookupMap[app.label] = {
|
const fav = app.favicon || app.logo || null;
|
||||||
favicon: app.favicon || app.logo || null,
|
const cat = app.application_category?.label || app.category?.label || null;
|
||||||
category: app.application_category?.label || null
|
if (app.tag) lookupMap[app.tag] = { favicon: fav, category: cat };
|
||||||
};
|
if (app.label) lookupMap[app.label] = { favicon: fav, category: cat };
|
||||||
}
|
}
|
||||||
|
|
||||||
const formatted = result.map(r => ({
|
const formatted = result.map(r => {
|
||||||
app_label: r._id,
|
const resolvedCat = lookupMap[r._id]?.category || resolveAppCategory(r._id, lookupMap);
|
||||||
download: r.download || 0,
|
return {
|
||||||
upload: r.upload || 0,
|
app_label: r._id,
|
||||||
total_bytes: r.total_bytes || 0,
|
download: r.download || 0,
|
||||||
flows: r.flows || 0,
|
upload: r.upload || 0,
|
||||||
category: lookupMap[r._id]?.category || null,
|
total_bytes: r.total_bytes || 0,
|
||||||
favicon: lookupMap[r._id]?.favicon || null,
|
flows: r.flows || 0,
|
||||||
}));
|
category: resolvedCat,
|
||||||
|
favicon: lookupMap[r._id]?.favicon || null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
res.json({ ok: true, data: formatted });
|
res.json({ ok: true, data: formatted });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -111,18 +120,23 @@ router.get('/app-categories', async (req, res) => {
|
|||||||
|
|
||||||
// Enrich with categories
|
// Enrich with categories
|
||||||
const labels = appResult.map(r => r._id);
|
const labels = appResult.map(r => r._id);
|
||||||
const lookups = await LookupApp.find({ label: { $in: labels } }).lean();
|
const lookups = await LookupApp.find({
|
||||||
|
$or: [
|
||||||
|
{ tag: { $in: labels } },
|
||||||
|
{ label: { $in: labels } }
|
||||||
|
]
|
||||||
|
}).lean();
|
||||||
const lookupMap = {};
|
const lookupMap = {};
|
||||||
for (const app of lookups) {
|
for (const app of lookups) {
|
||||||
if (app.application_category?.label) {
|
const cat = app.application_category?.label || app.category?.label || null;
|
||||||
lookupMap[app.label] = app.application_category.label;
|
if (app.tag && cat) lookupMap[app.tag] = cat;
|
||||||
}
|
if (app.label && cat) lookupMap[app.label] = cat;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Group by category
|
// Group by category
|
||||||
const catMap = {};
|
const catMap = {};
|
||||||
for (const r of appResult) {
|
for (const r of appResult) {
|
||||||
const cat = lookupMap[r._id] || 'Uncategorized';
|
const cat = resolveAppCategory(r._id, lookupMap);
|
||||||
if (!catMap[cat]) catMap[cat] = { download: 0, upload: 0, flows: 0 };
|
if (!catMap[cat]) catMap[cat] = { download: 0, upload: 0, flows: 0 };
|
||||||
catMap[cat].download += r.download || 0;
|
catMap[cat].download += r.download || 0;
|
||||||
catMap[cat].upload += r.upload || 0;
|
catMap[cat].upload += r.upload || 0;
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const mongoose = require('mongoose');
|
const { DeviceStat, Flow } = require('../../models/Schemas');
|
||||||
const { DeviceStat, CustomDeviceLabel, Flow } = require('../../models/Schemas');
|
|
||||||
const { getTimeFilter, getBaseFilter, getCustomLabelsMap } = require('./helpers');
|
const { getTimeFilter, getBaseFilter, getCustomLabelsMap } = require('./helpers');
|
||||||
const { generateMacFromIp, resolveDeviceTypeFromIp, resolveOSFromIp, resolveVendorFromIp, generateAutoLabel } = require('../../deviceResolver');
|
const { generateMacFromIp, resolveDeviceTypeFromIp, resolveOSFromIp, resolveVendorFromIp, generateAutoLabel } = require('../../deviceResolver');
|
||||||
const { applySubnetFilterToQuery, filterRowsByAgentSubnets } = require('../../utils/subnetFilter');
|
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 limit = req.query.limit !== undefined ? parseInt(req.query.limit) : 0;
|
||||||
const skip = parseInt(req.query.skip ?? 0);
|
const skip = parseInt(req.query.skip ?? 0);
|
||||||
const timeFilter = getTimeFilter(req);
|
const timeFilter = getTimeFilter(req);
|
||||||
const query = getBaseFilter(req, timeFilter);
|
const devQuery = getBaseFilter(req, timeFilter);
|
||||||
const subnetsMap = await applySubnetFilterToQuery(query, query.agent_uuid ? 'src_ip' : 'ip_address');
|
const flowQuery = getBaseFilter(req, timeFilter);
|
||||||
|
|
||||||
let data;
|
const [subnetsMap] = await Promise.all([
|
||||||
let customLabelsMap;
|
applySubnetFilterToQuery(devQuery, 'ip_address'),
|
||||||
|
applySubnetFilterToQuery(flowQuery, 'src_ip'),
|
||||||
|
]);
|
||||||
|
|
||||||
if (query.agent_uuid) {
|
const devPipeline = [
|
||||||
const flowPipeline = [
|
{ $match: devQuery },
|
||||||
{ $match: query },
|
{ $sort: { timestamp: -1 } },
|
||||||
{ $group: {
|
{ $group: { _id: { ip: '$ip_address', agent: '$agent_uuid' }, doc: { $first: '$$ROOT' } } },
|
||||||
_id: { ip: "$src_ip", agent: "$agent_uuid" },
|
{ $replaceRoot: { newRoot: '$doc' } },
|
||||||
download: { $sum: "$download" },
|
{ $sort: { timestamp: -1, download: -1 } }
|
||||||
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
|
|
||||||
}}
|
|
||||||
];
|
|
||||||
|
|
||||||
if (skip > 0) flowPipeline.push({ $skip: skip });
|
const flowPipeline = [
|
||||||
if (limit > 0) flowPipeline.push({ $limit: limit });
|
{ $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([
|
const [rawDevs, customLabelsMap, flowRecent] = await Promise.all([
|
||||||
Flow.aggregate(flowPipeline),
|
DeviceStat.aggregate(devPipeline),
|
||||||
getCustomLabelsMap()
|
getCustomLabelsMap(),
|
||||||
]);
|
Flow.aggregate(flowPipeline)
|
||||||
} 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 } }
|
|
||||||
];
|
|
||||||
|
|
||||||
if (skip > 0) pipeline.push({ $skip: skip });
|
const validDevs = filterRowsByAgentSubnets(rawDevs, subnetsMap, 'ip_address', 'agent_uuid');
|
||||||
if (limit > 0) pipeline.push({ $limit: limit });
|
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 devMap = new Map();
|
||||||
const [rawDevs, customLabelsMap, flowRecent] = await Promise.all([
|
for (const d of validDevs) {
|
||||||
DeviceStat.aggregate(pipeline),
|
const key = `${d.agent_uuid || ''}:${d.ip_address}`;
|
||||||
getCustomLabelsMap(),
|
devMap.set(key, { ...d });
|
||||||
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 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 ip = obj.ip_address;
|
||||||
const mac = obj.mac_address && obj.mac_address !== '-' ? obj.mac_address : generateMacFromIp(ip);
|
const mac = obj.mac_address && obj.mac_address !== '-' ? obj.mac_address : generateMacFromIp(ip);
|
||||||
const man = resolveVendorFromIp(ip, mac);
|
const man = resolveVendorFromIp(ip, mac);
|
||||||
@@ -110,14 +122,13 @@ router.get('/devices', async (req, res) => {
|
|||||||
last_seen: lastSeen
|
last_seen: lastSeen
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
res.json({ ok: true, data: mapped });
|
res.json({ ok: true, data: mapped });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
res.status(500).json({ ok: false, error: err.message });
|
res.status(500).json({ ok: false, error: err.message });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// GET /api/dashboard/mac-bandwidth
|
// GET /api/dashboard/mac-bandwidth
|
||||||
router.get('/mac-bandwidth', async (req, res) => {
|
router.get('/mac-bandwidth', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
@@ -129,7 +140,7 @@ router.get('/mac-bandwidth', async (req, res) => {
|
|||||||
const raw = await DeviceStat.aggregate([
|
const raw = await DeviceStat.aggregate([
|
||||||
{ $match: { ...matchBase } },
|
{ $match: { ...matchBase } },
|
||||||
{ $group: {
|
{ $group: {
|
||||||
_id: { $ifNull: [ '$mac_address', '$ip_address' ] },
|
_id: { $ifNull: ['$mac_address', '$ip_address'] },
|
||||||
download: { $sum: '$download' },
|
download: { $sum: '$download' },
|
||||||
upload: { $sum: '$upload' },
|
upload: { $sum: '$upload' },
|
||||||
ip: { $last: '$ip_address' },
|
ip: { $last: '$ip_address' },
|
||||||
@@ -138,14 +149,8 @@ router.get('/mac-bandwidth', async (req, res) => {
|
|||||||
manufacturer: { $last: '$manufacturer' }
|
manufacturer: { $last: '$manufacturer' }
|
||||||
}},
|
}},
|
||||||
{ $project: {
|
{ $project: {
|
||||||
mac_address: 1,
|
mac_address: 1, download: 1, upload: 1, ip: 1, label: 1, manufacturer: 1,
|
||||||
download: 1,
|
total: { $add: ['$download', '$upload'] }, _id: 0
|
||||||
upload: 1,
|
|
||||||
ip: 1,
|
|
||||||
label: 1,
|
|
||||||
manufacturer: 1,
|
|
||||||
total: { $add: [ '$download', '$upload' ] },
|
|
||||||
_id: 0
|
|
||||||
}},
|
}},
|
||||||
{ $sort: { total: -1 } },
|
{ $sort: { total: -1 } },
|
||||||
{ $limit: limit },
|
{ $limit: limit },
|
||||||
@@ -153,12 +158,7 @@ router.get('/mac-bandwidth', async (req, res) => {
|
|||||||
|
|
||||||
const data = raw.map(d => {
|
const data = raw.map(d => {
|
||||||
const mac = d.mac_address && d.mac_address !== '-' ? d.mac_address : generateMacFromIp(d.ip);
|
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: resolveVendorFromIp(d.ip, mac) };
|
||||||
return {
|
|
||||||
...d,
|
|
||||||
mac_address: mac,
|
|
||||||
manufacturer: man
|
|
||||||
};
|
|
||||||
});
|
});
|
||||||
|
|
||||||
res.json({ ok: true, data });
|
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
|
// 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) => {
|
router.get('/devices/mac-details', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const mac = String(req.query.mac || '').toLowerCase().trim();
|
const mac = String(req.query.mac || '').toLowerCase().trim();
|
||||||
if (!mac) return res.status(400).json({ ok: false, error: 'mac parameter required' });
|
if (!mac) return res.status(400).json({ ok: false, error: 'mac parameter required' });
|
||||||
const safeMac = mac.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
const safeMac = mac.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
|
|
||||||
const timeFilter = getTimeFilter(req);
|
const timeFilter = getTimeFilter(req);
|
||||||
const matchBase = getBaseFilter(req, timeFilter);
|
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([
|
const raw = await DeviceStat.aggregate([
|
||||||
{ $match: { ...matchBase, mac_address: { $regex: new RegExp(`^${safeMac}$`, 'i') } } },
|
{ $match: { ...matchBase, mac_address: { $regex: new RegExp(`^${safeMac}$`, 'i') } } },
|
||||||
{ $group: {
|
{ $group: {
|
||||||
@@ -189,12 +186,7 @@ router.get('/devices/mac-details', async (req, res) => {
|
|||||||
first_seen: { $min: '$timestamp' },
|
first_seen: { $min: '$timestamp' },
|
||||||
last_seen: { $max: '$timestamp' },
|
last_seen: { $max: '$timestamp' },
|
||||||
}},
|
}},
|
||||||
{ $project: {
|
{ $project: { _id: 0, ip_address: '$_id', download: 1, upload: 1, flows: 1, first_seen: 1, last_seen: 1 } },
|
||||||
_id: 0,
|
|
||||||
ip_address: '$_id',
|
|
||||||
download: 1, upload: 1, flows: 1,
|
|
||||||
first_seen: 1, last_seen: 1
|
|
||||||
}},
|
|
||||||
{ $sort: { last_seen: -1 } },
|
{ $sort: { last_seen: -1 } },
|
||||||
{ $limit: 50 }
|
{ $limit: 50 }
|
||||||
]);
|
]);
|
||||||
@@ -205,7 +197,6 @@ router.get('/devices/mac-details', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
router.get('/security-devices', async (req, res) => {
|
router.get('/security-devices', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const timeFilter = getTimeFilter(req);
|
const timeFilter = getTimeFilter(req);
|
||||||
@@ -215,12 +206,11 @@ router.get('/security-devices', async (req, res) => {
|
|||||||
const rawUniqueDevices = await DeviceStat.aggregate([
|
const rawUniqueDevices = await DeviceStat.aggregate([
|
||||||
{ $match: baseFilter },
|
{ $match: baseFilter },
|
||||||
{ $sort: { timestamp: -1 } },
|
{ $sort: { timestamp: -1 } },
|
||||||
{ $group: {
|
{ $group: { _id: '$ip_address', latestDoc: { $first: '$$ROOT' } } }
|
||||||
_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([
|
const flowStats = await Flow.aggregate([
|
||||||
{ $match: baseFilter },
|
{ $match: baseFilter },
|
||||||
@@ -228,27 +218,13 @@ router.get('/security-devices', async (req, res) => {
|
|||||||
_id: '$src_ip',
|
_id: '$src_ip',
|
||||||
total_bytes: { $sum: { $add: ['$download', '$upload'] } },
|
total_bytes: { $sum: { $add: ['$download', '$upload'] } },
|
||||||
encrypted_bytes: {
|
encrypted_bytes: {
|
||||||
$sum: {
|
$sum: { $cond: [{ $in: ['$dst_port', [443, 8443, 853, 465, 989, 990, 587]] }, { $add: ['$download', '$upload'] }, 0] }
|
||||||
$cond: [
|
|
||||||
{ $in: ['$dst_port', [443, 8443, 853, 465, 989, 990, 587]] },
|
|
||||||
{ $add: ['$download', '$upload'] },
|
|
||||||
0
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const flowMap = {};
|
const flowMap = {};
|
||||||
flowStats.forEach(fs => {
|
flowStats.forEach(fs => { if (fs._id) flowMap[fs._id] = { total: fs.total_bytes || 0, encrypted: fs.encrypted_bytes || 0 }; });
|
||||||
if (fs._id) {
|
|
||||||
flowMap[fs._id] = {
|
|
||||||
total: fs.total_bytes || 0,
|
|
||||||
encrypted: fs.encrypted_bytes || 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const customLabelsMap = await getCustomLabelsMap();
|
const customLabelsMap = await getCustomLabelsMap();
|
||||||
|
|
||||||
const mapped = uniqueDevices.map(d => {
|
const mapped = uniqueDevices.map(d => {
|
||||||
@@ -263,32 +239,16 @@ router.get('/security-devices', async (req, res) => {
|
|||||||
? baseLabel
|
? baseLabel
|
||||||
: generateAutoLabel(ip, mac, man, type);
|
: generateAutoLabel(ip, mac, man, type);
|
||||||
const lastSeen = obj.last_seen || obj.timestamp || new Date().toISOString();
|
const lastSeen = obj.last_seen || obj.timestamp || new Date().toISOString();
|
||||||
|
|
||||||
const fStat = flowMap[ip] || { total: 0, encrypted: 0 };
|
const fStat = flowMap[ip] || { total: 0, encrypted: 0 };
|
||||||
const encrypted = fStat.encrypted;
|
const encrypted = fStat.encrypted;
|
||||||
const unencrypted = Math.max(0, fStat.total - encrypted);
|
const unencrypted = Math.max(0, fStat.total - encrypted);
|
||||||
const encrypted_pct = fStat.total > 0 ? (encrypted / fStat.total) * 100 : 0;
|
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';
|
||||||
let risk_level = 'Safe';
|
|
||||||
if (fStat.total > 0) {
|
|
||||||
if (encrypted_pct < 50) risk_level = 'Vulnerable';
|
|
||||||
else if (encrypted_pct < 80) risk_level = 'Moderate';
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
_id: obj._id.toString(),
|
_id: obj._id.toString(), ip_address: ip, mac_address: mac, device_label: label,
|
||||||
ip_address: ip,
|
device_type: type, os_label: os, manufacturer: man, encrypted, unencrypted,
|
||||||
mac_address: mac,
|
encrypted_pct, risk_level, has_insecure: unencrypted > encrypted * 2, timestamp: lastSeen
|
||||||
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;
|
module.exports = router;
|
||||||
+173
-17
@@ -13,14 +13,24 @@ router.get('/countries', async (req, res) => {
|
|||||||
const matchBase = getBaseFilter(req, timeFilter);
|
const matchBase = getBaseFilter(req, timeFilter);
|
||||||
await applySubnetFilterToQuery(matchBase, 'src_ip');
|
await applySubnetFilterToQuery(matchBase, 'src_ip');
|
||||||
|
|
||||||
// Aggregate directly from per-agent Flow collection to avoid upstream CountryStat global pollution
|
// Aggregate directly from per-agent Flow collection including domain & app_label per dst_ip
|
||||||
const raw = await Flow.aggregate([
|
const raw = await Flow.aggregate([
|
||||||
{ $match: { ...matchBase, dst_ip: { $ne: null, $ne: '' } } },
|
{ $match: { ...matchBase, dst_ip: { $ne: null, $ne: '' } } },
|
||||||
{ $group: {
|
{ $group: {
|
||||||
_id: { dst_ip: '$dst_ip', agent_uuid: '$agent_uuid' },
|
_id: { dst_ip: '$dst_ip', agent_uuid: '$agent_uuid' },
|
||||||
download: { $sum: '$download' },
|
download: { $sum: '$download' },
|
||||||
upload: { $sum: '$upload' },
|
upload: { $sum: '$upload' },
|
||||||
flow_count: { $sum: 1 }
|
flow_count: { $sum: 1 },
|
||||||
|
domain: { $max: { $ifNull: ['$domain', '$sni_hostname'] } },
|
||||||
|
app_label: {
|
||||||
|
$max: {
|
||||||
|
$cond: [
|
||||||
|
{ $and: [{ $ne: ['$app_label', null] }, { $ne: ['$app_label', ''] }, { $ne: ['$app_label', 'Unknown'] }] },
|
||||||
|
'$app_label',
|
||||||
|
null
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -44,7 +54,9 @@ router.get('/countries', async (req, res) => {
|
|||||||
download: 0,
|
download: 0,
|
||||||
upload: 0,
|
upload: 0,
|
||||||
flow_count: 0,
|
flow_count: 0,
|
||||||
byAgent: {}
|
byAgent: {},
|
||||||
|
byIp: {},
|
||||||
|
byDomain: {}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
countryMap[cc].download += dl;
|
countryMap[cc].download += dl;
|
||||||
@@ -57,6 +69,33 @@ router.get('/countries', async (req, res) => {
|
|||||||
countryMap[cc].byAgent[agentUuid].download += dl;
|
countryMap[cc].byAgent[agentUuid].download += dl;
|
||||||
countryMap[cc].byAgent[agentUuid].upload += ul;
|
countryMap[cc].byAgent[agentUuid].upload += ul;
|
||||||
countryMap[cc].byAgent[agentUuid].flow_count += fc;
|
countryMap[cc].byAgent[agentUuid].flow_count += fc;
|
||||||
|
|
||||||
|
if (!countryMap[cc].byIp[dstIp]) {
|
||||||
|
countryMap[cc].byIp[dstIp] = {
|
||||||
|
ip: dstIp,
|
||||||
|
domain: r.domain || null,
|
||||||
|
app_label: r.app_label || null,
|
||||||
|
download: 0,
|
||||||
|
upload: 0,
|
||||||
|
total: 0
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const ipEntry = countryMap[cc].byIp[dstIp];
|
||||||
|
ipEntry.download += dl;
|
||||||
|
ipEntry.upload += ul;
|
||||||
|
ipEntry.total += (dl + ul);
|
||||||
|
if (!ipEntry.domain && r.domain) ipEntry.domain = r.domain;
|
||||||
|
if (!ipEntry.app_label && r.app_label) ipEntry.app_label = r.app_label;
|
||||||
|
|
||||||
|
const domKey = (r.domain && String(r.domain).trim()) || (r.app_label && String(r.app_label).trim()) || null;
|
||||||
|
if (domKey && domKey !== 'Unknown') {
|
||||||
|
if (!countryMap[cc].byDomain[domKey]) {
|
||||||
|
countryMap[cc].byDomain[domKey] = { domain: domKey, download: 0, upload: 0, total: 0 };
|
||||||
|
}
|
||||||
|
countryMap[cc].byDomain[domKey].download += dl;
|
||||||
|
countryMap[cc].byDomain[domKey].upload += ul;
|
||||||
|
countryMap[cc].byDomain[domKey].total += (dl + ul);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let data = Object.values(countryMap)
|
let data = Object.values(countryMap)
|
||||||
@@ -66,7 +105,9 @@ router.get('/countries', async (req, res) => {
|
|||||||
download: c.download,
|
download: c.download,
|
||||||
upload: c.upload,
|
upload: c.upload,
|
||||||
flow_count: c.flow_count,
|
flow_count: c.flow_count,
|
||||||
agent_breakdown: Object.values(c.byAgent).sort((a, b) => (b.download + b.upload) - (a.download + a.upload))
|
agent_breakdown: Object.values(c.byAgent).sort((a, b) => (b.download + b.upload) - (a.download + a.upload)),
|
||||||
|
top_ips: Object.values(c.byIp).sort((a, b) => b.total - a.total).slice(0, 8),
|
||||||
|
top_domains: Object.values(c.byDomain).sort((a, b) => b.total - a.total).slice(0, 8),
|
||||||
}))
|
}))
|
||||||
.sort((a, b) => (b.download + b.upload) - (a.download + a.upload));
|
.sort((a, b) => (b.download + b.upload) - (a.download + a.upload));
|
||||||
|
|
||||||
@@ -171,36 +212,151 @@ router.get('/dns', async (req, res) => {
|
|||||||
const limit = req.query.limit !== undefined ? parseInt(req.query.limit, 10) : 0;
|
const limit = req.query.limit !== undefined ? parseInt(req.query.limit, 10) : 0;
|
||||||
const timeFilter = getTimeFilter(req);
|
const timeFilter = getTimeFilter(req);
|
||||||
const matchBase = getBaseFilter(req, timeFilter);
|
const matchBase = getBaseFilter(req, timeFilter);
|
||||||
const { SniHostnameStat } = require('../../models/SchemasTelemetry');
|
await applySubnetFilterToQuery(matchBase, 'src_ip');
|
||||||
|
const { Flow } = require('../../models/Schemas');
|
||||||
|
|
||||||
|
// Aggregate real domain connections directly from Flow
|
||||||
const pipeline = [
|
const pipeline = [
|
||||||
{ $match: { ...matchBase, sni_hostname: { $ne: null } } },
|
{
|
||||||
{ $group: {
|
$match: {
|
||||||
_id: '$sni_hostname',
|
...matchBase,
|
||||||
|
$or: [
|
||||||
|
{ domain: { $ne: null, $ne: '', $nin: ['Unknown', '-'] } },
|
||||||
|
{ sni_hostname: { $ne: null, $ne: '', $nin: ['Unknown', '-'] } }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$project: {
|
||||||
|
resolved_domain: { $ifNull: ['$domain', '$sni_hostname'] },
|
||||||
|
download: { $ifNull: ['$download', 0] },
|
||||||
|
upload: { $ifNull: ['$upload', 0] },
|
||||||
|
last_seen: 1,
|
||||||
|
app_label: 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$match: {
|
||||||
|
resolved_domain: { $ne: null, $ne: '', $nin: ['Unknown', '-'] }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$group: {
|
||||||
|
_id: '$resolved_domain',
|
||||||
download: { $sum: '$download' },
|
download: { $sum: '$download' },
|
||||||
upload: { $sum: '$upload' },
|
upload: { $sum: '$upload' },
|
||||||
count: { $sum: '$flows' }
|
query_count: { $sum: 1 },
|
||||||
}},
|
last_seen: { $max: '$last_seen' },
|
||||||
{ $project: {
|
app_label: { $first: '$app_label' }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$project: {
|
||||||
domain: '$_id',
|
domain: '$_id',
|
||||||
query_count: '$count',
|
query_count: 1,
|
||||||
download: 1,
|
download: 1,
|
||||||
upload: 1,
|
upload: 1,
|
||||||
app_label: { $literal: null },
|
last_seen: 1,
|
||||||
category: { $literal: null },
|
app_label: 1,
|
||||||
_id: 0
|
_id: 0
|
||||||
}},
|
}
|
||||||
{ $sort: { query_count: -1 } },
|
},
|
||||||
|
{ $sort: { query_count: -1, download: -1 } }
|
||||||
];
|
];
|
||||||
|
|
||||||
if (limit > 0) {
|
if (limit > 0) {
|
||||||
pipeline.push({ $limit: limit });
|
pipeline.push({ $limit: limit });
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await SniHostnameStat.aggregate(pipeline);
|
let data = await Flow.aggregate(pipeline);
|
||||||
|
|
||||||
|
// Fallback to SniHostnameStat if Flow has 0 matching records
|
||||||
|
if (data.length === 0) {
|
||||||
|
const { SniHostnameStat } = require('../../models/SchemasTelemetry');
|
||||||
|
const sniPipeline = [
|
||||||
|
{ $match: { ...matchBase, sni_hostname: { $ne: null, $ne: '', $nin: ['Unknown', '-'] } } },
|
||||||
|
{ $group: {
|
||||||
|
_id: '$sni_hostname',
|
||||||
|
download: { $sum: '$download' },
|
||||||
|
upload: { $sum: '$upload' },
|
||||||
|
query_count: { $sum: { $cond: [{ $gt: ['$flows', 0] }, '$flows', 1] } },
|
||||||
|
last_seen: { $max: '$timestamp' }
|
||||||
|
}},
|
||||||
|
{ $project: {
|
||||||
|
domain: '$_id',
|
||||||
|
query_count: 1,
|
||||||
|
download: 1,
|
||||||
|
upload: 1,
|
||||||
|
last_seen: 1,
|
||||||
|
app_label: { $literal: null },
|
||||||
|
_id: 0
|
||||||
|
}},
|
||||||
|
{ $sort: { query_count: -1, download: -1 } }
|
||||||
|
];
|
||||||
|
if (limit > 0) sniPipeline.push({ $limit: limit });
|
||||||
|
data = await SniHostnameStat.aggregate(sniPipeline);
|
||||||
|
}
|
||||||
|
|
||||||
res.json({ ok: true, data });
|
res.json({ ok: true, data });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
res.status(500).json({ ok: false, error: err.message });
|
res.status(500).json({ ok: false, error: err.message });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// GET /api/dashboard/domain-details?domain=...
|
||||||
|
router.get('/domain-details', async (req, res) => {
|
||||||
|
const { domain, agentUuid } = req.query;
|
||||||
|
if (!domain) return res.status(400).json({ ok: false, error: 'domain is required' });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { Flow } = require('../../models/Schemas');
|
||||||
|
const { generateMacFromIp, resolveVendorFromIp, resolveDeviceTypeFromIp, generateAutoLabel } = require('../../deviceResolver');
|
||||||
|
|
||||||
|
const filter = {
|
||||||
|
$or: [
|
||||||
|
{ domain: domain },
|
||||||
|
{ sni_hostname: domain }
|
||||||
|
]
|
||||||
|
};
|
||||||
|
if (agentUuid) {
|
||||||
|
filter.agent_uuid = agentUuid;
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = await Flow.find(filter).sort({ timestamp: -1, last_seen: -1 }).limit(100).lean();
|
||||||
|
if (!raw || !Array.isArray(raw)) {
|
||||||
|
return res.json({ ok: true, data: [] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = [];
|
||||||
|
const seen = new Set();
|
||||||
|
|
||||||
|
for (const r of raw) {
|
||||||
|
const ip = r.src_ip;
|
||||||
|
const mac = r.src_mac || generateMacFromIp(ip);
|
||||||
|
if (!ip) continue;
|
||||||
|
|
||||||
|
const key = `${ip}-${mac}`;
|
||||||
|
if (seen.has(key)) continue;
|
||||||
|
seen.add(key);
|
||||||
|
|
||||||
|
const vendor = resolveVendorFromIp(ip, mac);
|
||||||
|
const type = resolveDeviceTypeFromIp(ip, mac);
|
||||||
|
const autoLabel = generateAutoLabel(ip, mac, vendor, type);
|
||||||
|
|
||||||
|
results.push({
|
||||||
|
ip,
|
||||||
|
mac,
|
||||||
|
device_name: autoLabel,
|
||||||
|
download: r.download || 0,
|
||||||
|
upload: r.upload || 0,
|
||||||
|
last_seen: r.last_seen || r.timestamp
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({ ok: true, data: results });
|
||||||
|
} catch (err) {
|
||||||
|
res.status(500).json({ ok: false, error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
@@ -74,8 +74,9 @@ module.exports = async function deviceDetailsHandler(req, res, helpers) {
|
|||||||
const flowFilter = { ...siteFilter, ...strictAgentFilter };
|
const flowFilter = { ...siteFilter, ...strictAgentFilter };
|
||||||
|
|
||||||
const rawTimeRange = String(req.query.timeRange ?? 'all');
|
const rawTimeRange = String(req.query.timeRange ?? 'all');
|
||||||
|
let tf = null;
|
||||||
if (rawTimeRange !== 'all') {
|
if (rawTimeRange !== 'all') {
|
||||||
const tf = getTimeFilter(req);
|
tf = getTimeFilter(req);
|
||||||
if (tf) flowFilter.timestamp = tf;
|
if (tf) flowFilter.timestamp = tf;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,6 +90,10 @@ module.exports = async function deviceDetailsHandler(req, res, helpers) {
|
|||||||
else if (mac) threatQuery.$or = [{ mac_address: mac }, { src_mac: mac }];
|
else if (mac) threatQuery.$or = [{ mac_address: mac }, { src_mac: mac }];
|
||||||
|
|
||||||
const appFilter = { ...siteFilter, ...strictAgentFilter, ip_address: ip };
|
const appFilter = { ...siteFilter, ...strictAgentFilter, ip_address: ip };
|
||||||
|
if (tf) {
|
||||||
|
appFilter.timestamp = tf;
|
||||||
|
threatQuery.timestamp = tf;
|
||||||
|
}
|
||||||
|
|
||||||
const [deviceAppStats, flowsQuery, rawThreats] = await Promise.all([
|
const [deviceAppStats, flowsQuery, rawThreats] = await Promise.all([
|
||||||
ip ? DeviceAppStat.find(appFilter).sort({ timestamp: -1 }).lean() : [],
|
ip ? DeviceAppStat.find(appFilter).sort({ timestamp: -1 }).lean() : [],
|
||||||
@@ -157,8 +162,18 @@ module.exports = async function deviceDetailsHandler(req, res, helpers) {
|
|||||||
agentUuid = deviceAppStats[0]?.agent_uuid || flowsQuery[0]?.agent_uuid || agentUuid;
|
agentUuid = deviceAppStats[0]?.agent_uuid || flowsQuery[0]?.agent_uuid || agentUuid;
|
||||||
const appsDl = apps.reduce((s, a) => s + (a.download || 0), 0);
|
const appsDl = apps.reduce((s, a) => s + (a.download || 0), 0);
|
||||||
const appsUl = apps.reduce((s, a) => s + (a.upload || 0), 0);
|
const appsUl = apps.reduce((s, a) => s + (a.upload || 0), 0);
|
||||||
const totalDownload = Math.max(device?.download || 0, appsDl);
|
let totalDownload = appsDl;
|
||||||
const totalUpload = Math.max(device?.upload || 0, appsUl);
|
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 ───────────────────────────────────────────────────────
|
// ── Device metadata ───────────────────────────────────────────────────────
|
||||||
const flowMac = flowsQuery.find(f => f.src_ip === ip && f.src_mac && !f.src_mac.startsWith('00:16:3e:'))?.src_mac;
|
const flowMac = flowsQuery.find(f => f.src_ip === ip && f.src_mac && !f.src_mac.startsWith('00:16:3e:'))?.src_mac;
|
||||||
|
|||||||
@@ -0,0 +1,232 @@
|
|||||||
|
// backend/utils/categoryDictionary.js
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
// Category Dictionary & Resolvers for BackOne DPI
|
||||||
|
// Maps category IDs, tags, and app labels to human-readable categories.
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const CATEGORY_ID_MAP = {
|
||||||
|
'1': 'Unclassified',
|
||||||
|
'2': 'Adult',
|
||||||
|
'3': 'Advertiser',
|
||||||
|
'4': 'Arts and Entertainment',
|
||||||
|
'5': 'Business',
|
||||||
|
'6': 'Career and Education',
|
||||||
|
'9': 'Financial',
|
||||||
|
'10': 'File Sharing',
|
||||||
|
'11': 'Gambling',
|
||||||
|
'12': 'Games',
|
||||||
|
'13': 'Government',
|
||||||
|
'15': 'Mail',
|
||||||
|
'16': 'Malware',
|
||||||
|
'17': 'Messaging',
|
||||||
|
'18': 'News',
|
||||||
|
'19': 'Portal',
|
||||||
|
'20': 'Recreation',
|
||||||
|
'21': 'Reference',
|
||||||
|
'23': 'Shopping',
|
||||||
|
'24': 'Social Media',
|
||||||
|
'26': 'Sports',
|
||||||
|
'27': 'Technology',
|
||||||
|
'28': 'VPN and Proxy',
|
||||||
|
'29': 'Streaming Media',
|
||||||
|
'30': 'Cybersecurity',
|
||||||
|
'31': 'OS/Software Updates',
|
||||||
|
'32': 'VoIP/Conferencing',
|
||||||
|
'33': 'Device/IoT',
|
||||||
|
'34': 'Remote Desktop',
|
||||||
|
'35': 'CDN',
|
||||||
|
'36': 'Hosting',
|
||||||
|
'37': 'ISP/Telco',
|
||||||
|
'40': 'Identified'
|
||||||
|
};
|
||||||
|
|
||||||
|
const APP_CATEGORY_MAP = {
|
||||||
|
// Streaming Media
|
||||||
|
'youtube': 'Streaming Media',
|
||||||
|
'netflix': 'Streaming Media',
|
||||||
|
'spotify': 'Streaming Media',
|
||||||
|
'twitch': 'Streaming Media',
|
||||||
|
'disney': 'Streaming Media',
|
||||||
|
'disney-plus': 'Streaming Media',
|
||||||
|
'googlevideo': 'Streaming Media',
|
||||||
|
'vimeo': 'Streaming Media',
|
||||||
|
'soundcloud': 'Streaming Media',
|
||||||
|
'tiktokv': 'Streaming Media',
|
||||||
|
'bigo': 'Streaming Media',
|
||||||
|
'vidio': 'Streaming Media',
|
||||||
|
|
||||||
|
// Social Media
|
||||||
|
'facebook': 'Social Media',
|
||||||
|
'instagram': 'Social Media',
|
||||||
|
'tiktok': 'Social Media',
|
||||||
|
'twitter': 'Social Media',
|
||||||
|
'x': 'Social Media',
|
||||||
|
'threads': 'Social Media',
|
||||||
|
'reddit': 'Social Media',
|
||||||
|
'pinterest': 'Social Media',
|
||||||
|
'linkedin': 'Social Media',
|
||||||
|
'snapchat': 'Social Media',
|
||||||
|
|
||||||
|
// Messaging
|
||||||
|
'whatsapp': 'Messaging',
|
||||||
|
'telegram': 'Messaging',
|
||||||
|
'discord': 'Messaging',
|
||||||
|
'slack': 'Messaging',
|
||||||
|
'signal': 'Messaging',
|
||||||
|
'signalr': 'Messaging',
|
||||||
|
'line': 'Messaging',
|
||||||
|
'wechat': 'Messaging',
|
||||||
|
'messenger': 'Messaging',
|
||||||
|
|
||||||
|
// VoIP / Conferencing
|
||||||
|
'zoom': 'VoIP/Conferencing',
|
||||||
|
'teams': 'VoIP/Conferencing',
|
||||||
|
'skype': 'VoIP/Conferencing',
|
||||||
|
'webex': 'VoIP/Conferencing',
|
||||||
|
'google-meet': 'VoIP/Conferencing',
|
||||||
|
|
||||||
|
// Technology
|
||||||
|
'google': 'Technology',
|
||||||
|
'google-drive': 'Technology',
|
||||||
|
'google-ads': 'Technology',
|
||||||
|
'google-play': 'Technology',
|
||||||
|
'microsoft': 'Technology',
|
||||||
|
'apple': 'Technology',
|
||||||
|
'apple-updates': 'Technology',
|
||||||
|
'bytedance': 'Technology',
|
||||||
|
'yahoo': 'Technology',
|
||||||
|
'bing': 'Technology',
|
||||||
|
|
||||||
|
// CDN
|
||||||
|
'cloudflare': 'CDN',
|
||||||
|
'akamai': 'CDN',
|
||||||
|
'fastly': 'CDN',
|
||||||
|
'cdn77': 'CDN',
|
||||||
|
'edgecast': 'CDN',
|
||||||
|
|
||||||
|
// Hosting / Cloud
|
||||||
|
'amazon': 'Hosting',
|
||||||
|
'amazon-aws': 'Hosting',
|
||||||
|
'amazon-s3': 'Hosting',
|
||||||
|
'amazon-cloudfront': 'CDN',
|
||||||
|
'aws': 'Hosting',
|
||||||
|
'azure': 'Hosting',
|
||||||
|
'digitalocean': 'Hosting',
|
||||||
|
|
||||||
|
// Games
|
||||||
|
'steam': 'Games',
|
||||||
|
'epic': 'Games',
|
||||||
|
'roblox': 'Games',
|
||||||
|
'riot': 'Games',
|
||||||
|
'riot-games': 'Games',
|
||||||
|
'valorant': 'Games',
|
||||||
|
'garena': 'Games',
|
||||||
|
'genshin': 'Games',
|
||||||
|
'moonton': 'Games',
|
||||||
|
'netease': 'Games',
|
||||||
|
'netease-games': 'Games',
|
||||||
|
'unity': 'Games',
|
||||||
|
'playstation': 'Games',
|
||||||
|
'xbox': 'Games',
|
||||||
|
|
||||||
|
// Shopping
|
||||||
|
'shopee': 'Shopping',
|
||||||
|
'shopeepay': 'Shopping',
|
||||||
|
'tokopedia': 'Shopping',
|
||||||
|
'lazada': 'Shopping',
|
||||||
|
'bukalapak': 'Shopping',
|
||||||
|
'blibli': 'Shopping',
|
||||||
|
'ebay': 'Shopping',
|
||||||
|
'alibaba': 'Shopping',
|
||||||
|
'aliexpress': 'Shopping',
|
||||||
|
|
||||||
|
// Financial
|
||||||
|
'bca': 'Financial',
|
||||||
|
'mandiri': 'Financial',
|
||||||
|
'bri': 'Financial',
|
||||||
|
'bni': 'Financial',
|
||||||
|
'cimb': 'Financial',
|
||||||
|
'paypal': 'Financial',
|
||||||
|
'stripe': 'Financial',
|
||||||
|
|
||||||
|
// OS / Updates
|
||||||
|
'windowsupdate': 'OS/Software Updates',
|
||||||
|
'android': 'OS/Software Updates',
|
||||||
|
|
||||||
|
// Remote Desktop
|
||||||
|
'anydesk': 'Remote Desktop',
|
||||||
|
'teamviewer': 'Remote Desktop',
|
||||||
|
'rdp': 'Remote Desktop',
|
||||||
|
'ssh': 'Remote Desktop',
|
||||||
|
'vnc': 'Remote Desktop',
|
||||||
|
|
||||||
|
// Network Infrastructure
|
||||||
|
'dns': 'Network Infrastructure',
|
||||||
|
'ntp': 'Network Infrastructure',
|
||||||
|
'dhcp': 'Network Infrastructure',
|
||||||
|
'icmp': 'Network Infrastructure',
|
||||||
|
'reverse-dns': 'Network Infrastructure',
|
||||||
|
'root-servers': 'Network Infrastructure',
|
||||||
|
'dyn-ddns': 'Network Infrastructure',
|
||||||
|
|
||||||
|
// Development
|
||||||
|
'github': 'Technology',
|
||||||
|
'gitlab': 'Technology',
|
||||||
|
};
|
||||||
|
|
||||||
|
function resolveAppCategory(appLabel, lookupMap = {}) {
|
||||||
|
if (!appLabel || appLabel === 'Unknown' || appLabel === 'backone.unclassified' || appLabel === 'netify.unclassified') {
|
||||||
|
return 'Unclassified';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Check exact match in lookupMap (which contains LookupApp entries)
|
||||||
|
if (lookupMap[appLabel]?.category) {
|
||||||
|
return lookupMap[appLabel].category;
|
||||||
|
}
|
||||||
|
if (typeof lookupMap[appLabel] === 'string') {
|
||||||
|
return lookupMap[appLabel];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Clean prefix
|
||||||
|
const clean = String(appLabel).toLowerCase().replace(/^(?:backone|netify|siab|nexus)\./i, '');
|
||||||
|
|
||||||
|
if (lookupMap[clean]?.category) {
|
||||||
|
return lookupMap[clean].category;
|
||||||
|
}
|
||||||
|
if (typeof lookupMap[clean] === 'string') {
|
||||||
|
return lookupMap[clean];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Fallback dictionary by exact clean key
|
||||||
|
if (APP_CATEGORY_MAP[clean]) {
|
||||||
|
return APP_CATEGORY_MAP[clean];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Substring match against known apps
|
||||||
|
for (const [key, cat] of Object.entries(APP_CATEGORY_MAP)) {
|
||||||
|
if (clean.includes(key)) return cat;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Port-based categories
|
||||||
|
if (/^(?:port\s+)?(\d+)$/i.test(clean)) {
|
||||||
|
const port = parseInt(clean.replace(/^(?:port\s+)?/i, ''), 10);
|
||||||
|
if ([80, 443, 8080, 8443].includes(port)) return 'Technology';
|
||||||
|
if ([53, 67, 68, 123, 161, 162].includes(port)) return 'Network Infrastructure';
|
||||||
|
if ([22, 23, 3389, 5900].includes(port)) return 'Remote Desktop';
|
||||||
|
if ([25, 110, 143, 465, 587, 993, 995].includes(port)) return 'Mail';
|
||||||
|
return 'General Traffic';
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'General Traffic';
|
||||||
|
}
|
||||||
|
|
||||||
|
function getAppCategoryFallback(appLabel) {
|
||||||
|
return resolveAppCategory(appLabel, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
CATEGORY_ID_MAP,
|
||||||
|
APP_CATEGORY_MAP,
|
||||||
|
resolveAppCategory,
|
||||||
|
getAppCategoryFallback
|
||||||
|
};
|
||||||
@@ -30,7 +30,7 @@ services:
|
|||||||
- BACKONE_INFORMATICS_BASE_URL=${NETIFY_INFORMATICS_BASE_URL}
|
- BACKONE_INFORMATICS_BASE_URL=${NETIFY_INFORMATICS_BASE_URL}
|
||||||
|
|
||||||
frontend:
|
frontend:
|
||||||
image: git.proit.id/ypratama/deep-package-inspection/backone-frontend:v2
|
image: git.proit.id/ypratama/deep-package-inspection/backone-frontend:latest
|
||||||
container_name: backone_frontend_prod
|
container_name: backone_frontend_prod
|
||||||
restart: always
|
restart: always
|
||||||
ports:
|
ports:
|
||||||
|
|||||||
@@ -224,10 +224,16 @@ async function syncApplicationDictionary() {
|
|||||||
icon: app.icon || app.application?.icon || null,
|
icon: app.icon || app.application?.icon || null,
|
||||||
logo: app.logo || app.application?.logo || null,
|
logo: app.logo || app.application?.logo || null,
|
||||||
application_category: {
|
application_category: {
|
||||||
id: app.application_category?.id,
|
id: app.category?.id || app.application_category?.id || null,
|
||||||
name: app.application_category?.name,
|
name: app.category?.name || app.application_category?.name || app.category?.label || null,
|
||||||
label: app.application_category?.label,
|
label: app.category?.label || app.application_category?.label || null,
|
||||||
tag: app.application_category?.tag
|
tag: app.category?.tag || app.application_category?.tag || null
|
||||||
|
},
|
||||||
|
category: {
|
||||||
|
id: app.category?.id || app.application_category?.id || null,
|
||||||
|
name: app.category?.name || app.application_category?.name || app.category?.label || null,
|
||||||
|
label: app.category?.label || app.application_category?.label || null,
|
||||||
|
tag: app.category?.tag || app.application_category?.tag || null
|
||||||
}
|
}
|
||||||
})));
|
})));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect, useMemo } from "react";
|
||||||
import { TimestampCell } from "@/components/ui/TimestampCell";
|
import { TimestampCell } from "@/components/ui/TimestampCell";
|
||||||
import { AppStat } from "@/lib/api";
|
import { AppStat } from "@/lib/api";
|
||||||
import { useTopApps } from "@/lib/api-with-context";
|
import { useTopApps } from "@/lib/api-with-context";
|
||||||
@@ -31,9 +31,14 @@ export default function AppsPage() {
|
|||||||
document.title = "Apps | BackOne - Deep Package Inspection";
|
document.title = "Apps | BackOne - Deep Package Inspection";
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
if (!mounted) return null;
|
const all = useMemo(() => {
|
||||||
|
return (data || []).map((r: any) => ({
|
||||||
const all = data || [];
|
...r,
|
||||||
|
app_label: (r.app_label || "")
|
||||||
|
.replace(/\b(?:netify|siab|nexus)\.unclassified/gi, "backone.unclassified")
|
||||||
|
.replace(/\b(?:netify|siab|nexus)\.(?!ai)/gi, "backone."),
|
||||||
|
}));
|
||||||
|
}, [data]);
|
||||||
|
|
||||||
const opts = (key: string) => {
|
const opts = (key: string) => {
|
||||||
const raw = Array.from(new Set(all.map((r: any) => String(r[key] || "")).filter(Boolean)));
|
const raw = Array.from(new Set(all.map((r: any) => String(r[key] || "")).filter(Boolean)));
|
||||||
@@ -127,6 +132,9 @@ export default function AppsPage() {
|
|||||||
accessor: (row) => <span className="font-medium text-white">{fmtBytes(row.download + row.upload)}</span>
|
accessor: (row) => <span className="font-medium text-white">{fmtBytes(row.download + row.upload)}</span>
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
if (!mounted) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
|
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
|
||||||
@@ -189,7 +197,7 @@ export default function AppsPage() {
|
|||||||
<ResponsiveContainer width="100%" height="100%">
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
<BarChart data={top5} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
|
<BarChart data={top5} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
|
||||||
<CartesianGrid strokeDasharray="3 3" stroke="#30363d" vertical={false} />
|
<CartesianGrid strokeDasharray="3 3" stroke="#30363d" vertical={false} />
|
||||||
<XAxis dataKey="app_label" stroke="#8b949e" tickLine={false} axisLine={false} />
|
<XAxis dataKey="app_label" stroke="#8b949e" tickLine={false} axisLine={false} tickFormatter={formatAppLabel} />
|
||||||
<YAxis
|
<YAxis
|
||||||
stroke="#8b949e"
|
stroke="#8b949e"
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
@@ -221,6 +229,7 @@ export default function AppsPage() {
|
|||||||
<DataTable
|
<DataTable
|
||||||
data={processedData}
|
data={processedData}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
|
pageSize={20}
|
||||||
searchPlaceholder="Search by application or category..."
|
searchPlaceholder="Search by application or category..."
|
||||||
searchFilter={(row, query) => {
|
searchFilter={(row, query) => {
|
||||||
const q = query.toLowerCase();
|
const q = query.toLowerCase();
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ export default function DNSPage() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (selectedDomain) {
|
if (selectedDomain) {
|
||||||
setIsDetailLoading(true);
|
setIsDetailLoading(true);
|
||||||
fetch(`http://localhost:4000/domain-details?domain=${encodeURIComponent(selectedDomain)}`)
|
fetch(`/api/dashboard/domain-details?domain=${encodeURIComponent(selectedDomain)}`)
|
||||||
.then(res => res.json())
|
.then(res => res.json())
|
||||||
.then(data => {
|
.then(data => {
|
||||||
if (data.ok) {
|
if (data.ok) {
|
||||||
@@ -133,6 +133,7 @@ export default function DNSPage() {
|
|||||||
<DataTable
|
<DataTable
|
||||||
data={filteredData}
|
data={filteredData}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
|
pageSize={20}
|
||||||
searchPlaceholder="Search by domain, application, or category..."
|
searchPlaceholder="Search by domain, application, or category..."
|
||||||
onRowClick={(row) => setSelectedDomain(row.domain)}
|
onRowClick={(row) => setSelectedDomain(row.domain)}
|
||||||
searchFilter={(row, query) => {
|
searchFilter={(row, query) => {
|
||||||
|
|||||||
@@ -214,7 +214,7 @@ function EventsContent() {
|
|||||||
? "bg-yellow-500/10 border-l-2 border-yellow-500 animate-pulse font-semibold"
|
? "bg-yellow-500/10 border-l-2 border-yellow-500 animate-pulse font-semibold"
|
||||||
: "";
|
: "";
|
||||||
}}
|
}}
|
||||||
pageSize={50}
|
pageSize={20}
|
||||||
/>
|
/>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ export default function FlowsPage() {
|
|||||||
}, [filters, dateFrom, dateTo, debouncedSearch]);
|
}, [filters, dateFrom, dateTo, debouncedSearch]);
|
||||||
|
|
||||||
const { data: optionsData } = useFlowsOptions();
|
const { data: optionsData } = useFlowsOptions();
|
||||||
const { data: flows = [], total = 0, isLoading } = useFlows(currentPage, 50, {
|
const { data: flows = [], total = 0, isLoading } = useFlows(currentPage, 20, {
|
||||||
...filters,
|
...filters,
|
||||||
dateFrom,
|
dateFrom,
|
||||||
dateTo,
|
dateTo,
|
||||||
@@ -162,6 +162,7 @@ export default function FlowsPage() {
|
|||||||
<DataTable
|
<DataTable
|
||||||
data={flows}
|
data={flows}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
|
pageSize={20}
|
||||||
serverSide={true}
|
serverSide={true}
|
||||||
totalCount={total}
|
totalCount={total}
|
||||||
currentPage={currentPage}
|
currentPage={currentPage}
|
||||||
|
|||||||
@@ -133,7 +133,7 @@ export default function NetworkIntelligencePage() {
|
|||||||
<DataTable
|
<DataTable
|
||||||
data={processedData}
|
data={processedData}
|
||||||
columns={appCols}
|
columns={appCols}
|
||||||
pageSize={50}
|
pageSize={20}
|
||||||
onRowClick={(row) => setSelectedCategory(row.category_label)}
|
onRowClick={(row) => setSelectedCategory(row.category_label)}
|
||||||
/>
|
/>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|||||||
@@ -130,7 +130,9 @@ export default function SummaryPage() {
|
|||||||
dest: GeoLocation,
|
dest: GeoLocation,
|
||||||
downloadBytes: number,
|
downloadBytes: number,
|
||||||
uploadBytes: number,
|
uploadBytes: number,
|
||||||
countryCode: string
|
countryCode: string,
|
||||||
|
topIps?: any[],
|
||||||
|
topDomains?: any[]
|
||||||
) => {
|
) => {
|
||||||
const dl = downloadBytes || 0;
|
const dl = downloadBytes || 0;
|
||||||
const ul = uploadBytes || 0;
|
const ul = uploadBytes || 0;
|
||||||
@@ -148,6 +150,8 @@ export default function SummaryPage() {
|
|||||||
countryCode,
|
countryCode,
|
||||||
direction: 'outbound',
|
direction: 'outbound',
|
||||||
curveSign: 1,
|
curveSign: 1,
|
||||||
|
topIps: topIps || [],
|
||||||
|
topDomains: topDomains || [],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (dl > 0) {
|
if (dl > 0) {
|
||||||
@@ -164,6 +168,8 @@ export default function SummaryPage() {
|
|||||||
countryCode,
|
countryCode,
|
||||||
direction: 'inbound',
|
direction: 'inbound',
|
||||||
curveSign: -0.65,
|
curveSign: -0.65,
|
||||||
|
topIps: topIps || [],
|
||||||
|
topDomains: topDomains || [],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -177,17 +183,17 @@ export default function SummaryPage() {
|
|||||||
|
|
||||||
if (activeAgentUuid) {
|
if (activeAgentUuid) {
|
||||||
const origin = resolveOriginForAgent(activeAgentUuid, activeAgentLabel);
|
const origin = resolveOriginForAgent(activeAgentUuid, activeAgentLabel);
|
||||||
pushBidirectionalArcs(origin, dest, row.download, row.upload, row.country_code);
|
pushBidirectionalArcs(origin, dest, row.download, row.upload, row.country_code, row.top_ips, row.top_domains);
|
||||||
} else if (Array.isArray(row.agent_breakdown) && row.agent_breakdown.length > 0) {
|
} else if (Array.isArray(row.agent_breakdown) && row.agent_breakdown.length > 0) {
|
||||||
for (const ag of row.agent_breakdown) {
|
for (const ag of row.agent_breakdown) {
|
||||||
const agTraffic = (ag.download || 0) + (ag.upload || 0);
|
const agTraffic = (ag.download || 0) + (ag.upload || 0);
|
||||||
if (agTraffic === 0) continue;
|
if (agTraffic === 0) continue;
|
||||||
const origin = resolveOriginForAgent(ag.agent_uuid);
|
const origin = resolveOriginForAgent(ag.agent_uuid);
|
||||||
pushBidirectionalArcs(origin, dest, ag.download, ag.upload, row.country_code);
|
pushBidirectionalArcs(origin, dest, ag.download, ag.upload, row.country_code, row.top_ips, row.top_domains);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const origin = resolveOriginForAgent(null);
|
const origin = resolveOriginForAgent(null);
|
||||||
pushBidirectionalArcs(origin, dest, row.download, row.upload, row.country_code);
|
pushBidirectionalArcs(origin, dest, row.download, row.upload, row.country_code, row.top_ips, row.top_domains);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ export function CategoryDetailPanel({
|
|||||||
const [activeTab, setActiveTab] = useState<"apps" | "devices">("apps");
|
const [activeTab, setActiveTab] = useState<"apps" | "devices">("apps");
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
const [isMounted, setIsMounted] = useState(false);
|
const [isMounted, setIsMounted] = useState(false);
|
||||||
const PAGE_SIZE = 25;
|
const PAGE_SIZE = 20;
|
||||||
|
|
||||||
const handleClose = useCallback(() => {
|
const handleClose = useCallback(() => {
|
||||||
setIsClosing(true);
|
setIsClosing(true);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
import { fetchAgentDetails, AgentDetails } from "@/lib/api";
|
import { fetchAgentDetails, AgentDetails } from "@/lib/api";
|
||||||
import { fmtBytes, getAppFavicon } from "@/lib/utils";
|
import { fmtBytes, getAppFavicon } from "@/lib/utils";
|
||||||
import { DeviceDetailModal } from "@/components/ui/DeviceDetailModal";
|
import { DeviceDetailModal } from "@/components/ui/DeviceDetailModal";
|
||||||
@@ -37,6 +38,15 @@ export function AgentDetailModal({ agentUuid, agentLabel, onClose }: Props) {
|
|||||||
const [selectedDevice, setSelectedDevice] = useState<{ ip: string; label: string | null; mac: string | null; agent_uuid?: string } | null>(null);
|
const [selectedDevice, setSelectedDevice] = useState<{ ip: string; label: string | null; mac: string | null; agent_uuid?: string } | null>(null);
|
||||||
const [isClosing, setIsClosing] = useState(false);
|
const [isClosing, setIsClosing] = useState(false);
|
||||||
const [selectedAppLabel, setSelectedAppLabel] = useState<string | null>(null);
|
const [selectedAppLabel, setSelectedAppLabel] = useState<string | null>(null);
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setMounted(true);
|
||||||
|
document.body.style.overflow = "hidden";
|
||||||
|
return () => {
|
||||||
|
document.body.style.overflow = "unset";
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
const handleClose = () => {
|
const handleClose = () => {
|
||||||
setIsClosing(true);
|
setIsClosing(true);
|
||||||
@@ -77,7 +87,9 @@ export function AgentDetailModal({ agentUuid, agentLabel, onClose }: Props) {
|
|||||||
{ key: "telemetry", label: "Telemetry", icon: <LineChart className="w-3.5 h-3.5" /> },
|
{ key: "telemetry", label: "Telemetry", icon: <LineChart className="w-3.5 h-3.5" /> },
|
||||||
];
|
];
|
||||||
|
|
||||||
return (
|
if (!mounted) return null;
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
<>
|
<>
|
||||||
<div className="fixed inset-0 z-[9999] flex items-center justify-center p-4" onClick={handleClose}>
|
<div className="fixed inset-0 z-[9999] flex items-center justify-center p-4" onClick={handleClose}>
|
||||||
<div className={`absolute inset-0 bg-black/40 dark:bg-black/75 backdrop-blur-sm ${isClosing ? 'animate-overlay-out' : 'animate-overlay-in'}`} />
|
<div className={`absolute inset-0 bg-black/40 dark:bg-black/75 backdrop-blur-sm ${isClosing ? 'animate-overlay-out' : 'animate-overlay-in'}`} />
|
||||||
@@ -229,6 +241,7 @@ export function AgentDetailModal({ agentUuid, agentLabel, onClose }: Props) {
|
|||||||
onClose={() => setSelectedAppLabel(null)}
|
onClose={() => setSelectedAppLabel(null)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</>
|
</>,
|
||||||
|
document.body
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
import { fetchAppDetails, AppDetails } from "@/lib/api";
|
import { fetchAppDetails, AppDetails } from "@/lib/api";
|
||||||
import { useTimeFilter } from "@/contexts/TimeFilterContext";
|
import { useTimeFilter } from "@/contexts/TimeFilterContext";
|
||||||
import { fmtBytes } from "@/lib/utils";
|
import { fmtBytes } from "@/lib/utils";
|
||||||
@@ -63,11 +64,20 @@ export function AppDetailModal({ appLabel, favicon, category, agentUuid, onClose
|
|||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [isClosing, setIsClosing] = useState(false);
|
const [isClosing, setIsClosing] = useState(false);
|
||||||
const [selectedIp, setSelectedIp] = useState<string | null>(null);
|
const [selectedIp, setSelectedIp] = useState<string | null>(null);
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
const { timeRange } = useTimeFilter();
|
const { timeRange } = useTimeFilter();
|
||||||
|
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
const pageSize = 50;
|
const pageSize = 50;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setMounted(true);
|
||||||
|
document.body.style.overflow = "hidden";
|
||||||
|
return () => {
|
||||||
|
document.body.style.overflow = "unset";
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
const handleClose = () => {
|
const handleClose = () => {
|
||||||
setIsClosing(true);
|
setIsClosing(true);
|
||||||
setTimeout(() => { onClose(); }, 480);
|
setTimeout(() => { onClose(); }, 480);
|
||||||
@@ -88,7 +98,9 @@ export function AppDetailModal({ appLabel, favicon, category, agentUuid, onClose
|
|||||||
const startIndex = (page - 1) * pageSize;
|
const startIndex = (page - 1) * pageSize;
|
||||||
const paginatedIps = topIps.slice(startIndex, startIndex + pageSize);
|
const paginatedIps = topIps.slice(startIndex, startIndex + pageSize);
|
||||||
|
|
||||||
return (
|
if (!mounted) return null;
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
<>
|
<>
|
||||||
<div className="fixed inset-0 z-[9999] flex items-center justify-center p-4" onClick={handleClose}>
|
<div className="fixed inset-0 z-[9999] flex items-center justify-center p-4" onClick={handleClose}>
|
||||||
<div className={`absolute inset-0 bg-black/40 dark:bg-black/75 backdrop-blur-sm ${isClosing ? 'animate-overlay-out' : 'animate-overlay-in'}`} />
|
<div className={`absolute inset-0 bg-black/40 dark:bg-black/75 backdrop-blur-sm ${isClosing ? 'animate-overlay-out' : 'animate-overlay-in'}`} />
|
||||||
@@ -210,6 +222,7 @@ export function AppDetailModal({ appLabel, favicon, category, agentUuid, onClose
|
|||||||
onClose={() => setSelectedIp(null)}
|
onClose={() => setSelectedIp(null)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</>
|
</>,
|
||||||
|
document.body
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -41,7 +41,7 @@ export function DataTable<T>({
|
|||||||
searchFilter,
|
searchFilter,
|
||||||
isLoading,
|
isLoading,
|
||||||
getRowClassName,
|
getRowClassName,
|
||||||
pageSize = 50,
|
pageSize = 20,
|
||||||
csvExport,
|
csvExport,
|
||||||
pdfExport,
|
pdfExport,
|
||||||
onRowClick,
|
onRowClick,
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
import { fetchDeviceDetails, DeviceDetails, DeviceStat } from "@/lib/api";
|
import { fetchDeviceDetails, DeviceDetails, DeviceStat } from "@/lib/api";
|
||||||
|
import { useTimeFilter } from "@/contexts/TimeFilterContext";
|
||||||
import { fmtBytes } from "@/lib/utils";
|
import { fmtBytes } from "@/lib/utils";
|
||||||
import { Loader2, X, Monitor, Activity, Shield, Box, Server, Cpu, Clock, HardDrive, ArrowDownToLine, ArrowUpFromLine, RefreshCcw, Globe, Link2 } from "lucide-react";
|
import { Loader2, X, Monitor, Activity, Shield, Box, Server, Cpu, Clock, HardDrive, ArrowDownToLine, ArrowUpFromLine, RefreshCcw, Globe, Link2, ChevronDown } from "lucide-react";
|
||||||
import ActiveDurationDisplay from "./ActiveDurationDisplay";
|
import ActiveDurationDisplay from "./ActiveDurationDisplay";
|
||||||
import DeviceAppsTab from "./DeviceAppsTab";
|
import DeviceAppsTab from "./DeviceAppsTab";
|
||||||
import DeviceProtocolsTab from "./DeviceProtocolsTab";
|
import DeviceProtocolsTab from "./DeviceProtocolsTab";
|
||||||
@@ -19,6 +21,16 @@ interface Props {
|
|||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MODAL_TIME_OPTIONS = [
|
||||||
|
{ value: "5m", label: "Last 5 Minutes" },
|
||||||
|
{ value: "30m", label: "Last 30 Minutes" },
|
||||||
|
{ value: "1h", label: "Last 1 Hour" },
|
||||||
|
{ value: "1d", label: "Last 24 Hours" },
|
||||||
|
{ value: "7d", label: "Last 7 Days" },
|
||||||
|
{ value: "30d", label: "Last 30 Days" },
|
||||||
|
{ value: "all", label: "All Time" },
|
||||||
|
] as const;
|
||||||
|
|
||||||
type Tab = "info" | "apps" | "protocols" | "domains" | "flows" | "threats";
|
type Tab = "info" | "apps" | "protocols" | "domains" | "flows" | "threats";
|
||||||
|
|
||||||
const tabs: { id: Tab; label: string; icon: any }[] = [
|
const tabs: { id: Tab; label: string; icon: any }[] = [
|
||||||
@@ -31,6 +43,11 @@ const tabs: { id: Tab; label: string; icon: any }[] = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
export function DeviceDetailModal({ ip, mac = '', deviceData, onClose }: Props) {
|
export function DeviceDetailModal({ ip, mac = '', deviceData, onClose }: Props) {
|
||||||
|
const { timeRange: globalTimeRange } = useTimeFilter();
|
||||||
|
const [currentTimeRange, setCurrentTimeRange] = useState<string>(globalTimeRange || '1d');
|
||||||
|
const [isTimeDropdownOpen, setIsTimeDropdownOpen] = useState(false);
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
|
|
||||||
const [data, setData] = useState<DeviceDetails | null>(null);
|
const [data, setData] = useState<DeviceDetails | null>(null);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||||
@@ -38,18 +55,32 @@ export function DeviceDetailModal({ ip, mac = '', deviceData, onClose }: Props)
|
|||||||
const [isClosing, setIsClosing] = useState(false);
|
const [isClosing, setIsClosing] = useState(false);
|
||||||
const [activeTab, setActiveTab] = useState<Tab>("info");
|
const [activeTab, setActiveTab] = useState<Tab>("info");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setMounted(true);
|
||||||
|
document.body.style.overflow = "hidden";
|
||||||
|
return () => {
|
||||||
|
document.body.style.overflow = "unset";
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (globalTimeRange) {
|
||||||
|
setCurrentTimeRange(globalTimeRange);
|
||||||
|
}
|
||||||
|
}, [globalTimeRange]);
|
||||||
|
|
||||||
const handleClose = () => {
|
const handleClose = () => {
|
||||||
setIsClosing(true);
|
setIsClosing(true);
|
||||||
setTimeout(() => onClose(), 480);
|
setTimeout(() => onClose(), 480);
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadData = async (silent = false) => {
|
const loadData = async (silent = false, range = currentTimeRange) => {
|
||||||
if (!silent) setIsLoading(true);
|
if (!silent) setIsLoading(true);
|
||||||
else setIsRefreshing(true);
|
else setIsRefreshing(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const agentUuid = deviceData?.agent_uuid || '';
|
const agentUuid = deviceData?.agent_uuid || '';
|
||||||
const res = await fetchDeviceDetails(ip, 'all', mac, agentUuid);
|
const res = await fetchDeviceDetails(ip, range, mac, agentUuid);
|
||||||
setData(res);
|
setData(res);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
if (!silent) setError(e.message);
|
if (!silent) setError(e.message);
|
||||||
@@ -60,8 +91,8 @@ export function DeviceDetailModal({ ip, mac = '', deviceData, onClose }: Props)
|
|||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadData(false);
|
loadData(false, currentTimeRange);
|
||||||
}, [ip, mac]);
|
}, [ip, mac, currentTimeRange]);
|
||||||
|
|
||||||
const [isExporting, setIsExporting] = useState(false);
|
const [isExporting, setIsExporting] = useState(false);
|
||||||
|
|
||||||
@@ -93,8 +124,10 @@ export function DeviceDetailModal({ ip, mac = '', deviceData, onClose }: Props)
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
if (!mounted) return null;
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4" onClick={handleClose}>
|
|
||||||
|
return createPortal(
|
||||||
|
<div className="fixed inset-0 z-[9999] flex items-center justify-center p-4" onClick={handleClose}>
|
||||||
<div className={`absolute inset-0 bg-black/60 backdrop-blur-md ${isClosing ? 'animate-overlay-out' : 'animate-overlay-in'}`} />
|
<div className={`absolute inset-0 bg-black/60 backdrop-blur-md ${isClosing ? 'animate-overlay-out' : 'animate-overlay-in'}`} />
|
||||||
<div
|
<div
|
||||||
className={`relative bg-card border border-border rounded-3xl w-full max-w-5xl h-[85vh] flex flex-col shadow-2xl shadow-black/10 dark:shadow-blue-900/20 overflow-hidden backdrop-blur-xl ${isClosing ? 'animate-modal-out' : 'animate-modal-in'}`}
|
className={`relative bg-card border border-border rounded-3xl w-full max-w-5xl h-[85vh] flex flex-col shadow-2xl shadow-black/10 dark:shadow-blue-900/20 overflow-hidden backdrop-blur-xl ${isClosing ? 'animate-modal-out' : 'animate-modal-in'}`}
|
||||||
@@ -133,12 +166,54 @@ export function DeviceDetailModal({ ip, mac = '', deviceData, onClose }: Props)
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center justify-between sm:justify-end gap-3 flex-shrink-0 w-full sm:w-auto border-t border-border/40 pt-3 sm:border-t-0 sm:pt-0">
|
<div className="flex items-center justify-between sm:justify-end gap-2.5 flex-shrink-0 w-full sm:w-auto border-t border-border/40 pt-3 sm:border-t-0 sm:pt-0">
|
||||||
|
{/* Time Filter Selector in Modal */}
|
||||||
|
<div className="relative">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setIsTimeDropdownOpen(!isTimeDropdownOpen)}
|
||||||
|
className="flex items-center gap-1.5 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg sm:rounded-xl text-xs font-semibold bg-secondary/80 hover:bg-secondary text-card-foreground border border-border transition-all shadow-sm cursor-pointer"
|
||||||
|
title="Filter time range"
|
||||||
|
>
|
||||||
|
<Clock className="w-3.5 h-3.5 text-blue-500" />
|
||||||
|
<span className="truncate max-w-[110px] sm:max-w-[140px]">
|
||||||
|
{MODAL_TIME_OPTIONS.find(o => o.value === currentTimeRange)?.label || currentTimeRange}
|
||||||
|
</span>
|
||||||
|
<ChevronDown className={`w-3 h-3 text-muted-foreground transition-transform duration-200 ${isTimeDropdownOpen ? 'rotate-180' : ''}`} />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{isTimeDropdownOpen && (
|
||||||
|
<>
|
||||||
|
<div className="fixed inset-0 z-[10000]" onClick={() => setIsTimeDropdownOpen(false)} />
|
||||||
|
<div className="absolute right-0 top-full mt-1.5 z-[10001] w-44 rounded-xl border border-border bg-card/95 backdrop-blur-xl p-1 shadow-2xl origin-top-right">
|
||||||
|
{MODAL_TIME_OPTIONS.map((opt) => (
|
||||||
|
<button
|
||||||
|
key={opt.value}
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setCurrentTimeRange(opt.value);
|
||||||
|
setIsTimeDropdownOpen(false);
|
||||||
|
}}
|
||||||
|
className={`flex items-center justify-between w-full rounded-lg px-2.5 py-1.5 text-left text-xs font-medium transition-colors ${
|
||||||
|
currentTimeRange === opt.value
|
||||||
|
? 'bg-blue-600 text-white'
|
||||||
|
: 'text-muted-foreground hover:bg-secondary hover:text-card-foreground'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span>{opt.label}</span>
|
||||||
|
{currentTimeRange === opt.value && <span className="text-[10px]">✓</span>}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
{data ? (
|
{data ? (
|
||||||
<button
|
<button
|
||||||
disabled={isExporting}
|
disabled={isExporting}
|
||||||
onClick={exportToPdf}
|
onClick={exportToPdf}
|
||||||
className="flex items-center gap-1.5 px-3 py-1.5 sm:px-3.5 sm:py-2 rounded-lg sm:rounded-xl text-xs font-semibold bg-blue-600 hover:bg-blue-500 text-white transition-all shadow-md shadow-blue-600/15 disabled:opacity-50 disabled:cursor-not-allowed"
|
className="flex items-center gap-1.5 px-3 py-1.5 sm:px-3.5 sm:py-2 rounded-lg sm:rounded-xl text-xs font-semibold bg-blue-600 hover:bg-blue-500 text-white transition-all shadow-md shadow-blue-600/15 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
|
||||||
>
|
>
|
||||||
{isExporting ? (
|
{isExporting ? (
|
||||||
<Loader2 className="w-3 h-3 sm:w-3.5 sm:h-3.5 animate-spin" />
|
<Loader2 className="w-3 h-3 sm:w-3.5 sm:h-3.5 animate-spin" />
|
||||||
@@ -148,7 +223,7 @@ export function DeviceDetailModal({ ip, mac = '', deviceData, onClose }: Props)
|
|||||||
Export PDF
|
Export PDF
|
||||||
</button>
|
</button>
|
||||||
) : <div />}
|
) : <div />}
|
||||||
<button onClick={handleClose} className="p-1.5 sm:p-2 text-muted-foreground hover:text-card-foreground hover:bg-secondary rounded-lg sm:rounded-xl transition-all">
|
<button onClick={handleClose} className="p-1.5 sm:p-2 text-muted-foreground hover:text-card-foreground hover:bg-secondary rounded-lg sm:rounded-xl transition-all cursor-pointer">
|
||||||
<X className="w-4 h-4 sm:w-5 sm:h-5" />
|
<X className="w-4 h-4 sm:w-5 sm:h-5" />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -238,6 +313,7 @@ export function DeviceDetailModal({ ip, mac = '', deviceData, onClose }: Props)
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>,
|
||||||
|
document.body
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -3,9 +3,8 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { ComposableMap, Geographies, Geography, Line, Marker, ZoomableGroup } from "react-simple-maps";
|
import { ComposableMap, Geographies, Geography, Line, Marker, ZoomableGroup } from "react-simple-maps";
|
||||||
import { useTheme } from "next-themes";
|
import { useTheme } from "next-themes";
|
||||||
import { X, MapPin, ArrowDownLeft, ArrowUpRight, Activity } from "lucide-react";
|
|
||||||
import { fmtBytes } from "@/lib/utils";
|
|
||||||
import { useGlobeData, GlobeDataInput, GlobePointData } from './useGlobeData';
|
import { useGlobeData, GlobeDataInput, GlobePointData } from './useGlobeData';
|
||||||
|
import { GlobePointPopup } from './GlobePointPopup';
|
||||||
|
|
||||||
const geoUrl = "/ne_110m_admin_0_countries.geojson";
|
const geoUrl = "/ne_110m_admin_0_countries.geojson";
|
||||||
|
|
||||||
@@ -172,56 +171,7 @@ export const GlobeMap = ({ data }: GlobeMapProps) => {
|
|||||||
</ComposableMap>
|
</ComposableMap>
|
||||||
|
|
||||||
{selectedPoint && (
|
{selectedPoint && (
|
||||||
<div className="absolute top-3 right-3 z-30 w-60 rounded-xl border border-white/15 bg-slate-950/95 p-3 text-slate-200 shadow-2xl backdrop-blur-md animate-fade-in">
|
<GlobePointPopup point={selectedPoint} onClose={() => setSelectedPoint(null)} />
|
||||||
<div className="flex items-start justify-between gap-2 border-b border-white/10 pb-2">
|
|
||||||
<div className="min-w-0">
|
|
||||||
<span
|
|
||||||
className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[9px] font-bold uppercase tracking-wider ${
|
|
||||||
selectedPoint.isOrigin
|
|
||||||
? "bg-rose-500/20 text-rose-400 border border-rose-500/30"
|
|
||||||
: "bg-sky-500/20 text-sky-400 border border-sky-500/30"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<MapPin className="h-2.5 w-2.5" />
|
|
||||||
{selectedPoint.isOrigin ? "Lokasi Server Agent" : "Negara Tujuan / Luar"}
|
|
||||||
</span>
|
|
||||||
<h4 className="mt-1 text-xs font-bold text-white break-words">{selectedPoint.name}</h4>
|
|
||||||
<p className="text-[9px] font-mono text-slate-400">
|
|
||||||
Lat: {selectedPoint.lat.toFixed(6)}, Lng: {selectedPoint.lng.toFixed(6)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setSelectedPoint(null)}
|
|
||||||
className="rounded-lg p-1 text-slate-400 hover:bg-white/10 hover:text-white transition-colors"
|
|
||||||
aria-label="Close detail"
|
|
||||||
>
|
|
||||||
<X className="h-3.5 w-3.5" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div className="mt-2 space-y-1 text-[10px]">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<span className="flex items-center gap-1 text-emerald-400">
|
|
||||||
<ArrowDownLeft className="h-3 w-3" /> Download (Luar → Agent)
|
|
||||||
</span>
|
|
||||||
<span className="font-mono font-semibold text-emerald-400">{fmtBytes(selectedPoint.download || 0)}</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<span className="flex items-center gap-1 text-sky-400">
|
|
||||||
<ArrowUpRight className="h-3 w-3" /> Upload (Agent → Luar)
|
|
||||||
</span>
|
|
||||||
<span className="font-mono font-semibold text-sky-400">{fmtBytes(selectedPoint.upload || 0)}</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between border-t border-white/10 pt-1">
|
|
||||||
<span className="flex items-center gap-1 text-slate-300 font-medium">
|
|
||||||
<Activity className="h-3 w-3 text-purple-400" /> Total Trafik
|
|
||||||
</span>
|
|
||||||
<span className="font-mono font-bold text-white">
|
|
||||||
{fmtBytes((selectedPoint.download || 0) + (selectedPoint.upload || 0))}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Legenda Berderet ke Bawah */}
|
{/* Legenda Berderet ke Bawah */}
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import React from "react";
|
||||||
|
import { X, MapPin, ArrowDownLeft, ArrowUpRight, Activity, Globe, Server } from "lucide-react";
|
||||||
|
import { fmtBytes } from "@/lib/utils";
|
||||||
|
import { formatAppLabel } from "@/lib/domainUtils";
|
||||||
|
import { GlobePointData } from "./useGlobeData";
|
||||||
|
|
||||||
|
interface GlobePointPopupProps {
|
||||||
|
point: GlobePointData;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GlobePointPopup = ({ point, onClose }: GlobePointPopupProps) => {
|
||||||
|
const topIps = point.topIps || [];
|
||||||
|
const topDomains = point.topDomains || [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="absolute top-3 right-3 z-30 w-72 max-h-[460px] flex flex-col rounded-xl border border-white/15 bg-slate-950/95 p-3 text-slate-200 shadow-2xl backdrop-blur-md animate-fade-in cursor-default"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<div className="flex items-start justify-between gap-2 border-b border-white/10 pb-2 shrink-0">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<span
|
||||||
|
className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[9px] font-bold uppercase tracking-wider ${
|
||||||
|
point.isOrigin
|
||||||
|
? "bg-rose-500/20 text-rose-400 border border-rose-500/30"
|
||||||
|
: "bg-sky-500/20 text-sky-400 border border-sky-500/30"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<MapPin className="h-2.5 w-2.5" />
|
||||||
|
{point.isOrigin ? "Lokasi Server Agent" : "Negara Tujuan / Luar"}
|
||||||
|
</span>
|
||||||
|
<h4 className="mt-1 text-xs font-bold text-white break-words">{point.name}</h4>
|
||||||
|
<p className="text-[9px] font-mono text-slate-400">
|
||||||
|
Lat: {point.lat.toFixed(6)}, Lng: {point.lng.toFixed(6)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
className="rounded-lg p-1 text-slate-400 hover:bg-white/10 hover:text-white transition-colors"
|
||||||
|
aria-label="Close detail"
|
||||||
|
>
|
||||||
|
<X className="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-2 space-y-1 text-[10px] shrink-0">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="flex items-center gap-1 text-emerald-400">
|
||||||
|
<ArrowDownLeft className="h-3 w-3" /> Download (Luar → Agent)
|
||||||
|
</span>
|
||||||
|
<span className="font-mono font-semibold text-emerald-400">{fmtBytes(point.download || 0)}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="flex items-center gap-1 text-sky-400">
|
||||||
|
<ArrowUpRight className="h-3 w-3" /> Upload (Agent → Luar)
|
||||||
|
</span>
|
||||||
|
<span className="font-mono font-semibold text-sky-400">{fmtBytes(point.upload || 0)}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between border-t border-white/10 pt-1">
|
||||||
|
<span className="flex items-center gap-1 text-slate-300 font-medium">
|
||||||
|
<Activity className="h-3 w-3 text-purple-400" /> Total Trafik
|
||||||
|
</span>
|
||||||
|
<span className="font-mono font-bold text-white">
|
||||||
|
{fmtBytes((point.download || 0) + (point.upload || 0))}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{(topIps.length > 0 || topDomains.length > 0) && (
|
||||||
|
<div className="mt-2.5 pt-2 border-t border-white/10 overflow-y-auto space-y-2.5 pr-1 custom-scrollbar">
|
||||||
|
{topIps.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-1 text-[9px] font-bold uppercase tracking-wider text-sky-400 mb-1">
|
||||||
|
<Server className="h-2.5 w-2.5" />
|
||||||
|
<span>Daftar IP ({topIps.length})</span>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{topIps.map((item, idx) => {
|
||||||
|
const hostLabel = item.domain
|
||||||
|
? formatAppLabel(item.domain)
|
||||||
|
: item.app_label
|
||||||
|
? formatAppLabel(item.app_label)
|
||||||
|
: null;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={`${item.ip}-${idx}`}
|
||||||
|
className="rounded-md bg-white/[0.04] border border-white/5 px-2 py-1 text-[9px]"
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<span className="font-mono font-semibold text-slate-100 truncate">{item.ip}</span>
|
||||||
|
<span className="font-mono text-sky-300 shrink-0">{fmtBytes(item.total || 0)}</span>
|
||||||
|
</div>
|
||||||
|
{hostLabel && (
|
||||||
|
<div className="text-[8.5px] text-slate-400 truncate mt-0.5" title={hostLabel}>
|
||||||
|
{hostLabel}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{topDomains.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-1 text-[9px] font-bold uppercase tracking-wider text-emerald-400 mb-1">
|
||||||
|
<Globe className="h-2.5 w-2.5" />
|
||||||
|
<span>Domain / Aplikasi ({topDomains.length})</span>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{topDomains.map((item, idx) => {
|
||||||
|
const label = formatAppLabel(item.domain);
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={`${item.domain}-${idx}`}
|
||||||
|
className="flex items-center justify-between gap-2 rounded-md bg-white/[0.04] border border-white/5 px-2 py-1 text-[9px]"
|
||||||
|
>
|
||||||
|
<span className="text-slate-200 truncate" title={label}>
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
|
<span className="font-mono text-emerald-300 shrink-0">{fmtBytes(item.total || 0)}</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
import { fetchRemoteIpDetails } from "@/lib/api";
|
import { fetchRemoteIpDetails } from "@/lib/api";
|
||||||
|
import { useTimeFilter } from "@/contexts/TimeFilterContext";
|
||||||
import { RemoteIpDetails } from "@/lib/api-detail-types";
|
import { RemoteIpDetails } from "@/lib/api-detail-types";
|
||||||
import { fmtBytes } from "@/lib/utils";
|
import { fmtBytes } from "@/lib/utils";
|
||||||
import { Loader2, X, Globe, Activity, Shield, Box, Server, Clock, ArrowDownToLine, ArrowUpFromLine, RefreshCcw, Link2, Laptop } from "lucide-react";
|
import { Loader2, X, Globe, Activity, Shield, Box, Server, Clock, ArrowDownToLine, ArrowUpFromLine, RefreshCcw, Link2, Laptop, ChevronDown } from "lucide-react";
|
||||||
import ActiveDurationDisplay from "./ActiveDurationDisplay";
|
import ActiveDurationDisplay from "./ActiveDurationDisplay";
|
||||||
import { IpDetails } from "./IpDetails";
|
import { IpDetails } from "./IpDetails";
|
||||||
|
|
||||||
@@ -19,9 +21,24 @@ interface Props {
|
|||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MODAL_TIME_OPTIONS = [
|
||||||
|
{ value: "5m", label: "Last 5 Minutes" },
|
||||||
|
{ value: "30m", label: "Last 30 Minutes" },
|
||||||
|
{ value: "1h", label: "Last 1 Hour" },
|
||||||
|
{ value: "1d", label: "Last 24 Hours" },
|
||||||
|
{ value: "7d", label: "Last 7 Days" },
|
||||||
|
{ value: "30d", label: "Last 30 Days" },
|
||||||
|
{ value: "all", label: "All Time" },
|
||||||
|
] as const;
|
||||||
|
|
||||||
type Tab = "info" | "local_devices" | "protocols" | "domains" | "flows" | "threats";
|
type Tab = "info" | "local_devices" | "protocols" | "domains" | "flows" | "threats";
|
||||||
|
|
||||||
export function RemoteIpDetailModal({ ip, onClose }: Props) {
|
export function RemoteIpDetailModal({ ip, onClose }: Props) {
|
||||||
|
const { timeRange: globalTimeRange } = useTimeFilter();
|
||||||
|
const [currentTimeRange, setCurrentTimeRange] = useState<string>(globalTimeRange || '1d');
|
||||||
|
const [isTimeDropdownOpen, setIsTimeDropdownOpen] = useState(false);
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
|
|
||||||
const [data, setData] = useState<RemoteIpDetails | null>(null);
|
const [data, setData] = useState<RemoteIpDetails | null>(null);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||||
@@ -29,17 +46,31 @@ export function RemoteIpDetailModal({ ip, onClose }: Props) {
|
|||||||
const [isClosing, setIsClosing] = useState(false);
|
const [isClosing, setIsClosing] = useState(false);
|
||||||
const [activeTab, setActiveTab] = useState<Tab>("info");
|
const [activeTab, setActiveTab] = useState<Tab>("info");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setMounted(true);
|
||||||
|
document.body.style.overflow = "hidden";
|
||||||
|
return () => {
|
||||||
|
document.body.style.overflow = "unset";
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (globalTimeRange) {
|
||||||
|
setCurrentTimeRange(globalTimeRange);
|
||||||
|
}
|
||||||
|
}, [globalTimeRange]);
|
||||||
|
|
||||||
const handleClose = () => {
|
const handleClose = () => {
|
||||||
setIsClosing(true);
|
setIsClosing(true);
|
||||||
setTimeout(() => onClose(), 480);
|
setTimeout(() => onClose(), 480);
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadData = async (silent = false) => {
|
const loadData = async (silent = false, range = currentTimeRange) => {
|
||||||
if (!silent) setIsLoading(true);
|
if (!silent) setIsLoading(true);
|
||||||
else setIsRefreshing(true);
|
else setIsRefreshing(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const res = await fetchRemoteIpDetails(ip, '1d');
|
const res = await fetchRemoteIpDetails(ip, range);
|
||||||
setData(res);
|
setData(res);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
if (!silent) setError(e.message);
|
if (!silent) setError(e.message);
|
||||||
@@ -50,8 +81,8 @@ export function RemoteIpDetailModal({ ip, onClose }: Props) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadData(false);
|
loadData(false, currentTimeRange);
|
||||||
}, [ip]);
|
}, [ip, currentTimeRange]);
|
||||||
|
|
||||||
const tabs: { id: Tab; label: string; icon: any }[] = [
|
const tabs: { id: Tab; label: string; icon: any }[] = [
|
||||||
{ id: "info", label: "Overview", icon: Globe },
|
{ id: "info", label: "Overview", icon: Globe },
|
||||||
@@ -62,7 +93,9 @@ export function RemoteIpDetailModal({ ip, onClose }: Props) {
|
|||||||
{ id: "threats", label: "Threats", icon: Shield }
|
{ id: "threats", label: "Threats", icon: Shield }
|
||||||
];
|
];
|
||||||
|
|
||||||
return (
|
if (!mounted) return null;
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
<div className="fixed inset-0 z-[9999] flex items-center justify-center p-4" onClick={handleClose}>
|
<div className="fixed inset-0 z-[9999] flex items-center justify-center p-4" onClick={handleClose}>
|
||||||
<div className={`absolute inset-0 bg-black/60 backdrop-blur-md ${isClosing ? 'animate-overlay-out' : 'animate-overlay-in'}`} />
|
<div className={`absolute inset-0 bg-black/60 backdrop-blur-md ${isClosing ? 'animate-overlay-out' : 'animate-overlay-in'}`} />
|
||||||
<div
|
<div
|
||||||
@@ -91,18 +124,60 @@ export function RemoteIpDetailModal({ ip, onClose }: Props) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center justify-between sm:justify-end gap-2 flex-shrink-0 w-full sm:w-auto border-t border-border/40 pt-3 sm:border-t-0 sm:pt-0">
|
<div className="flex items-center justify-between sm:justify-end gap-2.5 flex-shrink-0 w-full sm:w-auto border-t border-border/40 pt-3 sm:border-t-0 sm:pt-0">
|
||||||
|
{/* Time Filter Selector in Modal */}
|
||||||
|
<div className="relative">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setIsTimeDropdownOpen(!isTimeDropdownOpen)}
|
||||||
|
className="flex items-center gap-1.5 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg sm:rounded-xl text-xs font-semibold bg-secondary/80 hover:bg-secondary text-card-foreground border border-border transition-all shadow-sm cursor-pointer"
|
||||||
|
title="Filter time range"
|
||||||
|
>
|
||||||
|
<Clock className="w-3.5 h-3.5 text-indigo-500" />
|
||||||
|
<span className="truncate max-w-[110px] sm:max-w-[140px]">
|
||||||
|
{MODAL_TIME_OPTIONS.find(o => o.value === currentTimeRange)?.label || currentTimeRange}
|
||||||
|
</span>
|
||||||
|
<ChevronDown className={`w-3 h-3 text-muted-foreground transition-transform duration-200 ${isTimeDropdownOpen ? 'rotate-180' : ''}`} />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{isTimeDropdownOpen && (
|
||||||
|
<>
|
||||||
|
<div className="fixed inset-0 z-[10000]" onClick={() => setIsTimeDropdownOpen(false)} />
|
||||||
|
<div className="absolute right-0 top-full mt-1.5 z-[10001] w-44 rounded-xl border border-border bg-card/95 backdrop-blur-xl p-1 shadow-2xl origin-top-right">
|
||||||
|
{MODAL_TIME_OPTIONS.map((opt) => (
|
||||||
|
<button
|
||||||
|
key={opt.value}
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setCurrentTimeRange(opt.value);
|
||||||
|
setIsTimeDropdownOpen(false);
|
||||||
|
}}
|
||||||
|
className={`flex items-center justify-between w-full rounded-lg px-2.5 py-1.5 text-left text-xs font-medium transition-colors ${
|
||||||
|
currentTimeRange === opt.value
|
||||||
|
? 'bg-indigo-600 text-white'
|
||||||
|
: 'text-muted-foreground hover:bg-secondary hover:text-card-foreground'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span>{opt.label}</span>
|
||||||
|
{currentTimeRange === opt.value && <span className="text-[10px]">✓</span>}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={() => loadData(true)}
|
onClick={() => loadData(true)}
|
||||||
disabled={isLoading || isRefreshing}
|
disabled={isLoading || isRefreshing}
|
||||||
className="p-2 text-muted-foreground hover:text-indigo-500 hover:bg-indigo-500/10 rounded-full transition-all disabled:opacity-50"
|
className="p-2 text-muted-foreground hover:text-indigo-500 hover:bg-indigo-500/10 rounded-full transition-all disabled:opacity-50 cursor-pointer"
|
||||||
title="Refresh Data"
|
title="Refresh Data"
|
||||||
>
|
>
|
||||||
<RefreshCcw className="w-4 h-4" />
|
<RefreshCcw className="w-4 h-4" />
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={handleClose}
|
onClick={handleClose}
|
||||||
className="p-2 text-muted-foreground hover:text-destructive hover:bg-destructive/10 rounded-full transition-all bg-black/5 dark:bg-white/5"
|
className="p-2 text-muted-foreground hover:text-destructive hover:bg-destructive/10 rounded-full transition-all bg-black/5 dark:bg-white/5 cursor-pointer"
|
||||||
>
|
>
|
||||||
<X className="w-4 h-4" />
|
<X className="w-4 h-4" />
|
||||||
</button>
|
</button>
|
||||||
@@ -226,6 +301,7 @@ export function RemoteIpDetailModal({ ip, onClose }: Props) {
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>,
|
||||||
|
document.body
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,22 @@
|
|||||||
import { useMemo } from 'react';
|
import { useMemo } from 'react';
|
||||||
import { SMALL_LABEL_COUNTRIES, getStaggeredCoordinates } from './globeOffsets';
|
import { SMALL_LABEL_COUNTRIES, getStaggeredCoordinates } from './globeOffsets';
|
||||||
|
|
||||||
|
export interface GlobeTopIpItem {
|
||||||
|
ip: string;
|
||||||
|
domain?: string | null;
|
||||||
|
app_label?: string | null;
|
||||||
|
download: number;
|
||||||
|
upload: number;
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GlobeTopDomainItem {
|
||||||
|
domain: string;
|
||||||
|
download: number;
|
||||||
|
upload: number;
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
|
|
||||||
export interface GlobeDataInput {
|
export interface GlobeDataInput {
|
||||||
startLat: number;
|
startLat: number;
|
||||||
startLng: number;
|
startLng: number;
|
||||||
@@ -15,6 +31,8 @@ export interface GlobeDataInput {
|
|||||||
countryCode?: string;
|
countryCode?: string;
|
||||||
direction?: 'outbound' | 'inbound';
|
direction?: 'outbound' | 'inbound';
|
||||||
curveSign?: number;
|
curveSign?: number;
|
||||||
|
topIps?: GlobeTopIpItem[];
|
||||||
|
topDomains?: GlobeTopDomainItem[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface GlobePointData {
|
export interface GlobePointData {
|
||||||
@@ -28,6 +46,42 @@ export interface GlobePointData {
|
|||||||
download: number;
|
download: number;
|
||||||
isOrigin: boolean;
|
isOrigin: boolean;
|
||||||
countryCode?: string;
|
countryCode?: string;
|
||||||
|
topIps?: GlobeTopIpItem[];
|
||||||
|
topDomains?: GlobeTopDomainItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeTopIps(existing: GlobeTopIpItem[] = [], incoming: GlobeTopIpItem[] = []): GlobeTopIpItem[] {
|
||||||
|
const map = new Map<string, GlobeTopIpItem>();
|
||||||
|
for (const item of [...existing, ...incoming]) {
|
||||||
|
if (!item?.ip) continue;
|
||||||
|
const prev = map.get(item.ip);
|
||||||
|
if (prev) {
|
||||||
|
prev.download += item.download || 0;
|
||||||
|
prev.upload += item.upload || 0;
|
||||||
|
prev.total += item.total || 0;
|
||||||
|
if (!prev.domain && item.domain) prev.domain = item.domain;
|
||||||
|
if (!prev.app_label && item.app_label) prev.app_label = item.app_label;
|
||||||
|
} else {
|
||||||
|
map.set(item.ip, { ...item });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Array.from(map.values()).sort((a, b) => b.total - a.total).slice(0, 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeTopDomains(existing: GlobeTopDomainItem[] = [], incoming: GlobeTopDomainItem[] = []): GlobeTopDomainItem[] {
|
||||||
|
const map = new Map<string, GlobeTopDomainItem>();
|
||||||
|
for (const item of [...existing, ...incoming]) {
|
||||||
|
if (!item?.domain) continue;
|
||||||
|
const prev = map.get(item.domain);
|
||||||
|
if (prev) {
|
||||||
|
prev.download += item.download || 0;
|
||||||
|
prev.upload += item.upload || 0;
|
||||||
|
prev.total += item.total || 0;
|
||||||
|
} else {
|
||||||
|
map.set(item.domain, { ...item });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Array.from(map.values()).sort((a, b) => b.total - a.total).slice(0, 8);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useGlobeData(data: GlobeDataInput[], isLight: boolean) {
|
export function useGlobeData(data: GlobeDataInput[], isLight: boolean) {
|
||||||
@@ -77,6 +131,8 @@ export function useGlobeData(data: GlobeDataInput[], isLight: boolean) {
|
|||||||
download: 0,
|
download: 0,
|
||||||
isOrigin: false,
|
isOrigin: false,
|
||||||
countryCode: arc.countryCode,
|
countryCode: arc.countryCode,
|
||||||
|
topIps: [],
|
||||||
|
topDomains: [],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (isFirstForPair) {
|
if (isFirstForPair) {
|
||||||
@@ -84,6 +140,8 @@ export function useGlobeData(data: GlobeDataInput[], isLight: boolean) {
|
|||||||
dp.download += (arc.download || 0);
|
dp.download += (arc.download || 0);
|
||||||
dp.upload += (arc.upload || 0);
|
dp.upload += (arc.upload || 0);
|
||||||
dp.value = dp.download + dp.upload;
|
dp.value = dp.download + dp.upload;
|
||||||
|
dp.topIps = mergeTopIps(dp.topIps, arc.topIps);
|
||||||
|
dp.topDomains = mergeTopDomains(dp.topDomains, arc.topDomains);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!originMap.has(originKey)) {
|
if (!originMap.has(originKey)) {
|
||||||
@@ -98,6 +156,8 @@ export function useGlobeData(data: GlobeDataInput[], isLight: boolean) {
|
|||||||
download: 0,
|
download: 0,
|
||||||
isOrigin: true,
|
isOrigin: true,
|
||||||
countryCode: 'ID',
|
countryCode: 'ID',
|
||||||
|
topIps: [],
|
||||||
|
topDomains: [],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (isFirstForPair) {
|
if (isFirstForPair) {
|
||||||
@@ -105,6 +165,8 @@ export function useGlobeData(data: GlobeDataInput[], isLight: boolean) {
|
|||||||
op.download += (arc.download || 0);
|
op.download += (arc.download || 0);
|
||||||
op.upload += (arc.upload || 0);
|
op.upload += (arc.upload || 0);
|
||||||
op.value = op.download + op.upload;
|
op.value = op.download + op.upload;
|
||||||
|
op.topIps = mergeTopIps(op.topIps, arc.topIps);
|
||||||
|
op.topDomains = mergeTopDomains(op.topDomains, arc.topDomains);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -42,6 +42,20 @@ export interface CountryStat {
|
|||||||
upload: number;
|
upload: number;
|
||||||
flow_count: number;
|
flow_count: number;
|
||||||
}>;
|
}>;
|
||||||
|
top_ips?: Array<{
|
||||||
|
ip: string;
|
||||||
|
domain?: string | null;
|
||||||
|
app_label?: string | null;
|
||||||
|
download: number;
|
||||||
|
upload: number;
|
||||||
|
total: number;
|
||||||
|
}>;
|
||||||
|
top_domains?: Array<{
|
||||||
|
domain: string;
|
||||||
|
download: number;
|
||||||
|
upload: number;
|
||||||
|
total: number;
|
||||||
|
}>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DnsStat {
|
export interface DnsStat {
|
||||||
|
|||||||
Reference in new issue
Block a user