feat: NetFlow/IPFIX traffic analytics — per-client usage, app breakdown, built-in collector (v0.13.0-beta)

Adds Meraki-style traffic analytics powered by MikroTik Traffic Flow:

Backend
- Built-in NetFlow v9 + IPFIX collector (UDP 2055) with hand-rolled decoder,
  template caching, enterprise-field and IPv6 support
- Flow attribution: client IP → MAC via the clients table, upload/download
  direction, NAT-duplicate records dropped
- App classification by protocol/port (~25 categories: HTTPS, QUIC, DNS,
  SSH, Email, WireGuard, ...)
- Deduplication: per-client best-exporter-per-window so flows crossing two
  managed routers are never double-counted
- NAT-tolerant ingest: flows from sources matching no managed device (NAT /
  Tailscale subnet routers in path) are accepted as per-source unidentified
  exporters instead of silently dropped (netflow_accept_unknown setting)
- Storage: InfluxDB client_traffic time-series (bounded cardinality via
  top-N fold) + Postgres client_traffic_daily rollups; daily retention purge
- One-toggle device config push via RouterOS API (/ip traffic-flow + target)
- New /api/traffic/* analytics endpoints + /api/network-services/netflow
- docker-compose: NETFLOW_PORT (default 2055/udp) published on the backend

Frontend
- New Traffic page: fleet up/down chart, top talkers with client
  click-through, app-category donut, 1h–30d ranges
- New NetFlow config page: collector settings, live ingest stats,
  per-device export toggles with health badges, NAT-source banner
- Client detail: App Traffic card (auto-hides without data)
- Clients page: sortable "Data (today)" column
- Settings: NetFlow retention controls

Includes 17 unit tests (decoder fixtures, dedup, attribution, classifier);
verified end-to-end against live RouterOS devices.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2GT-Rich
2026-06-10 10:58:41 -07:00
co-authored by Claude Fable 5
parent 367034c2d6
commit b841eb6e7b
29 changed files with 2553 additions and 15 deletions
+4
View File
@@ -24,6 +24,8 @@ import NetworkServicesDNSPage from './pages/NetworkServicesDNSPage';
import NetworkServicesNTPPage from './pages/NetworkServicesNTPPage';
import NetworkServicesWireGuardPage from './pages/NetworkServicesWireGuardPage';
import NetworkServicesSyslogPage from './pages/NetworkServicesSyslogPage';
import NetworkServicesNetflowPage from './pages/NetworkServicesNetflowPage';
import TrafficAnalyticsPage from './pages/TrafficAnalyticsPage';
function ProtectedRoute({ children }: { children: React.ReactNode }) {
const token = useAuthStore((s) => s.token);
@@ -67,6 +69,8 @@ export default function App() {
<Route path="network-services/ntp" element={<NetworkServicesNTPPage />} />
<Route path="network-services/wireguard" element={<NetworkServicesWireGuardPage />} />
<Route path="network-services/syslog" element={<NetworkServicesSyslogPage />} />
<Route path="network-services/netflow" element={<NetworkServicesNetflowPage />} />
<Route path="traffic" element={<TrafficAnalyticsPage />} />
</Route>
<Route path="*" element={<Navigate to="/dashboard" replace />} />
</Routes>
+3 -1
View File
@@ -4,7 +4,7 @@ import { useQuery } from '@tanstack/react-query';
import {
LayoutDashboard, Router, Users, Bell, GitBranch, HardDrive,
Settings, Network, ChevronLeft, ChevronRight, Layers, ChevronDown, SlidersHorizontal, X, Wifi,
Server, Globe, Clock, Shield, FileText,
Server, Globe, Clock, Shield, FileText, Activity, BarChart3,
} from 'lucide-react';
import clsx from 'clsx';
import { APP_VERSION } from '../../version';
@@ -14,6 +14,7 @@ const navItems = [
{ to: '/dashboard', icon: LayoutDashboard, label: 'Dashboard' },
{ to: '/devices', icon: Router, label: 'Devices' },
{ to: '/clients', icon: Users, label: 'Clients' },
{ to: '/traffic', icon: Activity, label: 'Traffic' },
{ to: '/events', icon: Bell, label: 'Events' },
{ to: '/topology', icon: GitBranch, label: 'Topology' },
{ to: '/backups', icon: HardDrive, label: 'Backups' },
@@ -42,6 +43,7 @@ const networkServicesSubItems = [
{ to: '/network-services/ntp', icon: Clock, label: 'NTP' },
{ to: '/network-services/wireguard', icon: Shield, label: 'WireGuard' },
{ to: '/network-services/syslog', icon: FileText, label: 'Syslog' },
{ to: '/network-services/netflow', icon: BarChart3, label: 'NetFlow' },
];
interface SidebarProps {
+131 -7
View File
@@ -11,7 +11,7 @@ import {
BarChart, Bar, Cell, ReferenceLine,
} from 'recharts';
import { format, formatDistanceToNow, parseISO } from 'date-fns';
import { clientsApi } from '../services/api';
import { clientsApi, trafficApi } from '../services/api';
import type { ClientDetail } from '../services/api';
import type { SignalPoint } from '../services/api';
import clsx from 'clsx';
@@ -581,6 +581,127 @@ function TrafficCard({ mac }: { mac: string }) {
);
}
// ─── App Traffic (NetFlow) ────────────────────────────────────────────────────
const APP_COLORS = [
'#3b82f6', '#8b5cf6', '#10b981', '#f59e0b', '#ef4444', '#06b6d4',
'#ec4899', '#84cc16', '#f97316', '#6366f1', '#14b8a6', '#a855f7',
];
function AppTrafficCard({ mac }: { mac: string }) {
const [range, setRange] = useState<'1h' | '24h' | '7d' | '30d'>('24h');
const { data, isLoading } = useQuery({
queryKey: ['client-app-traffic', mac, range],
queryFn: () => trafficApi.client(mac, range).then(r => r.data),
refetchInterval: 60_000,
});
const series = data?.series ?? [];
const apps = data?.apps ?? [];
// NetFlow data only exists for clients on networks with export enabled —
// hide the card entirely rather than showing a permanently empty chart.
if (!isLoading && series.length === 0 && apps.length === 0) return null;
const ranges = [
{ value: '1h', label: '1h' },
{ value: '24h', label: '24h' },
{ value: '7d', label: '7d' },
{ value: '30d', label: '30d' },
] as const;
const chartData = series.map(p => ({
time: p.time,
Upload: p.upload,
Download: p.download,
label: format(parseISO(p.time), range === '7d' || range === '30d' ? 'MMM d HH:mm' : 'HH:mm'),
}));
const totalAppBytes = apps.reduce((s, a) => s + a.bytes, 0);
return (
<div className="card p-4 space-y-3">
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold text-gray-800 dark:text-white flex items-center gap-2">
<Activity className="w-4 h-4 text-gray-400" />
App Traffic
<span className="text-xs font-normal text-gray-400 dark:text-slate-500">(NetFlow)</span>
</h2>
<div className="flex gap-1">
{ranges.map(r => (
<button
key={r.value}
onClick={() => setRange(r.value)}
className={clsx(
'px-2 py-1 text-xs rounded font-medium transition-colors',
range === r.value
? 'bg-blue-600 text-white'
: 'text-gray-500 dark:text-slate-400 hover:bg-gray-100 dark:hover:bg-slate-700'
)}
>
{r.label}
</button>
))}
</div>
</div>
{isLoading ? (
<div className="h-48 bg-gray-100 dark:bg-slate-700/40 rounded animate-pulse" />
) : (
<>
{chartData.length > 0 && (
<ResponsiveContainer width="100%" height={180}>
<AreaChart data={chartData} margin={{ top: 4, right: 8, bottom: 0, left: 0 }}>
<CartesianGrid strokeDasharray="3 3" className="opacity-20" />
<XAxis
dataKey="label"
tick={{ fontSize: 10, fill: 'currentColor' }}
className="text-gray-400 dark:text-slate-500"
interval="preserveStartEnd"
/>
<YAxis
tickFormatter={(v) => formatBytes(v)}
tick={{ fontSize: 10, fill: 'currentColor' }}
className="text-gray-400 dark:text-slate-500"
width={60}
/>
<Tooltip
formatter={(value: number) => [formatBytes(value), '']}
contentStyle={{
fontSize: '11px',
backgroundColor: 'var(--tooltip-bg, #1e293b)',
borderColor: 'var(--tooltip-border, #334155)',
color: 'var(--tooltip-color, #e2e8f0)',
}}
/>
<Legend wrapperStyle={{ fontSize: '11px' }} />
<Area type="monotone" dataKey="Download" stroke="#3b82f6" fill="#3b82f620" strokeWidth={1.5} dot={false} />
<Area type="monotone" dataKey="Upload" stroke="#8b5cf6" fill="#8b5cf620" strokeWidth={1.5} dot={false} />
</AreaChart>
</ResponsiveContainer>
)}
{apps.length > 0 && (
<div className="space-y-1.5">
{apps.slice(0, 8).map((a, i) => (
<div key={a.app} className="flex items-center gap-2 text-xs">
<span className="w-2 h-2 rounded-sm flex-shrink-0" style={{ backgroundColor: APP_COLORS[i % APP_COLORS.length] }} />
<span className="text-gray-700 dark:text-slate-300 flex-1 truncate">{a.app}</span>
<span className="text-gray-400 dark:text-slate-500">
{totalAppBytes > 0 ? `${((a.bytes / totalAppBytes) * 100).toFixed(1)}%` : ''}
</span>
<span className="font-medium text-gray-900 dark:text-white w-16 text-right">{formatBytes(a.bytes)}</span>
</div>
))}
</div>
)}
</>
)}
</div>
);
}
// ─── Signal Strength Graph ────────────────────────────────────────────────────
function qualityColor(dbm: number): string {
@@ -800,12 +921,15 @@ export default function ClientDetailPage() {
{/* Details on left; Traffic + Signal stacked on right */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">
<ClientDetailsCard client={client} canWrite={canWrite} />
{client.client_type === 'wireless' && (
<div className="space-y-4">
<TrafficCard mac={mac!} />
<SignalCard mac={mac!} />
</div>
)}
<div className="space-y-4">
<AppTrafficCard mac={client.mac_address} />
{client.client_type === 'wireless' && (
<>
<TrafficCard mac={mac!} />
<SignalCard mac={mac!} />
</>
)}
</div>
</div>
</div>
);
+12
View File
@@ -19,6 +19,13 @@ const REFRESH_OPTIONS = [
const STORAGE_KEY = 'clients-refresh-interval';
function formatDataBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;
}
function readStoredInterval(): number | null {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw === 'null') return null;
@@ -189,6 +196,7 @@ export default function ClientsPage() {
case 'interface_name': av = a.interface_name || ''; bv = b.interface_name || ''; break;
case 'vlan_id': av = a.vlan_id ?? -1; bv = b.vlan_id ?? -1; break;
case 'device_name': av = a.device_name || ''; bv = b.device_name || ''; break;
case 'traffic_today_bytes': av = a.traffic_today_bytes ?? 0; bv = b.traffic_today_bytes ?? 0; break;
case 'last_seen': av = a.last_seen || ''; bv = b.last_seen || ''; break;
default: av = ''; bv = '';
}
@@ -298,6 +306,7 @@ export default function ClientsPage() {
{ col: 'interface_name', label: 'Port', align: 'left' },
{ col: 'vlan_id', label: 'VLAN', align: 'left' },
{ col: 'device_name', label: 'Device', align: 'left' },
{ col: 'traffic_today_bytes', label: 'Data (today)', align: 'left' },
{ col: 'last_seen', label: 'Last Seen', align: 'left' },
] as { col: string; label: string; align: 'left' | 'right' }[]).map(({ col, label, align }) => (
<th
@@ -392,6 +401,9 @@ export default function ClientsPage() {
<td className="px-4 py-2.5 text-xs text-gray-500 dark:text-slate-400">
{client.device_name || '—'}
</td>
<td className="px-4 py-2.5 text-xs text-gray-500 dark:text-slate-400 whitespace-nowrap">
{client.traffic_today_bytes ? formatDataBytes(client.traffic_today_bytes) : '—'}
</td>
<td className="px-4 py-2.5 text-xs text-gray-400 dark:text-slate-500">
{client.last_seen
? formatDistanceToNow(new Date(client.last_seen), { addSuffix: true })
@@ -0,0 +1,324 @@
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import {
BarChart3, RefreshCw, AlertTriangle, Save, CheckCircle, XCircle, Radio,
} from 'lucide-react';
import clsx from 'clsx';
import { formatDistanceToNow, parseISO } from 'date-fns';
import { networkServicesApi, settingsApi, trafficApi } from '../services/api';
import { useCanWrite } from '../hooks/useCanWrite';
function Toggle({ checked, onChange, disabled }: { checked: boolean; onChange: (v: boolean) => void; disabled?: boolean }) {
return (
<button
role="switch" aria-checked={checked}
onClick={() => !disabled && onChange(!checked)}
className={clsx(
'relative inline-flex h-5 w-9 flex-shrink-0 rounded-full border-2 border-transparent transition-colors',
checked ? 'bg-blue-600' : 'bg-gray-300 dark:bg-slate-600',
disabled && 'opacity-50 cursor-not-allowed'
)}
>
<span className={clsx('pointer-events-none inline-block h-4 w-4 rounded-full bg-white shadow transform transition-transform', checked ? 'translate-x-4' : 'translate-x-0')} />
</button>
);
}
export default function NetworkServicesNetflowPage() {
const canWrite = useCanWrite();
const qc = useQueryClient();
// ── Collector settings ────────────────────────────────────────────────────
const { data: settings } = useQuery({
queryKey: ['app-settings'],
queryFn: () => settingsApi.get().then(r => r.data),
});
const [enabled, setEnabled] = useState(false);
const [address, setAddress] = useState('');
const [port, setPort] = useState('2055');
const [version, setVersion] = useState('9');
const [loaded, setLoaded] = useState(false);
const [saving, setSaving] = useState(false);
const [saveMsg, setSaveMsg] = useState('');
useEffect(() => {
if (settings && !loaded) {
setEnabled(settings['netflow_enabled'] === true);
setAddress(String(settings['netflow_collector_address'] ?? ''));
setPort(String(settings['netflow_collector_port'] ?? '2055'));
setVersion(String(settings['netflow_version'] ?? '9'));
setLoaded(true);
}
}, [settings, loaded]);
async function saveCollectorSettings(overrides: Record<string, unknown> = {}) {
setSaving(true); setSaveMsg('');
try {
await settingsApi.update({
netflow_enabled: enabled,
netflow_collector_address: address.trim(),
netflow_collector_port: parseInt(port, 10) || 2055,
netflow_version: version,
...overrides,
});
qc.invalidateQueries({ queryKey: ['app-settings'] });
qc.invalidateQueries({ queryKey: ['traffic-status'] });
setSaveMsg('Saved');
setTimeout(() => setSaveMsg(''), 3000);
} catch (e) {
setSaveMsg(`Failed: ${(e as Error).message}`);
} finally {
setSaving(false);
}
}
async function handleListenerToggle(value: boolean) {
setEnabled(value);
await saveCollectorSettings({ netflow_enabled: value });
}
// ── Collector status (live) ───────────────────────────────────────────────
const { data: status } = useQuery({
queryKey: ['traffic-status'],
queryFn: () => trafficApi.status().then(r => r.data),
refetchInterval: 10_000,
});
// ── Fleet device state ────────────────────────────────────────────────────
const { data: fleet, isLoading: fleetLoading, refetch, isFetching, error: fleetError } = useQuery({
queryKey: ['ns-netflow-fleet'],
queryFn: () => networkServicesApi.netflowFleet().then(r => r.data),
});
const [togglePending, setTogglePending] = useState<number | null>(null);
const [toggleError, setToggleError] = useState('');
async function handleDeviceToggle(deviceId: number, value: boolean) {
setTogglePending(deviceId); setToggleError('');
try {
await networkServicesApi.setNetflow(deviceId, value);
qc.invalidateQueries({ queryKey: ['ns-netflow-fleet'] });
} catch (e) {
const err = e as { response?: { data?: { error?: string } }; message: string };
setToggleError(err.response?.data?.error || err.message);
} finally {
setTogglePending(null);
}
}
const addressMissing = !address.trim();
const devices = fleet?.devices ?? [];
const unidentified = (status?.exporters ?? []).filter(e => e.deviceId < 0);
function deviceBadge(d: (typeof devices)[number]) {
if (d.error) {
return <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400"><XCircle className="w-3 h-3" />Unreachable</span>;
}
if (!d.enabled) {
return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 dark:bg-slate-700 text-gray-500 dark:text-slate-400">Disabled</span>;
}
if (!d.target_matches_collector) {
return <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400"><AlertTriangle className="w-3 h-3" />Wrong target</span>;
}
if (!d.last_flow_at) {
return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400">No flows yet</span>;
}
return <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400"><CheckCircle className="w-3 h-3" />Exporting</span>;
}
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-xl font-bold text-gray-900 dark:text-white">NetFlow</h1>
<p className="text-sm text-gray-500 dark:text-slate-400">
Per-client traffic analytics via NetFlow/IPFIX export — view results on the{' '}
<Link to="/traffic" className="text-blue-600 dark:text-blue-400 hover:underline">Traffic</Link> page
</p>
</div>
<button onClick={() => refetch()} disabled={isFetching}
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-gray-300 dark:border-slate-600 text-sm text-gray-600 dark:text-slate-300 hover:bg-gray-100 dark:hover:bg-slate-700 disabled:opacity-50 transition-colors">
<RefreshCw className={clsx('w-3.5 h-3.5', isFetching && 'animate-spin')} />Refresh
</button>
</div>
{/* Collector card */}
<div className="card overflow-hidden">
<div className="px-5 py-3 border-b border-gray-200 dark:border-slate-700 flex items-center gap-2">
<Radio className="w-4 h-4 text-blue-500" />
<h2 className="text-sm font-semibold text-gray-700 dark:text-slate-200">Collector</h2>
{status && (
<span className={clsx('inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium',
status.listening
? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400'
: 'bg-gray-100 dark:bg-slate-700 text-gray-500 dark:text-slate-400')}>
<span className={clsx('w-1.5 h-1.5 rounded-full', status.listening ? 'bg-green-500' : 'bg-gray-400')} />
{status.listening ? `Listening on udp/${status.port}` : 'Stopped'}
</span>
)}
</div>
<div className="p-5 space-y-4">
<div className="flex items-center gap-3">
<Toggle checked={enabled} onChange={handleListenerToggle} disabled={!canWrite || saving} />
<div>
<div className="text-sm font-medium text-gray-700 dark:text-slate-200">Enable NetFlow collector</div>
<p className="text-xs text-gray-400 dark:text-slate-500">
Receives NetFlow v9 / IPFIX exports from your MikroTik devices and aggregates per-client traffic.
</p>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div className="sm:col-span-1">
<label className="block text-sm font-medium text-gray-700 dark:text-slate-200 mb-1">
Collector Address <span className="text-red-500">*</span>
</label>
<input className="input w-full" value={address} onChange={e => setAddress(e.target.value)}
placeholder="192.168.1.100" disabled={!canWrite} />
<p className="mt-1 text-xs text-gray-400 dark:text-slate-500">
The IP of this server as reachable by your devices (the Docker host IP, not the container).
</p>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-slate-200 mb-1">Port</label>
<input type="number" className="input w-full" value={port} onChange={e => setPort(e.target.value)}
min="1" max="65535" disabled={!canWrite} />
<p className="mt-1 text-xs text-gray-400 dark:text-slate-500">
Must match the host port mapping (NETFLOW_PORT, default 2055).
</p>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-slate-200 mb-1">Version</label>
<select className="input w-full" value={version} onChange={e => setVersion(e.target.value)} disabled={!canWrite}>
<option value="9">NetFlow v9</option>
<option value="ipfix">IPFIX</option>
</select>
</div>
</div>
{addressMissing && (
<div className="flex items-center gap-1.5 text-xs text-amber-600 dark:text-amber-400">
<AlertTriangle className="w-3.5 h-3.5" />Set the collector address before enabling devices below.
</div>
)}
<div className="flex items-center gap-3">
{canWrite && (
<button onClick={() => saveCollectorSettings()} disabled={saving}
className="flex items-center gap-1.5 px-4 py-1.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg disabled:opacity-50 transition-colors">
<Save className="w-3.5 h-3.5" />{saving ? 'Saving…' : 'Save Settings'}
</button>
)}
{saveMsg && (
<span className={clsx('text-sm', saveMsg === 'Saved' ? 'text-green-600 dark:text-green-400' : 'text-red-500')}>{saveMsg}</span>
)}
</div>
{unidentified.length > 0 && (
<div className="flex items-start gap-2 p-3 rounded-lg bg-amber-50 dark:bg-amber-900/20 text-xs text-amber-700 dark:text-amber-400">
<AlertTriangle className="w-4 h-4 flex-shrink-0 mt-0.5" />
<div>
Receiving flows from unidentified source{unidentified.length > 1 ? 's' : ''}{' '}
<span className="font-mono">{unidentified.map(e => e.deviceName.replace(/^Unidentified \((.+)\)$/, '$1')).join(', ')}</span>.
This usually means NAT sits between your routers and the collector. Flows are still
processed and attributed to clients, but can&apos;t be tied to a specific exporting device.
</div>
</div>
)}
{status && status.packetsReceived > 0 && (
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4 pt-2 border-t border-gray-100 dark:border-slate-800">
<div>
<div className="text-xs text-gray-400 dark:text-slate-500">Packets received</div>
<div className="text-sm font-semibold text-gray-900 dark:text-white">{status.packetsReceived.toLocaleString()}</div>
</div>
<div>
<div className="text-xs text-gray-400 dark:text-slate-500">Flows decoded</div>
<div className="text-sm font-semibold text-gray-900 dark:text-white">{status.flowsDecoded.toLocaleString()}</div>
</div>
<div>
<div className="text-xs text-gray-400 dark:text-slate-500">Flows attributed</div>
<div className="text-sm font-semibold text-gray-900 dark:text-white">{status.flowsAttributed.toLocaleString()}</div>
</div>
<div>
<div className="text-xs text-gray-400 dark:text-slate-500">Unknown exporters</div>
<div className="text-sm font-semibold text-gray-900 dark:text-white">{status.packetsFromUnknownExporter.toLocaleString()}</div>
</div>
</div>
)}
</div>
</div>
{/* Devices */}
<div className="card overflow-hidden">
<div className="px-5 py-3 border-b border-gray-200 dark:border-slate-700 flex items-center gap-2">
<BarChart3 className="w-4 h-4 text-indigo-500" />
<h2 className="text-sm font-semibold text-gray-700 dark:text-slate-200">
Devices<span className="ml-2 text-xs font-normal text-gray-400 dark:text-slate-500">({devices.length} online)</span>
</h2>
</div>
{toggleError && (
<div className="px-5 py-3 flex items-center gap-2 text-sm text-red-600 dark:text-red-400 border-b border-gray-100 dark:border-slate-800">
<AlertTriangle className="w-4 h-4 flex-shrink-0" />{toggleError}
</div>
)}
{fleetLoading && <div className="p-8 text-center text-sm text-gray-400 dark:text-slate-500">Loading device state…</div>}
{!!fleetError && (
<div className="p-4 flex items-center gap-2 text-sm text-red-600 dark:text-red-400">
<AlertTriangle className="w-4 h-4 flex-shrink-0" />Failed: {(fleetError as Error).message}
</div>
)}
{!fleetLoading && !fleetError && devices.length === 0 && (
<div className="p-8 text-center text-sm text-gray-400 dark:text-slate-500">No online devices found.</div>
)}
{devices.length > 0 && (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-gray-200 dark:border-slate-700 bg-gray-50 dark:bg-slate-800/40">
<th className="px-4 py-2.5 text-left text-xs font-semibold text-gray-500 dark:text-slate-400 uppercase tracking-wide">Device</th>
<th className="px-4 py-2.5 text-left text-xs font-semibold text-gray-500 dark:text-slate-400 uppercase tracking-wide">Status</th>
<th className="px-4 py-2.5 text-left text-xs font-semibold text-gray-500 dark:text-slate-400 uppercase tracking-wide">Flows</th>
<th className="px-4 py-2.5 text-left text-xs font-semibold text-gray-500 dark:text-slate-400 uppercase tracking-wide">Last Flow</th>
<th className="px-4 py-2.5 text-right text-xs font-semibold text-gray-500 dark:text-slate-400 uppercase tracking-wide">Export</th>
</tr>
</thead>
<tbody>
{devices.map((d, i) => (
<tr key={d.id}
className={clsx('border-b border-gray-100 dark:border-slate-800 transition-colors hover:bg-blue-50 dark:hover:bg-slate-700/40',
i % 2 === 0 ? 'bg-white dark:bg-transparent' : 'bg-gray-50 dark:bg-slate-800/40')}>
<td className="px-4 py-3">
<div className="font-medium text-gray-900 dark:text-white">{d.name}</div>
<div className="font-mono text-xs text-gray-400 dark:text-slate-500">{d.ip_address}</div>
</td>
<td className="px-4 py-3">{deviceBadge(d)}</td>
<td className="px-4 py-3 text-gray-700 dark:text-slate-300">{d.flows_received.toLocaleString()}</td>
<td className="px-4 py-3 text-gray-500 dark:text-slate-400 text-xs">
{d.last_flow_at ? formatDistanceToNow(parseISO(d.last_flow_at), { addSuffix: true }) : '—'}
</td>
<td className="px-4 py-3 text-right">
<div className="flex justify-end">
<Toggle
checked={!!d.enabled && d.target_matches_collector}
onChange={v => handleDeviceToggle(d.id, v)}
disabled={!canWrite || !!d.error || togglePending === d.id || (addressMissing && !d.enabled)}
/>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
);
}
+2
View File
@@ -667,6 +667,8 @@ export default function SettingsPage() {
{[
{ key: 'retention_events_days', label: 'Events retention', desc: 'Auto-delete event log entries older than this many days' },
{ key: 'retention_clients_days', label: 'Client retention', desc: 'Auto-delete inactive client records not seen within this many days' },
{ key: 'netflow_retention_days', label: 'Traffic detail retention', desc: 'Auto-delete per-client NetFlow time-series data older than this many days' },
{ key: 'netflow_daily_retention_days', label: 'Traffic daily rollup retention', desc: 'Auto-delete per-client daily traffic totals older than this many days' },
].map(({ key, label, desc }) => (
<div key={key} className="flex items-center justify-between gap-4">
<div>
+261
View File
@@ -0,0 +1,261 @@
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import {
AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
PieChart, Pie, Cell, Legend,
} from 'recharts';
import { Activity, ArrowDown, ArrowUp, BarChart3, Settings2 } from 'lucide-react';
import { format, parseISO } from 'date-fns';
import clsx from 'clsx';
import { trafficApi } from '../services/api';
type Range = '1h' | '24h' | '7d' | '30d';
const RANGES: Range[] = ['1h', '24h', '7d', '30d'];
const APP_COLORS = [
'#3b82f6', '#8b5cf6', '#10b981', '#f59e0b', '#ef4444', '#06b6d4',
'#ec4899', '#84cc16', '#f97316', '#6366f1', '#14b8a6', '#a855f7',
'#64748b', '#0ea5e9', '#d946ef', '#22c55e',
];
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
if (bytes < 1024 ** 4) return `${(bytes / 1024 ** 3).toFixed(2)} GB`;
return `${(bytes / 1024 ** 4).toFixed(2)} TB`;
}
function timeFormatter(range: Range) {
return (t: string) => {
try {
const d = parseISO(t);
return range === '7d' || range === '30d' ? format(d, 'MMM d') : format(d, 'HH:mm');
} catch {
return t;
}
};
}
function clientLabel(c: { mac: string; custom_name: string | null; hostname: string | null; vendor: string | null }): string {
if (c.mac === 'unknown') return 'Unattributed (local)';
if (c.mac === 'other') return 'Other clients';
return c.custom_name || c.hostname || c.vendor || c.mac;
}
export default function TrafficAnalyticsPage() {
const [range, setRange] = useState<Range>('24h');
const navigate = useNavigate();
const { data: series = [], isLoading: seriesLoading } = useQuery({
queryKey: ['traffic-timeseries', range],
queryFn: () => trafficApi.timeseries(range).then(r => r.data),
refetchInterval: 60_000,
});
const { data: topClients = [], isLoading: clientsLoading } = useQuery({
queryKey: ['traffic-top-clients', range],
queryFn: () => trafficApi.topClients(range, 10).then(r => r.data),
refetchInterval: 60_000,
});
const { data: apps = [], isLoading: appsLoading } = useQuery({
queryKey: ['traffic-apps', range],
queryFn: () => trafficApi.apps(range).then(r => r.data),
refetchInterval: 60_000,
});
const isLoading = seriesLoading || clientsLoading || appsLoading;
const hasData = series.length > 0 || topClients.length > 0 || apps.length > 0;
const totalUpload = series.reduce((s, p) => s + p.upload, 0);
const totalDownload = series.reduce((s, p) => s + p.download, 0);
const totalAppBytes = apps.reduce((s, a) => s + a.bytes, 0);
const maxClientBytes = topClients[0]?.total_bytes || 1;
// Donut: top 8 categories, rest folded into "Other"
const donutData = (() => {
const top = apps.slice(0, 8);
const rest = apps.slice(8).reduce((s, a) => s + a.bytes, 0);
return rest > 0 ? [...top, { app: 'Other', bytes: rest }] : top;
})();
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between flex-wrap gap-3">
<div>
<h1 className="text-xl font-bold text-gray-900 dark:text-white">Traffic</h1>
<p className="text-sm text-gray-500 dark:text-slate-400">Per-client traffic analytics from NetFlow/IPFIX</p>
</div>
<div className="flex items-center gap-2">
<div className="card p-1 flex rounded-lg gap-1">
{RANGES.map(r => (
<button key={r} onClick={() => setRange(r)}
className={clsx('px-3 py-1 rounded-md text-sm font-medium transition-colors',
range === r
? 'bg-blue-600 text-white shadow-sm'
: 'text-gray-600 dark:text-slate-300 hover:bg-gray-100 dark:hover:bg-slate-700')}>
{r}
</button>
))}
</div>
<Link to="/network-services/netflow"
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-gray-300 dark:border-slate-600 text-sm text-gray-600 dark:text-slate-300 hover:bg-gray-100 dark:hover:bg-slate-700 transition-colors">
<Settings2 className="w-3.5 h-3.5" />Configure
</Link>
</div>
</div>
{/* Empty state */}
{!isLoading && !hasData && (
<div className="card p-12 text-center space-y-3">
<Activity className="w-10 h-10 mx-auto text-gray-300 dark:text-slate-600" />
<h2 className="text-sm font-semibold text-gray-700 dark:text-slate-200">No traffic data yet</h2>
<p className="text-sm text-gray-500 dark:text-slate-400 max-w-md mx-auto">
Enable the NetFlow collector and turn on traffic export for your routers to start
collecting per-client usage and protocol analytics.
</p>
<Link to="/network-services/netflow"
className="inline-flex items-center gap-1.5 px-4 py-1.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition-colors">
<Settings2 className="w-3.5 h-3.5" />Set up NetFlow
</Link>
</div>
)}
{hasData && (
<>
{/* Totals */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="card p-4 flex items-center gap-3">
<div className="p-2 rounded-lg bg-blue-100 dark:bg-blue-900/30">
<ArrowDown className="w-5 h-5 text-blue-600 dark:text-blue-400" />
</div>
<div>
<div className="text-xs text-gray-400 dark:text-slate-500">Download ({range})</div>
<div className="text-lg font-bold text-gray-900 dark:text-white">{formatBytes(totalDownload)}</div>
</div>
</div>
<div className="card p-4 flex items-center gap-3">
<div className="p-2 rounded-lg bg-violet-100 dark:bg-violet-900/30">
<ArrowUp className="w-5 h-5 text-violet-600 dark:text-violet-400" />
</div>
<div>
<div className="text-xs text-gray-400 dark:text-slate-500">Upload ({range})</div>
<div className="text-lg font-bold text-gray-900 dark:text-white">{formatBytes(totalUpload)}</div>
</div>
</div>
</div>
{/* Throughput chart */}
<div className="card p-5">
<h2 className="text-sm font-semibold text-gray-700 dark:text-slate-200 mb-4">Network Traffic</h2>
<ResponsiveContainer width="100%" height={280}>
<AreaChart data={series}>
<defs>
<linearGradient id="dl" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#3b82f6" stopOpacity={0.35} />
<stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
</linearGradient>
<linearGradient id="ul" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#8b5cf6" stopOpacity={0.35} />
<stop offset="95%" stopColor="#8b5cf6" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" className="stroke-gray-200 dark:stroke-slate-700" />
<XAxis dataKey="time" tickFormatter={timeFormatter(range)} tick={{ fontSize: 11 }} stroke="currentColor" />
<YAxis tickFormatter={v => formatBytes(v)} tick={{ fontSize: 11 }} width={70} stroke="currentColor" />
<Tooltip
labelFormatter={t => { try { return format(parseISO(String(t)), 'MMM d, HH:mm'); } catch { return String(t); } }}
formatter={(value: number, name: string) => [formatBytes(value), name === 'download' ? 'Download' : 'Upload']}
/>
<Legend formatter={(v: string) => (v === 'download' ? 'Download' : 'Upload')} />
<Area type="monotone" dataKey="download" stroke="#3b82f6" fill="url(#dl)" strokeWidth={2} />
<Area type="monotone" dataKey="upload" stroke="#8b5cf6" fill="url(#ul)" strokeWidth={2} />
</AreaChart>
</ResponsiveContainer>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Top talkers */}
<div className="card overflow-hidden">
<div className="px-5 py-3 border-b border-gray-200 dark:border-slate-700 flex items-center gap-2">
<BarChart3 className="w-4 h-4 text-blue-500" />
<h2 className="text-sm font-semibold text-gray-700 dark:text-slate-200">Top Talkers</h2>
</div>
{topClients.length === 0
? <div className="p-6 text-center text-sm text-gray-400 dark:text-slate-500">No client traffic recorded.</div>
: (
<div className="divide-y divide-gray-100 dark:divide-slate-800">
{topClients.map(c => {
const isReal = c.mac !== 'unknown' && c.mac !== 'other';
return (
<div key={c.mac}
onClick={() => isReal && navigate(`/clients/${encodeURIComponent(c.mac)}`)}
className={clsx('px-5 py-3', isReal && 'cursor-pointer hover:bg-blue-50 dark:hover:bg-slate-700/40 transition-colors')}>
<div className="flex items-center justify-between mb-1.5">
<div className="min-w-0">
<span className="text-sm font-medium text-gray-900 dark:text-white truncate">{clientLabel(c)}</span>
{isReal && (
<span className="ml-2 font-mono text-xs text-gray-400 dark:text-slate-500">{c.ip_address || c.mac}</span>
)}
</div>
<span className="text-sm font-semibold text-gray-700 dark:text-slate-200 flex-shrink-0">{formatBytes(c.total_bytes)}</span>
</div>
<div className="h-1.5 rounded-full bg-gray-100 dark:bg-slate-700 overflow-hidden">
<div className="h-full rounded-full bg-blue-500" style={{ width: `${Math.max(2, (c.total_bytes / maxClientBytes) * 100)}%` }} />
</div>
<div className="mt-1 flex gap-3 text-xs text-gray-400 dark:text-slate-500">
<span className="inline-flex items-center gap-0.5"><ArrowDown className="w-3 h-3" />{formatBytes(c.download_bytes)}</span>
<span className="inline-flex items-center gap-0.5"><ArrowUp className="w-3 h-3" />{formatBytes(c.upload_bytes)}</span>
</div>
</div>
);
})}
</div>
)}
</div>
{/* App categories */}
<div className="card overflow-hidden">
<div className="px-5 py-3 border-b border-gray-200 dark:border-slate-700 flex items-center gap-2">
<Activity className="w-4 h-4 text-indigo-500" />
<h2 className="text-sm font-semibold text-gray-700 dark:text-slate-200">Traffic by Application</h2>
</div>
{apps.length === 0
? <div className="p-6 text-center text-sm text-gray-400 dark:text-slate-500">No application data recorded.</div>
: (
<div className="p-5">
<ResponsiveContainer width="100%" height={220}>
<PieChart>
<Pie data={donutData} dataKey="bytes" nameKey="app" innerRadius={55} outerRadius={85} paddingAngle={2}>
{donutData.map((entry, i) => (
<Cell key={entry.app} fill={APP_COLORS[i % APP_COLORS.length]} />
))}
</Pie>
<Tooltip formatter={(value: number, name: string) => [formatBytes(value), name]} />
</PieChart>
</ResponsiveContainer>
<div className="mt-2 space-y-1.5">
{apps.slice(0, 10).map((a, i) => (
<div key={a.app} className="flex items-center gap-2 text-sm">
<span className="w-2.5 h-2.5 rounded-sm flex-shrink-0" style={{ backgroundColor: APP_COLORS[i % APP_COLORS.length] }} />
<span className="text-gray-700 dark:text-slate-300 flex-1 truncate">{a.app}</span>
<span className="text-gray-500 dark:text-slate-400 text-xs">
{totalAppBytes > 0 ? `${((a.bytes / totalAppBytes) * 100).toFixed(1)}%` : ''}
</span>
<span className="font-medium text-gray-900 dark:text-white w-20 text-right">{formatBytes(a.bytes)}</span>
</div>
))}
</div>
</div>
)}
</div>
</div>
</>
)}
</div>
);
}
+67
View File
@@ -775,6 +775,73 @@ export const networkServicesApi = {
api.put<NS[]>(`/network-services/wireguard/peer/${encodeURIComponent(id)}`, body, { params: { deviceId } }),
deleteWireGuardPeer: (deviceId: number, id: string) =>
api.delete(`/network-services/wireguard/peer/${encodeURIComponent(id)}`, { params: { deviceId } }),
// ── NetFlow ───────────────────────────────────────────────────────────────
netflowFleet: () =>
api.get<{
collector: { address: string; port: number; version: string; listening: boolean };
devices: NetflowDeviceState[];
}>('/network-services/netflow/fleet', { timeout: 60_000 }),
getNetflow: (deviceId: number) =>
api.get<{ settings: NS | null; targets: NS[]; target_matches_collector: boolean }>(
'/network-services/netflow', { params: { deviceId } }
),
setNetflow: (deviceId: number, enabled: boolean) =>
api.put<{ settings: NS | null; targets: NS[]; target_matches_collector: boolean }>(
'/network-services/netflow', { enabled }, { params: { deviceId } }
),
};
export interface NetflowDeviceState {
id: number;
name: string;
ip_address: string;
enabled: boolean | null;
interfaces: string;
targets: { id: string; dst_address: string; port: number; version: string; disabled: boolean }[];
target_matches_collector: boolean;
flows_received: number;
last_flow_at: string | null;
error?: string;
}
// ─── Traffic Analytics (NetFlow) ──────────────────────────────────────────────
export interface ClientTrafficPoint { time: string; upload: number; download: number }
export interface TrafficTopClient {
mac: string;
upload_bytes: number;
download_bytes: number;
total_bytes: number;
hostname: string | null;
custom_name: string | null;
vendor: string | null;
ip_address: string | null;
}
export interface TrafficApp { app: string; bytes: number }
export interface TrafficCollectorStats {
listening: boolean;
port: number;
packetsReceived: number;
flowsDecoded: number;
flowsAttributed: number;
packetsFromUnknownExporter: number;
recordsWithoutTemplate: number;
exporters: { deviceId: number; deviceName: string; packets: number; flows: number; lastSeen: string | null }[];
}
export const trafficApi = {
status: () => api.get<TrafficCollectorStats>('/traffic/status'),
timeseries: (range = '24h') =>
api.get<ClientTrafficPoint[]>('/traffic/timeseries', { params: { range } }),
topClients: (range = '24h', limit = 10) =>
api.get<TrafficTopClient[]>('/traffic/top-clients', { params: { range, limit } }),
apps: (range = '24h', mac?: string) =>
api.get<TrafficApp[]>('/traffic/apps', { params: { range, mac } }),
client: (mac: string, range = '24h') =>
api.get<{ series: ClientTrafficPoint[]; apps: TrafficApp[] }>(
`/traffic/client/${encodeURIComponent(mac)}`, { params: { range } }
),
};
// ─── Maintenance Windows ──────────────────────────────────────────────────────
+2
View File
@@ -179,6 +179,8 @@ export interface Client {
client_type: 'wired' | 'wireless';
active: boolean;
last_seen?: string;
/** Today's NetFlow upload+download total (0 when NetFlow is not collecting). */
traffic_today_bytes?: number;
}
export interface Backup {
+1 -1
View File
@@ -1 +1 @@
export const APP_VERSION = 'v0.12.3 Beta';
export const APP_VERSION = 'v0.13.0 Beta';