Selaa lähdekoodia

feat(ui): show DNS activity per device and per network

Device detail gets a lazy panel with the top domains of the last hour or day, blocked ones highlighted, and an explicit notice when the query log is disabled, anonymized or unreachable. The AdGuard card on the overview adds the network-wide top and the domains seen for the first time.

Hidden in demo mode: the demo shows a simulated AdGuard and there is no aggregate to read.

Refs #2078
gnacho 2 viikkoa sitten
vanhempi
sitoutus
bf4e5d3788

+ 24 - 0
app/public/locales/en/translation.json

@@ -607,6 +607,17 @@
       "unpinHint": "Stop restoring this filter set when opening clients",
       "pinned": "Filters pinned as the default",
       "unpinned": "Filters unpinned"
+    },
+    "dns": {
+      "title": "DNS activity",
+      "queries": "{{n}} queries",
+      "blocked": "{{n}} blocked",
+      "unavailable": "DNS activity needs the AdGuard Home integration. Add it in Settings > Integrations.",
+      "disabled": "The AdGuard query log is disabled, so there is nothing to attribute to this device.",
+      "anonymized": "AdGuard is anonymizing client IPs, so queries cannot be attributed to a device. Turn off anonymize_client_ip.",
+      "error": "Could not read the DNS activity. Check that AdGuard Home is reachable.",
+      "empty": "No DNS queries recorded for this device in the selected window.",
+      "gap": "Some entries were rotated out of the AdGuard log before they could be read, so a stretch of this window is missing."
     }
   },
   "home": {
@@ -3165,5 +3176,18 @@
     "staleClean": "Clean up ports",
     "staleCleaned": "{{count}} stale ports removed from the profile",
     "staleNothing": "No ports can be cleaned up"
+  },
+  "dns": {
+    "overview": {
+      "title": "DNS activity (24 h)",
+      "totals": "{{queries}} queries, {{blocked}} blocked",
+      "newDomains": "New domains",
+      "unavailable": "Add the AdGuard Home integration to see which domains the network asks for.",
+      "disabled": "The AdGuard query log is disabled, so per-domain activity is not available.",
+      "anonymized": "AdGuard is anonymizing client IPs: domains are recorded but cannot be linked to a device.",
+      "error": "Could not read the DNS activity from AdGuard.",
+      "empty": "No DNS activity recorded yet. The first read can take a minute.",
+      "gap": "A stretch of the window is missing because the AdGuard log rotated before it was read."
+    }
   }
 }

+ 24 - 0
app/public/locales/es/translation.json

@@ -607,6 +607,17 @@
       "unpinHint": "Dejar de restaurar este conjunto al abrir clientes",
       "pinned": "Filtros fijados como defecto",
       "unpinned": "Filtros sin fijar"
+    },
+    "dns": {
+      "title": "Actividad DNS",
+      "queries": "{{n}} consultas",
+      "blocked": "{{n}} bloqueadas",
+      "unavailable": "La actividad DNS necesita la integración con AdGuard Home. Añádela en Ajustes > Integraciones.",
+      "disabled": "El registro de consultas de AdGuard está desactivado, así que no hay nada que atribuir a este dispositivo.",
+      "anonymized": "AdGuard está anonimizando las IPs de los clientes, así que las consultas no se pueden atribuir. Desactiva anonymize_client_ip.",
+      "error": "No se pudo leer la actividad DNS. Comprueba que AdGuard Home responde.",
+      "empty": "No hay consultas DNS registradas para este dispositivo en la ventana elegida.",
+      "gap": "Parte de las entradas rotaron del registro de AdGuard antes de poder leerse, así que falta un tramo de esta ventana."
     }
   },
   "home": {
@@ -3165,5 +3176,18 @@
     "staleClean": "Limpiar puertos",
     "staleCleaned": "{{count}} puertos obsoletos quitados del perfil",
     "staleNothing": "No hay puertos que se puedan limpiar"
+  },
+  "dns": {
+    "overview": {
+      "title": "Actividad DNS (24 h)",
+      "totals": "{{queries}} consultas, {{blocked}} bloqueadas",
+      "newDomains": "Dominios nuevos",
+      "unavailable": "Añade la integración con AdGuard Home para ver qué dominios pide la red.",
+      "disabled": "El registro de consultas de AdGuard está desactivado, así que no hay actividad por dominio.",
+      "anonymized": "AdGuard anonimiza las IPs de los clientes: los dominios se registran pero no se pueden asociar a un dispositivo.",
+      "error": "No se pudo leer la actividad DNS de AdGuard.",
+      "empty": "Aún no hay actividad DNS registrada. La primera lectura puede tardar un minuto.",
+      "gap": "Falta un tramo de la ventana porque el registro de AdGuard rotó antes de leerse."
+    }
   }
 }

+ 133 - 0
app/src/components/DNSOverviewBlock.tsx

@@ -0,0 +1,133 @@
+/**
+ * DNSOverviewBlock — vista de red de la actividad DNS (#2078): top de
+ * dominios y dominios vistos por primera vez en la ventana.
+ *
+ * Vive dentro de la tarjeta de AdGuard Home en el Resumen: es la misma
+ * integración, sin abrir un menú nuevo para dos listas.
+ */
+import { useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useNetPulse } from '@/data/DataProvider'
+import { fmtInt } from '@/data/mock'
+
+interface DNSDomain {
+  domain: string
+  queries: number
+  blocked: number
+}
+
+interface DNSNewDomain {
+  domain: string
+  mac: string
+  first_seen_ms: number
+}
+
+interface DNSResponse {
+  status: string
+  gap_ts: number
+  total_queries: number
+  total_blocked: number
+  top: DNSDomain[] | null
+  new_domains: DNSNewDomain[] | null
+}
+
+export function DNSOverviewBlock() {
+  const { t } = useTranslation()
+  const { isDemo } = useNetPulse()
+    const [data, setData] = useState<DNSResponse | null>(null)
+  const [failed, setFailed] = useState(false)
+
+  useEffect(() => {
+    const ctl = new AbortController()
+    fetch('/api/dns/overview?window=24h', { signal: ctl.signal, credentials: 'same-origin' })
+      .then((res) => (res.ok ? res.json() : Promise.reject(new Error(String(res.status)))))
+      .then((body: DNSResponse) => setData(body))
+      .catch((err: Error) => {
+        if (err.name !== 'AbortError') setFailed(true)
+      })
+    return () => ctl.abort()
+  }, [])
+
+  // La demo enseña un AdGuard simulado: pedir el agregado real daría un
+  // aviso de "sin integración" que contradice la tarjeta.
+  // La demo enseña un AdGuard simulado: pedir el agregado real daría un
+  // aviso de "sin integración" que contradice la tarjeta.
+  if (isDemo || failed) return null
+  if (!data) return <div className="mt-4 h-8 animate-pulse rounded-lg bg-elevated" aria-hidden />
+
+  const top = data.top ?? []
+  const fresh = data.new_domains ?? []
+  const max = top.reduce((m, d) => Math.max(m, d.queries), 0)
+
+  let notice: string | null = null
+  if (data.status === 'unavailable') notice = t('dns.overview.unavailable')
+  else if (data.status === 'disabled') notice = t('dns.overview.disabled')
+  else if (data.status === 'anonymized') notice = t('dns.overview.anonymized')
+  else if (data.status === 'error') notice = t('dns.overview.error')
+  else if (top.length === 0) notice = t('dns.overview.empty')
+
+  if (notice) {
+    return (
+      <p className="mt-4 rounded-xl bg-elevated px-3 py-2 text-caption leading-relaxed text-text-muted">
+        {notice}
+      </p>
+    )
+  }
+
+  return (
+    <div className="mt-4 border-t border-border/60 pt-3">
+      <div className="flex items-baseline justify-between">
+        <div className="text-label uppercase text-text-muted">{t('dns.overview.title')}</div>
+        <div className="font-mono text-mono-sm text-text-secondary">
+          {t('dns.overview.totals', {
+            queries: fmtInt(data.total_queries),
+            blocked: fmtInt(data.total_blocked),
+          })}
+        </div>
+      </div>
+
+      <div className="mt-2 space-y-1.5">
+        {top.slice(0, 3).map((d) => (
+          <div key={d.domain} className="flex items-center gap-2">
+            <span
+              className="w-36 shrink-0 truncate font-mono text-mono-sm text-text-secondary"
+              title={d.domain}
+              translate="no"
+            >
+              {d.domain}
+            </span>
+            <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-border/50">
+              <div
+                className={d.blocked > 0 ? 'h-full rounded-full bg-ok' : 'h-full rounded-full bg-accent'}
+                style={{ width: `${max > 0 ? (d.queries / max) * 100 : 0}%` }}
+              />
+            </div>
+            <span className="w-10 shrink-0 text-right font-mono text-mono-sm text-text-primary">
+              {fmtInt(d.queries)}
+            </span>
+          </div>
+        ))}
+      </div>
+
+      {fresh.length > 0 && (
+        <div className="mt-3">
+          <div className="text-label uppercase text-text-muted">{t('dns.overview.newDomains')}</div>
+          <ul className="mt-1 space-y-0.5">
+            {fresh.slice(0, 3).map((d) => (
+              <li key={d.domain} className="flex items-baseline justify-between gap-2">
+                <span className="truncate font-mono text-mono-sm text-text-secondary" translate="no">
+                  {d.domain}
+                </span>
+                <span className="shrink-0 font-mono text-caption text-text-muted">{d.mac || '—'}</span>
+              </li>
+            ))}
+          </ul>
+        </div>
+      )}
+
+      {data.gap_ts > 0 && (
+        <p className="mt-2 text-caption text-text-muted">{t('dns.overview.gap')}</p>
+      )}
+    </div>
+  )
+}

+ 135 - 0
app/src/components/DeviceDNSPanel.tsx

@@ -0,0 +1,135 @@
+/**
+ * DeviceDNSPanel — actividad DNS de un dispositivo desde el agregado del
+ * query log de AdGuard (#2078).
+ *
+ * Se carga al abrir el detalle (lazy), con ventana de 1 h o 24 h. Si la
+ * ingesta no puede atribuir consultas, el panel lo dice: deshabilitado,
+ * IPs anonimizadas, integración ausente o un hueco por rotación del log.
+ */
+import { useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { ShieldBan } from 'lucide-react'
+import { SegmentedControl } from '@/components/SegmentedControl'
+import { fmtInt } from '@/data/mock'
+
+interface DNSDomain {
+  domain: string
+  queries: number
+  blocked: number
+}
+
+interface DNSResponse {
+  status: string
+  window: string
+  gap_ts: number
+  total_queries: number
+  total_blocked: number
+  top: DNSDomain[] | null
+}
+
+type WindowKey = '1h' | '24h'
+
+export function DeviceDNSPanel({ mac }: { mac: string }) {
+  const { t } = useTranslation()
+  const [win, setWin] = useState<WindowKey>('24h')
+  const [data, setData] = useState<DNSResponse | null>(null)
+  const [failed, setFailed] = useState(false)
+
+  useEffect(() => {
+    const ctl = new AbortController()
+    setData(null)
+    setFailed(false)
+    fetch(`/api/devices/${encodeURIComponent(mac)}/dns?window=${win}`, {
+      signal: ctl.signal,
+      credentials: 'same-origin',
+    })
+      .then((res) => (res.ok ? res.json() : Promise.reject(new Error(String(res.status)))))
+      .then((body: DNSResponse) => setData(body))
+      .catch((err: Error) => {
+        if (err.name !== 'AbortError') setFailed(true)
+      })
+    return () => ctl.abort()
+  }, [mac, win])
+
+  const top = data?.top ?? []
+  const max = top.reduce((m, d) => Math.max(m, d.queries), 0)
+
+  let notice: string | null = null
+  if (failed) notice = t('devices.dns.error')
+  else if (data) {
+    if (data.status === 'unavailable') notice = t('devices.dns.unavailable')
+    else if (data.status === 'disabled') notice = t('devices.dns.disabled')
+    else if (data.status === 'anonymized') notice = t('devices.dns.anonymized')
+    else if (data.status === 'error') notice = t('devices.dns.error')
+    else if (top.length === 0) notice = t('devices.dns.empty')
+  }
+
+  return (
+    <div className="border-t border-border/60 px-4 py-4 md:px-5">
+      <div className="flex flex-wrap items-center justify-between gap-2">
+        <div className="text-label uppercase text-text-muted">{t('devices.dns.title')}</div>
+        <SegmentedControl<WindowKey>
+          size="sm"
+          value={win}
+          onChange={setWin}
+          ariaLabel={t('devices.dns.title')}
+          options={[
+            { value: '1h', label: '1 h' },
+            { value: '24h', label: '24 h' },
+          ]}
+        />
+      </div>
+
+      {!data && !failed && (
+        <div className="mt-3 h-10 animate-pulse rounded-lg bg-elevated" aria-hidden />
+      )}
+
+      {notice && (
+        <p className="mt-3 rounded-lg bg-elevated px-3 py-2 text-caption leading-relaxed text-text-muted">
+          {notice}
+        </p>
+      )}
+
+      {data && !notice && (
+        <>
+          <div className="mt-3 flex items-baseline gap-4 text-caption text-text-muted">
+            <span>
+              {t('devices.dns.queries', { n: fmtInt(data.total_queries) })}
+            </span>
+            {data.total_blocked > 0 && (
+              <span className="inline-flex items-center gap-1 text-ok">
+                <ShieldBan className="h-3.5 w-3.5" strokeWidth={1.75} />
+                {t('devices.dns.blocked', { n: fmtInt(data.total_blocked) })}
+              </span>
+            )}
+          </div>
+          <div className="mt-3 space-y-2">
+            {top.slice(0, 8).map((d) => (
+              <div key={d.domain} className="flex items-center gap-2">
+                <span
+                  className="w-40 shrink-0 truncate font-mono text-mono-sm text-text-secondary"
+                  title={d.domain}
+                  translate="no"
+                >
+                  {d.domain}
+                </span>
+                <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-border/50">
+                  <div
+                    className={d.blocked > 0 ? 'h-full rounded-full bg-ok' : 'h-full rounded-full bg-accent'}
+                    style={{ width: `${max > 0 ? (d.queries / max) * 100 : 0}%` }}
+                  />
+                </div>
+                <span className="w-12 shrink-0 text-right font-mono text-mono-sm text-text-primary">
+                  {fmtInt(d.queries)}
+                </span>
+              </div>
+            ))}
+          </div>
+          {data.gap_ts > 0 && (
+            <p className="mt-3 text-caption text-text-muted">{t('devices.dns.gap')}</p>
+          )}
+        </>
+      )}
+    </div>
+  )
+}

+ 5 - 1
app/src/pages/Devices.tsx

@@ -31,6 +31,7 @@ import { fmtEs, signalLevel } from '@/data/mock'
 import { useNetPulse } from '@/data/DataProvider'
 import { useDashboard } from '@/hooks/useDashboard'
 import { useWeakSignalDbm } from '@/hooks/useWeakSignalDbm'
+import { DeviceDNSPanel } from '@/components/DeviceDNSPanel'
 import { DeviceEditSheet } from '@/components/DeviceEditSheet'
 import { OnboardingIntake } from '@/components/OnboardingIntake'
 import { cn, copyToClipboard, fetchJson } from '@/lib/utils'
@@ -901,9 +902,10 @@ function DeviceDetail({
   onEdit: () => void
 }) {
   const { t } = useTranslation()
-  const { adguard } = useNetPulse()
+  const { adguard, isDemo } = useNetPulse()
   const hasAdGuard = Boolean(adguard.host)
   return (
+    <div>
     <div className="relative grid grid-cols-2 gap-x-4 gap-y-4 px-4 py-4 md:grid-cols-3 md:px-5">
       <DetailItem label="MAC" mono>
         {device.mac}
@@ -974,6 +976,8 @@ function DeviceDetail({
         {t('devices.edit.action')}
       </button>
     </div>
+    {!isDemo && <DeviceDNSPanel mac={device.mac} />}
+    </div>
   )
 }
 

+ 2 - 0
app/src/sections/GatewayServices.tsx

@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next'
 import { relTime } from '@/i18n'
 import { fmtEs, fmtInt } from '@/data/mock'
 import type { PeerType, WGPeer } from '@/data/mock'
+import { DNSOverviewBlock } from '@/components/DNSOverviewBlock'
 import { useNetPulse } from '@/data/DataProvider'
 import { CountUp } from '@/components/CountUp'
 import { ServicePanel } from '@/components/ServicePanel'
@@ -177,6 +178,7 @@ export function AdGuardCard({ index = 0 }: { index?: number }) {
             </div>
           ))}
         </div>
+        <DNSOverviewBlock />
           </>
         )}
       </ServicePanel>