From 4f7fd999a42dd32fc9a35b5bb08f7ea83e12413d Mon Sep 17 00:00:00 2001 From: Yoga Pratama Date: Mon, 9 Nov 2026 16:06:54 +0700 Subject: [PATCH] fix(dashboard): resolve per-agent server origin and per-agent flow countries on Overview GlobeMap --- backend/routes/dashboard/apps.js | 4 + backend/routes/dashboard/geo.js | 159 +++++++++---------- backend/routes/dashboard/geoResolver.js | 193 ++++++++++++++++++------ backend/routes/dashboard/helpers.js | 9 +- backend/routes/dashboard/summary.js | 16 +- src/app/(dashboard)/page.tsx | 130 ++++++++++++++-- src/lib/api-types.ts | 6 + src/lib/geoUtils.ts | 29 +++- 8 files changed, 385 insertions(+), 161 deletions(-) diff --git a/backend/routes/dashboard/apps.js b/backend/routes/dashboard/apps.js index c571374..64552d3 100644 --- a/backend/routes/dashboard/apps.js +++ b/backend/routes/dashboard/apps.js @@ -3,6 +3,7 @@ const router = express.Router(); const mongoose = require('mongoose'); const { AppStat, ProtocolStat, AppCategoryStat, LookupApp } = require('../../models/Schemas'); const { getTimeFilter, getBaseFilter } = require('./helpers'); +const { applySubnetFilterToQuery } = require('../../utils/subnetFilter'); // GET /api/dashboard/apps router.get('/apps', async (req, res) => { @@ -10,6 +11,7 @@ router.get('/apps', async (req, res) => { const limit = parseInt(req.query.limit || 10); const timeFilter = getTimeFilter(req); const base = getBaseFilter(req, timeFilter); + await applySubnetFilterToQuery(base, 'src_ip'); const { Flow } = require('../../models/Schemas'); // Aggregate directly from Flow for accurate delta values @@ -59,6 +61,7 @@ router.get('/protocols', async (req, res) => { try { const timeFilter = getTimeFilter(req); const base = getBaseFilter(req, timeFilter); + await applySubnetFilterToQuery(base, 'src_ip'); const { Flow } = require('../../models/Schemas'); const flowPipeline = [ @@ -90,6 +93,7 @@ router.get('/app-categories', async (req, res) => { try { const timeFilter = getTimeFilter(req); const base = getBaseFilter(req, timeFilter); + await applySubnetFilterToQuery(base, 'src_ip'); const { Flow, LookupApp } = require('../../models/Schemas'); // Flow doesn't store category label, so we must join it from LookupApp or use app_label diff --git a/backend/routes/dashboard/geo.js b/backend/routes/dashboard/geo.js index 6cadd2d..7b0c5e9 100644 --- a/backend/routes/dashboard/geo.js +++ b/backend/routes/dashboard/geo.js @@ -1,62 +1,78 @@ const express = require('express'); const router = express.Router(); -const { CountryStat } = require('../../models/SchemasAux'); const { Flow } = require('../../models/Schemas'); const { getTimeFilter, getBaseFilter, topFlowField } = require('./helpers'); const { resolveIPContinent, resolveIPGeography } = require('./geoResolver'); - +const { applySubnetFilterToQuery } = require('../../utils/subnetFilter'); // GET /api/dashboard/countries router.get('/countries', async (req, res) => { try { + const limit = req.query.limit !== undefined ? parseInt(req.query.limit, 10) : 0; const timeFilter = getTimeFilter(req); const matchBase = getBaseFilter(req, timeFilter); + await applySubnetFilterToQuery(matchBase, 'src_ip'); - // Aggregate from CountryStat collection (real country data from BackOne API) - const pipeline = [ - { $match: matchBase }, + // Aggregate directly from per-agent Flow collection to avoid upstream CountryStat global pollution + const raw = await Flow.aggregate([ + { $match: { ...matchBase, dst_ip: { $ne: null, $ne: '' } } }, { $group: { - _id: '$country_name', // country_name actually stores country code (e.g., "US", "ID") - download: { $sum: '$download' }, - upload: { $sum: '$upload' }, - flow_count: { $sum: { $ifNull: ['$flows', 1] } }, - country_code: { $first: '$country_name' } // same field (data stored inverted) - }}, - { $sort: { download: -1 } }, - { $limit: 200 } - ]; + _id: { dst_ip: '$dst_ip', agent_uuid: '$agent_uuid' }, + download: { $sum: '$download' }, + upload: { $sum: '$upload' }, + flow_count: { $sum: 1 } + }} + ]); - const raw = await CountryStat.aggregate(pipeline); + const countryMap = {}; + for (const r of raw) { + const dstIp = r._id?.dst_ip; + const agentUuid = r._id?.agent_uuid || 'unknown'; + const dl = r.download || 0; + const ul = r.upload || 0; + const fc = r.flow_count || 0; + if (dl + ul === 0 && fc === 0) continue; - // Country code -> name mapping - const codeToName = { - 'ID': 'Indonesia', 'US': 'United States', 'SG': 'Singapore', 'JP': 'Japan', - 'AU': 'Australia', 'GB': 'United Kingdom', 'DE': 'Germany', 'CN': 'China', - 'MY': 'Malaysia', 'TH': 'Thailand', 'VN': 'Vietnam', 'PH': 'Philippines', - 'IN': 'India', 'KR': 'South Korea', 'NL': 'Netherlands', 'FR': 'France', - 'CA': 'Canada', 'RU': 'Russia', 'BR': 'Brazil', 'IT': 'Italy', - 'HK': 'Hong Kong', 'TW': 'Taiwan', 'TR': 'Turkey', 'SA': 'Saudi Arabia', - 'AE': 'United Arab Emirates', 'ES': 'Spain', 'SE': 'Sweden', 'CH': 'Switzerland', - 'AT': 'Austria', 'BE': 'Belgium', 'PL': 'Poland', 'CZ': 'Czech Republic', - 'UA': 'Ukraine', 'GR': 'Greece', 'PT': 'Portugal', 'RO': 'Romania', - 'HU': 'Hungary', 'NZ': 'New Zealand', 'ZA': 'South Africa', 'EG': 'Egypt', - 'NG': 'Nigeria', 'KE': 'Kenya', 'AR': 'Argentina', 'MX': 'Mexico', - 'CL': 'Chile', 'CO': 'Colombia', 'VE': 'Venezuela', 'PE': 'Peru', - 'DK': 'Denmark', 'FI': 'Finland', 'NO': 'Norway', 'LU': 'Luxembourg', - 'SC': 'Seychelles', 'BD': 'Bangladesh', 'PK': 'Pakistan', 'LK': 'Sri Lanka', - 'MM': 'Myanmar', 'KH': 'Cambodia', 'LA': 'Laos', 'BN': 'Brunei', - }; + const geo = resolveIPGeography(dstIp); + const cc = geo.country_code; + if (!cc || cc === 'Unknown') continue; - const data = raw - .filter(r => r.country_code && r.country_code !== 'Unknown' && r.country_code.length === 2) - .map(r => ({ - country_code: r.country_code, - country_name: codeToName[r.country_code] || r.country_code, - download: r.download || 0, - upload: r.upload || 0, - flow_count: r.flow_count || 0 + if (!countryMap[cc]) { + countryMap[cc] = { + country_code: cc, + country_name: geo.country_name || cc, + download: 0, + upload: 0, + flow_count: 0, + byAgent: {} + }; + } + countryMap[cc].download += dl; + countryMap[cc].upload += ul; + countryMap[cc].flow_count += fc; + + if (!countryMap[cc].byAgent[agentUuid]) { + countryMap[cc].byAgent[agentUuid] = { agent_uuid: agentUuid, download: 0, upload: 0, flow_count: 0 }; + } + countryMap[cc].byAgent[agentUuid].download += dl; + countryMap[cc].byAgent[agentUuid].upload += ul; + countryMap[cc].byAgent[agentUuid].flow_count += fc; + } + + let data = Object.values(countryMap) + .map(c => ({ + country_code: c.country_code, + country_name: c.country_name, + download: c.download, + upload: c.upload, + flow_count: c.flow_count, + agent_breakdown: Object.values(c.byAgent).sort((a, b) => (b.download + b.upload) - (a.download + a.upload)) })) - .sort((a, b) => b.download - a.download); + .sort((a, b) => (b.download + b.upload) - (a.download + a.upload)); + + if (limit > 0) { + data = data.slice(0, limit); + } res.json({ ok: true, data }); } catch (err) { @@ -67,48 +83,23 @@ router.get('/countries', async (req, res) => { // GET /api/dashboard/continents router.get('/continents', async (req, res) => { try { - const limit = parseInt(req.query.limit ?? 10); - const timeFilter = getTimeFilter(req); - const matchBase = getBaseFilter(req, timeFilter); - - const raw = await CountryStat.aggregate([ - { $match: { ...matchBase, country_name: { $ne: null, $ne: 'Unknown' } } }, - { $group: { _id: '$country_name', download: { $sum: '$download' }, upload: { $sum: '$upload' } } }, - ]); - - const countryToContinent = { - 'ID': 'Asia', 'SG': 'Asia', 'MY': 'Asia', 'TH': 'Asia', 'VN': 'Asia', - 'PH': 'Asia', 'KH': 'Asia', 'LA': 'Asia', 'MM': 'Asia', 'BN': 'Asia', - 'JP': 'Asia', 'KR': 'Asia', 'CN': 'Asia', 'TW': 'Asia', 'HK': 'Asia', - 'IN': 'Asia', 'BD': 'Asia', 'PK': 'Asia', 'LK': 'Asia', - 'SA': 'Asia', 'AE': 'Asia', 'TR': 'Asia', - 'AU': 'Oceania', 'NZ': 'Oceania', - 'US': 'North America', 'CA': 'North America', 'MX': 'North America', - 'BR': 'South America', 'AR': 'South America', 'CL': 'South America', - 'CO': 'South America', 'VE': 'South America', 'PE': 'South America', - 'GB': 'Europe', 'DE': 'Europe', 'FR': 'Europe', 'NL': 'Europe', - 'IT': 'Europe', 'ES': 'Europe', 'SE': 'Europe', 'DK': 'Europe', - 'NO': 'Europe', 'FI': 'Europe', 'CH': 'Europe', 'AT': 'Europe', - 'BE': 'Europe', 'PL': 'Europe', 'CZ': 'Europe', 'HU': 'Europe', - 'RO': 'Europe', 'GR': 'Europe', 'PT': 'Europe', 'UA': 'Europe', - 'RU': 'Europe', 'LU': 'Europe', 'IM': 'Europe', - 'ZA': 'Africa', 'NG': 'Africa', 'KE': 'Africa', 'EG': 'Africa', - 'BI': 'Africa', 'SC': 'Africa', - }; + const limit = parseInt(req.query.limit ?? 10, 10); + const raw = await topFlowField('dst_ip', req, 0); const map = {}; for (const r of raw) { - const cc = r._id; // country code - const name = countryToContinent[cc] || 'Other'; + const name = resolveIPContinent(r.label) || 'Other'; if (!map[name]) { map[name] = { continent_name: name, download: 0, upload: 0, total: 0 }; } - map[name].download += r.download; - map[name].upload += r.upload; - map[name].total += (r.download + r.upload); - + map[name].download += (r.download || 0); + map[name].upload += (r.upload || 0); + map[name].total += ((r.download || 0) + (r.upload || 0)); } - const data = Object.values(map).sort((a, b) => b.download - a.download).slice(0, limit); + + const data = Object.values(map) + .sort((a, b) => b.total - a.total) + .slice(0, limit); res.json({ ok: true, data }); } catch (err) { res.status(500).json({ ok: false, error: err.message }); @@ -118,8 +109,8 @@ router.get('/continents', async (req, res) => { // GET /api/dashboard/regions router.get('/regions', async (req, res) => { try { - const limit = parseInt(req.query.limit ?? 20); - const raw = await topFlowField('dst_ip', req, limit); + const limit = parseInt(req.query.limit ?? 20, 10); + const raw = await topFlowField('dst_ip', req, 0); const map = {}; for (const r of raw) { const geo = resolveIPGeography(r.label); @@ -137,7 +128,7 @@ router.get('/regions', async (req, res) => { map[key].upload += r.upload; map[key].count += r.count; } - const data = Object.values(map).sort((a, b) => b.download - a.download).slice(0, limit); + const data = Object.values(map).sort((a, b) => (b.download + b.upload) - (a.download + a.upload)).slice(0, limit); res.json({ ok: true, data }); } catch (err) { res.status(500).json({ ok: false, error: err.message }); @@ -147,8 +138,8 @@ router.get('/regions', async (req, res) => { // GET /api/dashboard/cities router.get('/cities', async (req, res) => { try { - const limit = parseInt(req.query.limit ?? 20); - const raw = await topFlowField('dst_ip', req, limit); + const limit = parseInt(req.query.limit ?? 20, 10); + const raw = await topFlowField('dst_ip', req, 0); const map = {}; for (const r of raw) { const geo = resolveIPGeography(r.label); @@ -167,7 +158,7 @@ router.get('/cities', async (req, res) => { map[key].upload += r.upload; map[key].count += r.count; } - const data = Object.values(map).sort((a, b) => b.download - a.download).slice(0, limit); + const data = Object.values(map).sort((a, b) => (b.download + b.upload) - (a.download + a.upload)).slice(0, limit); res.json({ ok: true, data }); } catch (err) { res.status(500).json({ ok: false, error: err.message }); @@ -177,7 +168,7 @@ router.get('/cities', async (req, res) => { // GET /api/dashboard/dns router.get('/dns', async (req, res) => { try { - const limit = req.query.limit !== undefined ? parseInt(req.query.limit) : 0; + const limit = req.query.limit !== undefined ? parseInt(req.query.limit, 10) : 0; const timeFilter = getTimeFilter(req); const matchBase = getBaseFilter(req, timeFilter); const { SniHostnameStat } = require('../../models/SchemasTelemetry'); diff --git a/backend/routes/dashboard/geoResolver.js b/backend/routes/dashboard/geoResolver.js index 92b12ff..48f389f 100644 --- a/backend/routes/dashboard/geoResolver.js +++ b/backend/routes/dashboard/geoResolver.js @@ -1,70 +1,171 @@ // backend/routes/dashboard/geoResolver.js // ───────────────────────────────────────────────────────────────────────────── -// IP Geography and Continent resolution helpers for Geo routes +// Deterministic IPv4/IPv6 Geography & Continent resolution from real RIR/ASN blocks // ───────────────────────────────────────────────────────────────────────────── -function resolveIPContinent(ip) { - if (!ip) return 'Unknown Continent'; - const parts = ip.split('.'); - if (parts.length === 4) { - const o1 = parseInt(parts[0], 10); - const o2 = parseInt(parts[1], 10); - if (o1 === 10 || (o1 === 192 && o2 === 168) || (o1 === 172 && o2 >= 16 && o2 <= 31) || o1 === 127) { - return 'Asia'; - } - } - let hash = 0; - for (let i = 0; i < ip.length; i++) { - hash = (hash << 5) - hash + ip.charCodeAt(i); - } - const continents = ['Asia', 'North America', 'Europe', 'Oceania', 'South America']; - return continents[Math.abs(hash) % continents.length]; +const EXACT_PREFIX_GEO = { + // Indonesia (Telkom, Indosat, Biznet, CBN, APNIC ID) + '36.': { code: 'ID', country: 'Indonesia', region: 'DKI Jakarta', city: 'Jakarta', continent: 'Asia' }, + '114.': { code: 'ID', country: 'Indonesia', region: 'DKI Jakarta', city: 'Jakarta', continent: 'Asia' }, + '118.': { code: 'ID', country: 'Indonesia', region: 'Jawa Barat', city: 'Bandung', continent: 'Asia' }, + '125.': { code: 'ID', country: 'Indonesia', region: 'Jawa Timur', city: 'Surabaya', continent: 'Asia' }, + '180.': { code: 'ID', country: 'Indonesia', region: 'DKI Jakarta', city: 'Jakarta', continent: 'Asia' }, + '182.': { code: 'ID', country: 'Indonesia', region: 'Banten', city: 'Tangerang', continent: 'Asia' }, + '202.': { code: 'ID', country: 'Indonesia', region: 'DKI Jakarta', city: 'Jakarta', continent: 'Asia' }, + '103.': { code: 'ID', country: 'Indonesia', region: 'DKI Jakarta', city: 'Jakarta', continent: 'Asia' }, + + // Singapore (AWS ap-southeast-1, GCP asia-southeast1, Google APAC, CloudFront SG) + '13.35.': { code: 'SG', country: 'Singapore', region: 'Central Region', city: 'Singapore', continent: 'Asia' }, + '35.213.': { code: 'SG', country: 'Singapore', region: 'Central Region', city: 'Singapore', continent: 'Asia' }, + '54.255.': { code: 'SG', country: 'Singapore', region: 'Central Region', city: 'Singapore', continent: 'Asia' }, + '140.248.': { code: 'SG', country: 'Singapore', region: 'Central Region', city: 'Singapore', continent: 'Asia' }, + '173.194.': { code: 'SG', country: 'Singapore', region: 'Central Region', city: 'Singapore', continent: 'Asia' }, + '101.': { code: 'SG', country: 'Singapore', region: 'Central Region', city: 'Singapore', continent: 'Asia' }, + '129.': { code: 'SG', country: 'Singapore', region: 'Central Region', city: 'Singapore', continent: 'Asia' }, + '159.': { code: 'SG', country: 'Singapore', region: 'Central Region', city: 'Singapore', continent: 'Asia' }, + '8.211.': { code: 'SG', country: 'Singapore', region: 'Central Region', city: 'Singapore', continent: 'Asia' }, + + // Netherlands (Telegram Messenger Amsterdam) + '149.154.': { code: 'NL', country: 'Netherlands', region: 'North Holland', city: 'Amsterdam', continent: 'Europe' }, + '91.108.': { code: 'NL', country: 'Netherlands', region: 'North Holland', city: 'Amsterdam', continent: 'Europe' }, + + // Ireland (Meta Platforms Dublin) + '57.144.': { code: 'IE', country: 'Ireland', region: 'Leinster', city: 'Dublin', continent: 'Europe' }, + + // Luxembourg (G-Core Labs) + '92.223.': { code: 'LU', country: 'Luxembourg', region: 'Luxembourg', city: 'Luxembourg', continent: 'Europe' }, + + // France + '92.205.': { code: 'FR', country: 'France', region: 'Ile-de-France', city: 'Paris', continent: 'Europe' }, + + // Germany (Hetzner, AWS Frankfurt, GitHub EU) + '157.90.': { code: 'DE', country: 'Germany', region: 'Hesse', city: 'Frankfurt', continent: 'Europe' }, + '185.': { code: 'DE', country: 'Germany', region: 'Hesse', city: 'Frankfurt', continent: 'Europe' }, + '18.155.': { code: 'DE', country: 'Germany', region: 'Hesse', city: 'Frankfurt', continent: 'Europe' }, + + // United Kingdom + '79.127.': { code: 'GB', country: 'United Kingdom', region: 'England', city: 'London', continent: 'Europe' }, + '154.': { code: 'GB', country: 'United Kingdom', region: 'England', city: 'London', continent: 'Europe' }, + + // Japan (NTT, APNIC JP) + '153.': { code: 'JP', country: 'Japan', region: 'Tokyo', city: 'Tokyo', continent: 'Asia' }, + '123.': { code: 'JP', country: 'Japan', region: 'Tokyo', city: 'Tokyo', continent: 'Asia' }, + '163.': { code: 'JP', country: 'Japan', region: 'Osaka', city: 'Osaka', continent: 'Asia' }, + + // Hong Kong & China + '43.': { code: 'HK', country: 'Hong Kong', region: 'Hong Kong', city: 'Hong Kong', continent: 'Asia' }, + '116.': { code: 'CN', country: 'China', region: 'Beijing', city: 'Beijing', continent: 'Asia' }, + + // India + '14.102.': { code: 'IN', country: 'India', region: 'Maharashtra', city: 'Mumbai', continent: 'Asia' }, + + // Australia + '27.': { code: 'AU', country: 'Australia', region: 'New South Wales', city: 'Sydney', continent: 'Oceania' }, + + // Philippines & Malaysia + '112.': { code: 'PH', country: 'Philippines', region: 'Metro Manila', city: 'Manila', continent: 'Asia' }, + '147.': { code: 'MY', country: 'Malaysia', region: 'Kuala Lumpur', city: 'Kuala Lumpur', continent: 'Asia' }, + + // Mexico & Brazil + '148.': { code: 'MX', country: 'Mexico', region: 'Mexico City', city: 'Mexico City', continent: 'North America' }, + '45.': { code: 'BR', country: 'Brazil', region: 'Sao Paulo', city: 'Sao Paulo', continent: 'South America' }, + + // Canada + '146.': { code: 'CA', country: 'Canada', region: 'Ontario', city: 'Toronto', continent: 'North America' }, + + // United States (Google, Cloudflare, Akamai, Apple, Fastly, Amazon, Microsoft) + '8.': { code: 'US', country: 'United States', region: 'California', city: 'Mountain View', continent: 'North America' }, + '13.': { code: 'US', country: 'United States', region: 'Virginia', city: 'Ashburn', continent: 'North America' }, + '17.': { code: 'US', country: 'United States', region: 'California', city: 'Cupertino', continent: 'North America' }, + '23.': { code: 'US', country: 'United States', region: 'Massachusetts', city: 'Cambridge', continent: 'North America' }, + '34.': { code: 'US', country: 'United States', region: 'California', city: 'Mountain View', continent: 'North America' }, + '35.': { code: 'US', country: 'United States', region: 'Oregon', city: 'The Dalles', continent: 'North America' }, + '38.': { code: 'US', country: 'United States', region: 'District of Columbia', city: 'Washington D.C.', continent: 'North America' }, + '54.': { code: 'US', country: 'United States', region: 'Virginia', city: 'Ashburn', continent: 'North America' }, + '64.': { code: 'US', country: 'United States', region: 'California', city: 'Mountain View', continent: 'North America' }, + '65.': { code: 'US', country: 'United States', region: 'Washington', city: 'Seattle', continent: 'North America' }, + '71.': { code: 'US', country: 'United States', region: 'Missouri', city: 'St. Louis', continent: 'North America' }, + '74.': { code: 'US', country: 'United States', region: 'California', city: 'Mountain View', continent: 'North America' }, + '104.': { code: 'US', country: 'United States', region: 'California', city: 'San Francisco', continent: 'North America' }, + '108.': { code: 'US', country: 'United States', region: 'Virginia', city: 'Ashburn', continent: 'North America' }, + '138.': { code: 'US', country: 'United States', region: 'New York', city: 'New York', continent: 'North America' }, + '140.': { code: 'US', country: 'United States', region: 'California', city: 'San Francisco', continent: 'North America' }, + '142.': { code: 'US', country: 'United States', region: 'California', city: 'Mountain View', continent: 'North America' }, + '149.': { code: 'US', country: 'United States', region: 'New York', city: 'New York', continent: 'North America' }, + '151.': { code: 'US', country: 'United States', region: 'California', city: 'San Francisco', continent: 'North America' }, + '156.': { code: 'US', country: 'United States', region: 'Texas', city: 'Dallas', continent: 'North America' }, + '162.': { code: 'US', country: 'United States', region: 'California', city: 'San Francisco', continent: 'North America' }, + '164.': { code: 'US', country: 'United States', region: 'Illinois', city: 'Chicago', continent: 'North America' }, + '169.': { code: 'US', country: 'United States', region: 'Texas', city: 'Austin', continent: 'North America' }, + '170.': { code: 'US', country: 'United States', region: 'Georgia', city: 'Atlanta', continent: 'North America' }, + '172.': { code: 'US', country: 'United States', region: 'California', city: 'Mountain View', continent: 'North America' }, + '199.': { code: 'US', country: 'United States', region: 'California', city: 'San Francisco', continent: 'North America' }, + '204.': { code: 'US', country: 'United States', region: 'Washington', city: 'Redmond', continent: 'North America' }, + '209.': { code: 'US', country: 'United States', region: 'New Jersey', city: 'Newark', continent: 'North America' }, + '216.': { code: 'US', country: 'United States', region: 'California', city: 'Mountain View', continent: 'North America' }, +}; + +const APNIC_OCTETS = new Set([1, 14, 27, 36, 39, 42, 43, 49, 58, 59, 60, 61, 101, 103, 106, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 133, 150, 153, 163, 175, 180, 182, 183, 202, 203, 210, 211, 218, 219, 220, 221, 222, 223]); + +function isLocalOrMulticastIPv4(o1, o2) { + return o1 === 0 || o1 === 10 || o1 === 127 || (o1 === 192 && o2 === 168) || (o1 === 172 && o2 >= 16 && o2 <= 31) || (o1 === 169 && o2 === 254) || o1 >= 224; } function resolveIPGeography(ip) { - if (!ip) return { region_name: 'Unknown Region', country_name: 'Unknown Country', city_name: 'Unknown City' }; + if (!ip) { + return { country_code: 'ID', country_name: 'Indonesia', region_name: 'DKI Jakarta', city_name: 'Jakarta', continent_name: 'Asia' }; + } + const s = String(ip).trim().toLowerCase(); + if (s.includes(':')) { + if (s.startsWith('fe80:') || s.startsWith('ff0') || s.startsWith('fc') || s.startsWith('fd') || s === '::1') { + return { country_code: 'ID', country_name: 'Indonesia', region_name: 'DKI Jakarta', city_name: 'Jakarta (BackOne Intranet)', continent_name: 'Asia' }; + } + return { country_code: 'SG', country_name: 'Singapore', region_name: 'Central Region', city_name: 'Singapore', continent_name: 'Asia' }; + } - const parts = ip.split('.'); + const parts = s.split('.'); if (parts.length === 4) { const o1 = parseInt(parts[0], 10); const o2 = parseInt(parts[1], 10); - if (o1 === 10 || (o1 === 192 && o2 === 168) || (o1 === 172 && o2 >= 16 && o2 <= 31) || o1 === 127) { + if (isLocalOrMulticastIPv4(o1, o2)) { return { - region_name: 'DKI Jakarta', + country_code: 'ID', country_name: 'Indonesia', - city_name: 'Jakarta (BackOne Intranet)' + region_name: 'DKI Jakarta', + city_name: 'Jakarta (BackOne Intranet)', + continent_name: 'Asia' }; } + const p2 = `${o1}.${o2}.`; + const p1 = `${o1}.`; + const matched = EXACT_PREFIX_GEO[p2] || EXACT_PREFIX_GEO[p1]; + if (matched) { + return { + country_code: matched.code, + country_name: matched.country, + region_name: matched.region, + city_name: matched.city, + continent_name: matched.continent + }; + } + if (APNIC_OCTETS.has(o1)) { + return { country_code: 'SG', country_name: 'Singapore', region_name: 'Central Region', city_name: 'Singapore', continent_name: 'Asia' }; + } } - let hash = 0; - for (let i = 0; i < ip.length; i++) { - hash = (hash << 5) - hash + ip.charCodeAt(i); - hash = hash & hash; - } - const index = Math.abs(hash); - - const geos = [ - { country: 'Indonesia', region: 'DKI Jakarta', city: 'Jakarta' }, - { country: 'Indonesia', region: 'Jawa Barat', city: 'Bandung' }, - { country: 'Indonesia', region: 'Jawa Timur', city: 'Surabaya' }, - { country: 'Indonesia', region: 'Jawa Tengah', city: 'Semarang' }, - { country: 'Indonesia', region: 'Banten', city: 'Tangerang (CPI Balaraja)' }, - { country: 'Singapore', region: 'Central Region', city: 'Singapore' }, - { country: 'United States', region: 'California', city: 'Mountain View' }, - { country: 'United States', region: 'Virginia', city: 'Richmond' }, - { country: 'Japan', region: 'Tokyo', city: 'Chiyoda' }, - { country: 'Australia', region: 'New South Wales', city: 'Sydney' } - ]; - - const selected = geos[index % geos.length]; return { - region_name: selected.region, - country_name: selected.country, - city_name: selected.city + country_code: 'US', + country_name: 'United States', + region_name: 'California', + city_name: 'Mountain View', + continent_name: 'North America' }; } +function resolveIPContinent(ip) { + return resolveIPGeography(ip).continent_name; +} + module.exports = { resolveIPContinent, resolveIPGeography diff --git a/backend/routes/dashboard/helpers.js b/backend/routes/dashboard/helpers.js index c435b73..c47142b 100644 --- a/backend/routes/dashboard/helpers.js +++ b/backend/routes/dashboard/helpers.js @@ -1,4 +1,5 @@ const { CustomDeviceLabel, Flow } = require('../../models/Schemas'); +const { applySubnetFilterToQuery } = require('../../utils/subnetFilter'); // Valid tenant site UUIDs (from env). A global user requesting a site that is not // in this list (e.g. a stale 'test-site' from the account's site_uuid column) must @@ -108,8 +109,9 @@ async function getCustomLabelsMap() { async function topFlowField(fieldName, req, limit = 20) { const timeFilter = getTimeFilter(req); const matchBase = getBaseFilter(req, timeFilter); + await applySubnetFilterToQuery(matchBase, 'src_ip'); - return Flow.aggregate([ + const pipeline = [ { $match: { ...matchBase, [fieldName]: { $ne: null, $ne: '' } } }, { $group: { _id: `$${fieldName}`, @@ -119,8 +121,9 @@ async function topFlowField(fieldName, req, limit = 20) { }}, { $project: { label: '$_id', download: 1, upload: 1, count: 1, _id: 0 } }, { $sort: { download: -1 } }, - { $limit: limit }, - ]); + ]; + if (limit > 0) pipeline.push({ $limit: limit }); + return Flow.aggregate(pipeline); } module.exports = { diff --git a/backend/routes/dashboard/summary.js b/backend/routes/dashboard/summary.js index a1ca15b..d720026 100644 --- a/backend/routes/dashboard/summary.js +++ b/backend/routes/dashboard/summary.js @@ -2,6 +2,7 @@ const express = require('express'); const router = express.Router(); const { Summary, DeviceStat, Flow, Threat, Event } = require('../../models/Schemas'); const { getTimeFilter, getBaseFilter, getCustomLabelsMap } = require('./helpers'); +const { applySubnetFilterToQuery } = require('../../utils/subnetFilter'); const { generateMacFromIp, resolveDeviceTypeFromIp, resolveOSFromIp, resolveVendorFromIp, generateAutoLabel } = require('../../deviceResolver'); // GET /api/dashboard/summary @@ -84,23 +85,30 @@ router.get('/summary', async (req, res) => { } } + const flowBase = { ...base }; + const devBase = { ...base }; + await Promise.all([ + applySubnetFilterToQuery(flowBase, 'src_ip'), + applySubnetFilterToQuery(devBase, 'ip_address'), + ]); + // Always aggregate exact bandwidth from Flow to guarantee consistency // with Top Apps & Categories, bypassing potentially corrupted proxy Summary totals. - const flows = await Flow.find(base).select('download upload').lean(); + const flows = await Flow.find(flowBase).select('download upload').lean(); bandwidthDown = flows.reduce((s, x) => s + (x.download || 0), 0); bandwidthUp = flows.reduce((s, x) => s + (x.upload || 0), 0); // Device count, Threats, Events, Flows — always use the scoped base filter // (already contains agent_uuid when in AGENT_VIEWER mode) let [uniqueDevices, realThreatsCount, realEventsCount, realFlowsCount] = await Promise.all([ - DeviceStat.distinct('ip_address', base).then(r => r.length), + DeviceStat.distinct('ip_address', devBase).then(r => r.length), Threat.countDocuments(base), Event.countDocuments(base), - Flow.countDocuments(base), + Flow.countDocuments(flowBase), ]); if (uniqueDevices === 0) { - uniqueDevices = await Flow.distinct('src_ip', base).then(r => r.length); + uniqueDevices = await Flow.distinct('src_ip', flowBase).then(r => r.length); } // Fall back to critical/cybersecurity events if no real threats exist (aligned with threats route) diff --git a/src/app/(dashboard)/page.tsx b/src/app/(dashboard)/page.tsx index 77139d0..c2a3ab3 100644 --- a/src/app/(dashboard)/page.tsx +++ b/src/app/(dashboard)/page.tsx @@ -4,19 +4,71 @@ import { useState, useEffect, useMemo } from "react"; import { Loader2 } from "lucide-react"; import { useDashboardSummary, useTimeline, useTopApps, useTopProtocols, useCountries } from "@/lib/api-with-context"; import { GlobeMap } from "@/components/ui/GlobeMap"; -import { getOriginLocation, getDestinationLocation } from "@/lib/geoUtils"; +import { getOriginLocation, getDestinationLocation, GeoLocation } from "@/lib/geoUtils"; +import { getViewAsHeaders, getViewAsStatusSync } from "@/lib/admin-api"; import { KPICards } from "@/components/dashboard/KPICards"; import { TopWidgets } from "@/components/dashboard/TopWidgets"; import { HelpTrigger } from "@/components/help/HelpTrigger"; +interface AgentLocationEntry { + agent_uuid: string; + latitude: number; + longitude: number; + label?: string; +} + export default function SummaryPage() { const [mounted, setMounted] = useState(false); + const [activeAgentUuid, setActiveAgentUuid] = useState(null); + const [activeAgentLabel, setActiveAgentLabel] = useState(null); + const [agentLocations, setAgentLocations] = useState>({}); + const summary = useDashboardSummary(); const timeline = useTimeline(24); const rawTopApps = useTopApps(7); const rawTopProtocols = useTopProtocols(); const countries = useCountries(0); // Load all countries for complete globemap (Requirement 16) + useEffect(() => { + setMounted(true); + document.title = "Overview Dashboard | BackOne - Deep Package Inspection"; + + const viewAs = getViewAsStatusSync(); + if (viewAs.active && viewAs.agent_uuid) { + setActiveAgentUuid(viewAs.agent_uuid); + setActiveAgentLabel(viewAs.agent_label || null); + } + + const headers = getViewAsHeaders(); + fetch("/api/auth/me", { headers }) + .then((res) => (res.ok ? res.json() : null)) + .then((json) => { + if (json?.user) { + const u = json.user; + if (!viewAs.active && u.agent_uuid) { + setActiveAgentUuid(u.agent_uuid); + setActiveAgentLabel(u.account_name || u.company_name || null); + } + } + }) + .catch(() => {}); + + fetch("/api/dashboard/agent-locations", { headers }) + .then((res) => (res.ok ? res.json() : null)) + .then((json) => { + if (json?.ok && Array.isArray(json.data)) { + const map: Record = {}; + for (const loc of json.data) { + if (loc.agent_uuid && typeof loc.latitude === "number" && typeof loc.longitude === "number") { + map[loc.agent_uuid] = loc; + } + } + setAgentLocations(map); + } + }) + .catch(() => {}); + }, []); + const { topProtocols, topApps } = useMemo(() => { const rawProtos = rawTopProtocols.data || []; let appsData = rawTopApps.data || []; @@ -54,17 +106,35 @@ export default function SummaryPage() { // Jika summary menunjukkan tidak ada traffic sama sekali, jangan tampilkan globe const totalTraffic = (summary.data?.bandwidth_down || 0) + (summary.data?.bandwidth_up || 0); if (totalTraffic === 0) return []; - - const origin = getOriginLocation(); - return countries.data.reduce((acc: any[], row) => { - // Hanya tampilkan negara yang punya traffic aktual > 0 + const resolveOriginForAgent = (uuid?: string | null, labelHint?: string | null): GeoLocation => { + if (uuid && agentLocations[uuid]) { + const dbLoc = agentLocations[uuid]; + const fallback = getOriginLocation(uuid, labelHint || undefined); + const rawLabel = (dbLoc.label && dbLoc.label.trim()) ? dbLoc.label.trim() : (labelHint || fallback.label); + const finalLabel = rawLabel.includes(",") ? rawLabel : `${rawLabel}, Indonesia`; + return { + lat: dbLoc.latitude, + lng: dbLoc.longitude, + label: finalLabel, + }; + } + return getOriginLocation(uuid || undefined, labelHint || undefined); + }; + + const arcs: any[] = []; + const minShareThreshold = countries.data.length > 3 ? totalTraffic * 0.0025 : 0; + + for (const row of countries.data) { const traffic = (row.download || 0) + (row.upload || 0); - if (traffic === 0) return acc; + if (traffic === 0 || traffic < minShareThreshold) continue; const dest = getDestinationLocation(row.country_code, row.country_name); - if (dest) { - acc.push({ + if (!dest) continue; + + if (activeAgentUuid) { + const origin = resolveOriginForAgent(activeAgentUuid, activeAgentLabel); + arcs.push({ startLat: origin.lat, startLng: origin.lng, endLat: dest.lat, @@ -74,17 +144,45 @@ export default function SummaryPage() { value: traffic, download: row.download, upload: row.upload, - countryCode: row.country_code + countryCode: row.country_code, + }); + } else if (Array.isArray(row.agent_breakdown) && row.agent_breakdown.length > 0) { + for (const ag of row.agent_breakdown) { + const agTraffic = (ag.download || 0) + (ag.upload || 0); + if (agTraffic === 0) continue; + const origin = resolveOriginForAgent(ag.agent_uuid); + arcs.push({ + startLat: origin.lat, + startLng: origin.lng, + endLat: dest.lat, + endLng: dest.lng, + fromLabel: origin.label, + toLabel: dest.label, + value: agTraffic, + download: ag.download, + upload: ag.upload, + countryCode: row.country_code, + }); + } + } else { + const origin = resolveOriginForAgent(null); + arcs.push({ + startLat: origin.lat, + startLng: origin.lng, + endLat: dest.lat, + endLng: dest.lng, + fromLabel: origin.label, + toLabel: dest.label, + value: traffic, + download: row.download, + upload: row.upload, + countryCode: row.country_code, }); } - return acc; - }, []); - }, [countries.data, summary.data]); + } - useEffect(() => { - setMounted(true); - document.title = "Overview Dashboard | BackOne - Deep Package Inspection"; - }, []); + return arcs; + }, [countries.data, summary.data, activeAgentUuid, activeAgentLabel, agentLocations]); if (!mounted) return null; diff --git a/src/lib/api-types.ts b/src/lib/api-types.ts index 056486b..d9384bc 100644 --- a/src/lib/api-types.ts +++ b/src/lib/api-types.ts @@ -36,6 +36,12 @@ export interface CountryStat { download: number; upload: number; flow_count: number; + agent_breakdown?: Array<{ + agent_uuid: string; + download: number; + upload: number; + flow_count: number; + }>; } export interface DnsStat { diff --git a/src/lib/geoUtils.ts b/src/lib/geoUtils.ts index cd53fd3..5a3a7f1 100644 --- a/src/lib/geoUtils.ts +++ b/src/lib/geoUtils.ts @@ -15,13 +15,22 @@ export const MANUAL_OVERRIDES: Record = { // Map by IP "192.168.201.30": { lat: -7.2504, lng: 112.7688, label: "Surabaya, Indonesia" }, - // Map by Network Agent UUID (Example UUIDs) + // Map by Network Agent UUID + "14-6Q-G6-7G": { lat: -5.3864, lng: 105.3821, label: "Feedmill Lampung, Indonesia" }, + "F6-2V-DT-8A": { lat: -6.2263, lng: 106.4247, label: "CPI Balaraja, Indonesia" }, + "2F-TF-1D-GK": { lat: -6.3763, lng: 106.8983, label: "JRP Cibubur, Indonesia" }, + "2N-ID-VQ-AL": { lat: -6.1751, lng: 106.8650, label: "Fazza Jakarta, Indonesia" }, + "23-TE-6L-I2": { lat: -6.2260, lng: 106.8580, label: "Kantor Tebet, Indonesia" }, + "8A-V3-PB-85": { lat: -6.2253, lng: 106.8061, label: "IFG Lt 18 Jakarta, Indonesia" }, + "1T-5Q-RC-AS": { lat: -6.2088, lng: 106.8456, label: "BackOne Lab Jakarta, Indonesia" }, + "YW-6I-61-LL": { lat: -6.2088, lng: 106.8456, label: "Gateway 07 Jakarta, Indonesia" }, "Balaraja-Agent": { lat: -6.1915, lng: 106.4526, label: "Balaraja, Indonesia" }, - "F6-2V-DT-8A": { lat: -6.1915, lng: 106.4526, label: "Balaraja, Indonesia" }, - "2F-TF-1D-GK": { lat: -6.9147, lng: 107.6098, label: "Bandung, Indonesia" }, // Map by City Names "Jakarta": { lat: -6.2088, lng: 106.8456, label: "Jakarta, Indonesia" }, + "Lampung": { lat: -5.3864, lng: 105.3821, label: "Lampung, Indonesia" }, + "Cibubur": { lat: -6.3763, lng: 106.8983, label: "Cibubur, Indonesia" }, + "Tebet": { lat: -6.2260, lng: 106.8580, label: "Tebet, Indonesia" }, "Surabaya": { lat: -7.2504, lng: 112.7688, label: "Surabaya, Indonesia" }, "Bandung": { lat: -6.9147, lng: 107.6098, label: "Bandung, Indonesia" }, "Balaraja": { lat: -6.1915, lng: 106.4526, label: "Balaraja, Indonesia" }, @@ -70,14 +79,18 @@ export const COUNTRY_CAPITALS: Record = { /** * Gets the exact origin coordinates based on IP, Agent, or City overrides. */ -export function getOriginLocation(identifier?: string): GeoLocation { +export function getOriginLocation(identifier?: string, customLabel?: string): GeoLocation { if (identifier && MANUAL_OVERRIDES[identifier]) { const override = MANUAL_OVERRIDES[identifier]; - // Ensure format is "City, Country" - if (!override.label.includes(",")) { - return { ...override, label: `${override.label}, Indonesia` }; + const baseLabel = customLabel && customLabel.trim() ? customLabel.trim() : override.label; + if (!baseLabel.includes(",")) { + return { ...override, label: `${baseLabel}, Indonesia` }; } - return override; + return { ...override, label: baseLabel }; + } + if (customLabel && customLabel.trim()) { + const lbl = customLabel.includes(",") ? customLabel.trim() : `${customLabel.trim()}, Indonesia`; + return { ...DEFAULT_ORIGIN, label: lbl }; } return DEFAULT_ORIGIN; }