Răsfoiți Sursa

fix(devices): stop inventing a lease and a hostname for bare MACs (#2029)

Nacho 3 săptămâni în urmă
părinte
comite
50ddb09a98

+ 3 - 1
app/public/locales/en/translation.json

@@ -404,7 +404,9 @@
     "never": "never",
     "notFound": "Page not found",
     "tunnelIp": "Tunnel IP",
-    "roleExternal": "External"
+    "roleExternal": "External",
+    "leaseExpired": "Expired",
+    "leaseRenewsDays": "renews in {{d}}d {{h}}h {{min}}min"
   },
   "devices": {
     "badges": {

+ 3 - 1
app/public/locales/es/translation.json

@@ -404,7 +404,9 @@
     "never": "nunca",
     "notFound": "Página no encontrada",
     "tunnelIp": "IP túnel",
-    "roleExternal": "Externo"
+    "roleExternal": "Externo",
+    "leaseExpired": "Caducada",
+    "leaseRenewsDays": "renueva en {{d}}d {{h}}h {{min}}min"
   },
   "devices": {
     "badges": {

+ 14 - 4
app/src/i18n.ts

@@ -126,16 +126,26 @@ export function fmtUptime(uptime: string): string {
 }
 
 const LEASE_RE = /^renueva en\s+(\d+)\s*h(?:\s*(\d+)\s*min)?$/
+// #1818: concesiones de más de un día ("renueva en 1d 4h 30min").
+const LEASE_DAYS_RE = /^renueva en\s+(\d+)d(?:\s+(\d+)h)?(?:\s+(\d+)min)?$/
 
 /** Concesión DHCP canónica: "renueva en 7 h 48 min" / "IP fija (reserva)" */
 export function dhcpLease(s: string): string {
   const t = s.trim()
   if (t === 'IP fija (reserva)') return i18n.t('common.staticLease')
+  // #1818: un lease caducado es un hecho, no un texto en inglés incrustado.
+  if (t === 'Expirado') return i18n.t('common.leaseExpired')
   const m = LEASE_RE.exec(t)
-  if (!m) return s
-  const h = Number(m[1])
-  if (!m[2]) return i18n.t('common.leaseRenewsH', { h })
-  return i18n.t('common.leaseRenews', { h, min: Number(m[2]) })
+  if (m) {
+    const h = Number(m[1])
+    if (!m[2]) return i18n.t('common.leaseRenewsH', { h })
+    return i18n.t('common.leaseRenews', { h, min: Number(m[2]) })
+  }
+  const md = LEASE_DAYS_RE.exec(t)
+  if (md) {
+    return i18n.t('common.leaseRenewsDays', { d: Number(md[1]), h: Number(md[2] ?? 0), min: Number(md[3] ?? 0) })
+  }
+  return s
 }
 
 const HEALTH_KEYS: Record<string, string> = {

+ 58 - 0
app/src/lib/clientLabels.ts

@@ -0,0 +1,58 @@
+/** #1818: etiquetas de cliente que no pueden inventarse.
+ *
+ * Una MAC que solo existe en una FDB (el NMRP de Netgear al reiniciar para
+ * flashear firmware) no tiene concesión DHCP ni hostname. Antes se pintaba como
+ * `Static IP (reservation)` estando online y como `Expired` al desaparecer, y un
+ * nombre vacío producía el hostname "cliente" (slug de cadena vacía).
+ *
+ * Aquí van las dos decisiones, puras, para poder probarlas sin montar la UI.
+ */
+
+/** Formatea segundos restantes del lease a "2h 15min" · "1d 4h" · "45min". */
+export function formatLeaseRemaining(totalSeconds: number): string {
+  const days = Math.floor(totalSeconds / 86400)
+  const hours = Math.floor((totalSeconds % 86400) / 3600)
+  const minutes = Math.floor((totalSeconds % 3600) / 60)
+  const parts: string[] = []
+  if (days > 0) parts.push(`${days}d`)
+  if (hours > 0) parts.push(`${hours}h`)
+  if (minutes > 0 || parts.length === 0) parts.push(`${minutes}min`)
+  return parts.join(' ')
+}
+
+/**
+ * Etiqueta del lease en formato canónico (el que traduce `dhcpLease()`).
+ * Sin dato (`null`/`undefined`) NO se inventa nada: ni reserva estática ni
+ * caducidad. Un 0 sí es un lease caducado de verdad.
+ */
+export function leaseLabel(remaining: number | null | undefined): string {
+  if (remaining == null) return '—'
+  if (remaining <= 0) return 'Expirado'
+  return `renueva en ${formatLeaseRemaining(remaining)}`
+}
+
+/** El fallback del server sin hostname es la MAC (con dos puntos o guiones). */
+export function isMACName(name: string): boolean {
+  return /^([0-9a-f]{2}[:-]){5}[0-9a-f]{2}$/i.test(name.trim())
+}
+
+function slug(name: string): string {
+  return (
+    name
+      .toLowerCase()
+      .normalize('NFD')
+      .replace(/[\u0300-\u036f]/g, '')
+      .replace(/[^a-z0-9]+/g, '-')
+      .replace(/^-|-$/g, '') || 'cliente'
+  )
+}
+
+/**
+ * Hostname del cliente. La MAC o un nombre vacío no son un hostname: el slug de
+ * una cadena vacía producía "cliente" en el detalle de una entrada sin nombre.
+ */
+export function hostnameLabel(name: string): string {
+  const n = name.trim()
+  if (n === '' || isMACName(n)) return ''
+  return slug(n)
+}

+ 3 - 44
app/src/pages/devices-data.ts

@@ -15,6 +15,7 @@
  */
 import type { Device } from '@/data/mock'
 import { devices as canonDevices } from '@/data/mock'
+import { hostnameLabel, leaseLabel } from '@/lib/clientLabels'
 
 // ---------------------------------------------------------------------------
 // Tipos
@@ -124,48 +125,11 @@ const TYPE_TO_GROUP: Record<Device['type'], FilterGroup> = {
   desconocido: 'otros',
 }
 
-function slug(name: string): string {
-  return (
-    name
-      .toLowerCase()
-      .normalize('NFD')
-      .replace(/[̀-ͯ]/g, '')
-      .replace(/[^a-z0-9]+/g, '-')
-      .replace(/^-|-$/g, '') || 'cliente'
-  )
-}
-
-/** Formatea segundos restantes del lease a "2h 15min" · "1d 4h" · "45min". */
-function formatLeaseRemaining(totalSeconds: number): string {
-  const days = Math.floor(totalSeconds / 86400)
-  const hours = Math.floor((totalSeconds % 86400) / 3600)
-  const minutes = Math.floor((totalSeconds % 3600) / 60)
-  const parts: string[] = []
-  if (days > 0) parts.push(`${days}d`)
-  if (hours > 0) parts.push(`${hours}h`)
-  if (minutes > 0 || parts.length === 0) parts.push(`${minutes}min`)
-  return parts.join(' ')
-}
-
 /** Detalles por defecto para un cliente que la API reporta sin metadatos. */
 function defaultDetails(d: Device): Omit<ClientDevice, keyof Device> {
-  // #1315: el lease con tiempo restante se muestra aunque el cliente esté
-  // desconectado (dnsmasq conserva la concesión hasta su expiración; antes
-  // se pintaba "Expired" a TODO lo offline, con tiempo restante o sin él).
-  const remaining = d.leaseRemaining
-  const leaseActive = remaining != null && remaining > 0
-  const leaseText =
-    remaining != null && remaining > 0
-      ? `renews in ${formatLeaseRemaining(remaining)}`
-      : remaining === 0
-        ? 'Expired'
-        : 'Static IP (reservation)'
   return {
-    // #1315: cuando el nombre es la propia MAC (sin hostname conocido), el
-    // campo Hostname queda vacío: la MAC ya tiene su campo en la vista y el
-    // slug en formato guionado ("34-5f-45-...") se leía como hostname.
-    hostname: isMACName(d.name) ? '' : slug(d.name),
-    dhcpLease: leaseActive || d.online ? leaseText : 'Expired',
+    hostname: hostnameLabel(d.name),
+    dhcpLease: leaseLabel(d.leaseRemaining),
     traffic24hRx: '—',
     traffic24hTx: '—',
     adguard: true,
@@ -173,11 +137,6 @@ function defaultDetails(d: Device): Omit<ClientDevice, keyof Device> {
   }
 }
 
-/** #1315: el fallback del server sin hostname es la MAC (colons o dashes). */
-function isMACName(name: string): boolean {
-  return /^([0-9a-f]{2}[:-]){5}[0-9a-f]{2}$/i.test(name.trim())
-}
-
 /** Metadatos de cliente que pueden venir inline (canon JSON / API demo).
  *  firstSeen/lastSeen NO van aquí: viajan en Device como epochs (#954), y
  *  newThisWeek tampoco: es alta de device_seen, no detalle del demo. */