Просмотр исходного кода

fase6(app): tarjeta Notificaciones push en Ajustes + capa de datos push + i18n es/en

- src/data/push.ts: getVapidKey/postPushSubscribe/postPushUnsubscribe
  contra el contrato SPEC-PUSH, urlBase64ToUint8Array y pushContext().
- Settings.tsx: PushNotificationsCard con estados loading, activadas,
  desactivadas, permiso denegado, no soportado, aviso HTTPS en LAN HTTP
  y demo local degradada (sin simulacion).
- Flujo activar: requestPermission -> GET vapid -> pushManager.subscribe
  -> POST subscribe (rollback local si el servidor no la acepta).
- i18n es/en completo; notif.note actualizado.
agent 4 месяцев назад
Родитель
Сommit
7fed78c42c
4 измененных файлов с 323 добавлено и 2 удалено
  1. 20 1
      app/public/locales/en/translation.json
  2. 20 1
      app/public/locales/es/translation.json
  3. 92 0
      app/src/data/push.ts
  4. 191 0
      app/src/pages/Settings.tsx

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

@@ -569,7 +569,7 @@
       "badge": "Alerts badge in the navigation",
       "badge": "Alerts badge in the navigation",
       "badgeCaption": "Counter next to \"Alerts\"",
       "badgeCaption": "Counter next to \"Alerts\"",
       "caption": "In-app notices",
       "caption": "In-app notices",
-      "note": "These are only in-app notices. NetPulse does not send push notifications in this phase.",
+      "note": "These are only in-app notices. To get alerts when the app is closed, enable “Push notifications”.",
       "pulse": "Pulsing dot on devices with warnings",
       "pulse": "Pulsing dot on devices with warnings",
       "pulseCaption": "Animated dot on cards with warn",
       "pulseCaption": "Animated dot on cards with warn",
       "sound": "Sound when an alert arrives",
       "sound": "Sound when an alert arrives",
@@ -577,6 +577,25 @@
       "soundOn": "On — plays a soft beep",
       "soundOn": "On — plays a soft beep",
       "title": "Visual notifications"
       "title": "Visual notifications"
     },
     },
+    "push": {
+      "title": "Push notifications",
+      "caption": "Urgent alerts even when the app is closed",
+      "checking": "Checking support…",
+      "enable": "Enable",
+      "disable": "Disable",
+      "enabling": "Enabling…",
+      "disabling": "Disabling…",
+      "stateOn": "Enabled",
+      "stateOnCaption": "This device receives urgent alerts even when NetPulse is closed.",
+      "stateOffCaption": "Get urgent alerts on this device even when the app is not open.",
+      "denied": "Permission denied in the browser. To re-enable it: click the lock (or tune) icon in the address bar → Permissions → Notifications → Allow, then reload the page.",
+      "unsupported": "This browser does not support push notifications (it needs Service Worker, the Push API and the Notifications API).",
+      "insecure": "Push notifications require a secure context (HTTPS). On the local network they only work via localhost; over http://<lan-ip> the browser blocks them.",
+      "demoNote": "Not available in the local demo: push notifications need the NetPulse backend (without a server, a subscription would never receive anything).",
+      "errorServer": "Could not reach the push server. Please try again.",
+      "errorGeneric": "Push notifications could not be enabled on this device.",
+      "note": "Only alerts marked as urgent arrive (configured in Alerts). The notice is shown by the operating system with the NetPulse icon."
+    },
     "pwa": {
     "pwa": {
       "caption": "Installable app · PWA",
       "caption": "Installable app · PWA",
       "desc": "Install it as an app: fullscreen launch, no browser bar and instant access.",
       "desc": "Install it as an app: fullscreen launch, no browser bar and instant access.",

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

@@ -569,7 +569,7 @@
       "badge": "Badge de avisos en la navegación",
       "badge": "Badge de avisos en la navegación",
       "badgeCaption": "Contador junto a «Alertas»",
       "badgeCaption": "Contador junto a «Alertas»",
       "caption": "Avisos dentro de la app",
       "caption": "Avisos dentro de la app",
-      "note": "Son solo avisos dentro de la app. NetPulse no envía notificaciones push en esta fase.",
+      "note": "Son solo avisos dentro de la app. Para recibir alertas con la app cerrada, activa las «Notificaciones push».",
       "pulse": "Punto pulsante en equipos con aviso",
       "pulse": "Punto pulsante en equipos con aviso",
       "pulseCaption": "Dot animado en tarjetas con warn",
       "pulseCaption": "Dot animado en tarjetas con warn",
       "sound": "Sonido al llegar una alerta",
       "sound": "Sonido al llegar una alerta",
@@ -577,6 +577,25 @@
       "soundOn": "Activado — suena un beep suave",
       "soundOn": "Activado — suena un beep suave",
       "title": "Notificaciones visuales"
       "title": "Notificaciones visuales"
     },
     },
+    "push": {
+      "title": "Notificaciones push",
+      "caption": "Alertas urgentes incluso con la app cerrada",
+      "checking": "Comprobando soporte…",
+      "enable": "Activar",
+      "disable": "Desactivar",
+      "enabling": "Activando…",
+      "disabling": "Desactivando…",
+      "stateOn": "Activadas",
+      "stateOnCaption": "Este dispositivo recibe las alertas urgentes aunque NetPulse esté cerrado.",
+      "stateOffCaption": "Recibe las alertas urgentes en este dispositivo aunque no tengas la app abierta.",
+      "denied": "Permiso denegado en el navegador. Para reactivarlo: pulsa el candado (o el icono de ajustes) de la barra de direcciones → Permisos → Notificaciones → Permitir, y recarga la página.",
+      "unsupported": "Este navegador no admite notificaciones push (hacen falta Service Worker, Push API y la API de notificaciones).",
+      "insecure": "Las notificaciones push exigen un contexto seguro (HTTPS). En la red local solo funcionan accediendo por localhost; desde http://<ip-de-la-lan> el navegador las bloquea.",
+      "demoNote": "No disponible en la demo local: las notificaciones push necesitan el backend de NetPulse (sin servidor, una suscripción nunca recibiría nada).",
+      "errorServer": "No se pudo contactar con el servidor push. Inténtalo de nuevo.",
+      "errorGeneric": "No se pudieron activar las notificaciones push en este dispositivo.",
+      "note": "Solo llegan las alertas marcadas como urgentes (se configura en Alertas). El aviso lo muestra el sistema operativo con el icono de NetPulse."
+    },
     "pwa": {
     "pwa": {
       "caption": "App instalable · PWA",
       "caption": "App instalable · PWA",
       "desc": "Instálala como app: arranque a pantalla completa, sin barra del navegador y acceso instantáneo.",
       "desc": "Instálala como app: arranque a pantalla completa, sin barra del navegador y acceso instantáneo.",

+ 92 - 0
app/src/data/push.ts

@@ -0,0 +1,92 @@
+/**
+ * NetPulse — capa de datos Web Push (SPEC-PUSH §2).
+ *
+ * Contrato con el backend (server-go, tras auth de sesión):
+ * - GET  /api/push/vapid-key   → {"key":"<base64url>"}  (clave pública VAPID)
+ * - POST /api/push/subscribe   body {endpoint, keys:{auth,p256dh}} → 201/200
+ * - POST /api/push/unsubscribe body {endpoint} → 204
+ *
+ * En la demo local (sin backend) la tarjeta de Ajustes NO simula la
+ * activación: una suscripción push sin servidor nunca recibiría nada y
+ * daría una falsa sensación de funcionalidad. Se muestra el estado
+ * degradado "no disponible en la demo local".
+ */
+
+/** Suscripción tal y como la espera el backend (PushSubscription.toJSON()). */
+export interface PushSubscriptionPayload {
+  endpoint: string
+  keys: { auth: string; p256dh: string }
+}
+
+function redirectLogin(): never {
+  window.dispatchEvent(new Event('netpulse-unauthorized'))
+  window.location.assign('/login')
+  throw new Error('unauthorized')
+}
+
+/** GET /api/push/vapid-key → clave pública VAPID (base64url). null si no hay backend push. */
+export async function getVapidKey(): Promise<string | null> {
+  try {
+    const res = await fetch('/api/push/vapid-key')
+    if (res.status === 401) redirectLogin()
+    if (!res.ok) return null
+    const json = (await res.json()) as { key?: string }
+    return typeof json.key === 'string' && json.key.length > 0 ? json.key : null
+  } catch {
+    return null
+  }
+}
+
+/** POST /api/push/subscribe (upsert por endpoint). true si el servidor la aceptó. */
+export async function postPushSubscribe(sub: PushSubscriptionPayload): Promise<boolean> {
+  try {
+    const res = await fetch('/api/push/subscribe', {
+      method: 'POST',
+      headers: { 'Content-Type': 'application/json' },
+      body: JSON.stringify(sub),
+    })
+    if (res.status === 401) redirectLogin()
+    return res.ok // 200/201
+  } catch {
+    return false
+  }
+}
+
+/** POST /api/push/unsubscribe. El resultado no bloquea la baja local. */
+export async function postPushUnsubscribe(endpoint: string): Promise<boolean> {
+  try {
+    const res = await fetch('/api/push/unsubscribe', {
+      method: 'POST',
+      headers: { 'Content-Type': 'application/json' },
+      body: JSON.stringify({ endpoint }),
+    })
+    if (res.status === 401) redirectLogin()
+    return res.ok // 204
+  } catch {
+    return false
+  }
+}
+
+/** Clave VAPID pública (base64url) → applicationServerKey para pushManager.subscribe(). */
+export function urlBase64ToUint8Array(base64url: string): Uint8Array {
+  const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/')
+  const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4)
+  const raw = atob(padded)
+  const out = new Uint8Array(raw.length)
+  for (let i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i)
+  return out
+}
+
+/**
+ * Contexto de soporte Web Push (evaluar en cliente, no en SSR).
+ * - `insecure`: Web Push exige contexto seguro; en LAN por HTTP solo
+ *   funciona en localhost (o con HTTPS). Aviso propio en la tarjeta.
+ * - `unsupported`: sin ServiceWorker, PushManager o Notification.
+ */
+export function pushContext(): 'ok' | 'insecure' | 'unsupported' {
+  if (!window.isSecureContext) return 'insecure'
+  if (!('serviceWorker' in navigator) || !('PushManager' in window) || !('Notification' in window)) {
+    return 'unsupported'
+  }
+  return 'ok'
+}

+ 191 - 0
app/src/pages/Settings.tsx

@@ -4,6 +4,8 @@ import { Link } from 'react-router-dom'
 import { AnimatePresence, motion, useReducedMotion } from 'framer-motion'
 import { AnimatePresence, motion, useReducedMotion } from 'framer-motion'
 import {
 import {
   BadgeCheck,
   BadgeCheck,
+  BellOff,
+  BellRing,
   Check,
   Check,
   Copy,
   Copy,
   Download,
   Download,
@@ -30,6 +32,7 @@ import { Slider } from '@/components/ui/slider'
 import { Switch } from '@/components/ui/switch'
 import { Switch } from '@/components/ui/switch'
 import { useNetPulse } from '@/data/DataProvider'
 import { useNetPulse } from '@/data/DataProvider'
 import { useAuth } from '@/data/AuthContext'
 import { useAuth } from '@/data/AuthContext'
+import { getVapidKey, postPushSubscribe, postPushUnsubscribe, pushContext, urlBase64ToUint8Array } from '@/data/push'
 import { useServicesVisibility } from '@/hooks/useServicesVisibility'
 import { useServicesVisibility } from '@/hooks/useServicesVisibility'
 import type { ServicesVisibility } from '@/hooks/useServicesVisibility'
 import type { ServicesVisibility } from '@/hooks/useServicesVisibility'
 import { cn } from '@/lib/utils'
 import { cn } from '@/lib/utils'
@@ -1046,6 +1049,189 @@ function ServicesCard({ reduce, onSaved }: { reduce: boolean; onSaved: () => voi
   )
   )
 }
 }
 
 
+// ---------------------------------------------------------------------------
+// Tarjeta «Notificaciones push» (SPEC-PUSH §2)
+// ---------------------------------------------------------------------------
+
+type PushCardState =
+  | 'loading'
+  | 'insecure' // sin contexto seguro (HTTP en LAN que no sea localhost)
+  | 'unsupported' // sin SW / PushManager / Notification
+  | 'demo' // demo local: no se simula (una suscripción sin servidor nunca recibiría nada)
+  | 'denied' // permiso de notificaciones denegado en el navegador
+  | 'enabled' // suscripción push activa
+  | 'disabled' // todo listo, falta activar
+
+function PushNotificationsCard({ reduce, onSaved }: { reduce: boolean; onSaved: () => void }) {
+  const { t } = useTranslation()
+  const { isDemo } = useNetPulse()
+  const [state, setState] = useState<PushCardState>('loading')
+  const [busy, setBusy] = useState(false)
+  const [error, setError] = useState<string | null>(null)
+
+  // Detección del estado real: soporte → demo → permiso → suscripción viva
+  useEffect(() => {
+    let cancelled = false
+    void (async () => {
+      const ctx = pushContext()
+      if (ctx !== 'ok') {
+        setState(ctx)
+        return
+      }
+      if (isDemo) {
+        setState('demo')
+        return
+      }
+      if (Notification.permission === 'denied') {
+        setState('denied')
+        return
+      }
+      try {
+        const reg = await navigator.serviceWorker.getRegistration()
+        const sub = reg ? await reg.pushManager.getSubscription() : null
+        if (!cancelled) setState(sub ? 'enabled' : 'disabled')
+      } catch {
+        if (!cancelled) setState('disabled')
+      }
+    })()
+    return () => {
+      cancelled = true
+    }
+  }, [isDemo])
+
+  /** requestPermission → pushManager.subscribe(VAPID) → POST /api/push/subscribe */
+  const enable = useCallback(async () => {
+    if (busy) return
+    setBusy(true)
+    setError(null)
+    try {
+      const perm = await Notification.requestPermission()
+      if (perm !== 'granted') {
+        setState(perm === 'denied' ? 'denied' : 'disabled')
+        return
+      }
+      const vapid = await getVapidKey()
+      if (!vapid) {
+        setError(t('settings.push.errorServer'))
+        return
+      }
+      const reg = await navigator.serviceWorker.ready
+      const sub = await reg.pushManager.subscribe({
+        userVisibleOnly: true,
+        applicationServerKey: urlBase64ToUint8Array(vapid) as BufferSource,
+      })
+      const json = sub.toJSON()
+      const ok = await postPushSubscribe({
+        endpoint: sub.endpoint,
+        keys: { auth: json.keys?.auth ?? '', p256dh: json.keys?.p256dh ?? '' },
+      })
+      if (!ok) {
+        // El servidor no la guardó: baja local para no dejar estado fantasma
+        await sub.unsubscribe().catch(() => false)
+        setError(t('settings.push.errorServer'))
+        return
+      }
+      setState('enabled')
+      onSaved()
+    } catch {
+      setError(t('settings.push.errorGeneric'))
+    } finally {
+      setBusy(false)
+    }
+  }, [busy, t, onSaved])
+
+  /** Baja local + POST /api/push/unsubscribe (best-effort: el servidor purga 404/410) */
+  const disable = useCallback(async () => {
+    if (busy) return
+    setBusy(true)
+    setError(null)
+    try {
+      const reg = await navigator.serviceWorker.getRegistration()
+      const sub = reg ? await reg.pushManager.getSubscription() : null
+      if (sub) {
+        const endpoint = sub.endpoint
+        await sub.unsubscribe().catch(() => false)
+        await postPushUnsubscribe(endpoint)
+      }
+      setState('disabled')
+      onSaved()
+    } catch {
+      setError(t('settings.push.errorGeneric'))
+    } finally {
+      setBusy(false)
+    }
+  }, [busy, t, onSaved])
+
+  const btnBase =
+    'flex shrink-0 items-center gap-1.5 rounded-lg px-3.5 py-2 text-xs font-semibold transition-opacity hover:opacity-90 disabled:opacity-50'
+
+  return (
+    <Card title={t('settings.push.title')} caption={t('settings.push.caption')} index={4} reduce={reduce}>
+      {state === 'loading' && <p className="text-caption text-text-muted">{t('settings.push.checking')}</p>}
+
+      {state === 'enabled' && (
+        <div className="flex flex-wrap items-center justify-between gap-3">
+          <div className="flex min-w-0 items-center gap-2.5">
+            <span className="inline-flex shrink-0 items-center gap-1.5 rounded-full bg-ok/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-wider text-ok">
+              <BellRing className="h-3.5 w-3.5" strokeWidth={2} />
+              {t('settings.push.stateOn')}
+            </span>
+            <p className="text-caption leading-snug text-text-muted">{t('settings.push.stateOnCaption')}</p>
+          </div>
+          <button type="button" disabled={busy} onClick={() => void disable()} className={cn(btnBase, 'border border-border bg-elevated text-text-primary')}>
+            <BellOff className="h-3.5 w-3.5" strokeWidth={2} />
+            {busy ? t('settings.push.disabling') : t('settings.push.disable')}
+          </button>
+        </div>
+      )}
+
+      {state === 'disabled' && (
+        <div className="flex flex-wrap items-center justify-between gap-3">
+          <p className="min-w-0 flex-1 text-caption leading-snug text-text-secondary">{t('settings.push.stateOffCaption')}</p>
+          <button type="button" disabled={busy} onClick={() => void enable()} className={cn(btnBase, 'bg-accent text-canvas')}>
+            <BellRing className="h-3.5 w-3.5" strokeWidth={2} />
+            {busy ? t('settings.push.enabling') : t('settings.push.enable')}
+          </button>
+        </div>
+      )}
+
+      {state === 'denied' && (
+        <p className="rounded-xl bg-warn/10 px-3.5 py-2.5 text-caption leading-relaxed text-warn">
+          {t('settings.push.denied')}
+        </p>
+      )}
+
+      {state === 'unsupported' && (
+        <p className="rounded-xl bg-elevated px-3.5 py-2.5 text-caption leading-relaxed text-text-muted">
+          {t('settings.push.unsupported')}
+        </p>
+      )}
+
+      {state === 'insecure' && (
+        <p className="rounded-xl bg-warn/10 px-3.5 py-2.5 text-caption leading-relaxed text-warn">
+          {t('settings.push.insecure')}
+        </p>
+      )}
+
+      {state === 'demo' && (
+        <p className="rounded-xl bg-elevated px-3.5 py-2.5 text-caption leading-relaxed text-text-muted">
+          {t('settings.push.demoNote')}
+        </p>
+      )}
+
+      {error && (
+        <p role="alert" className="mt-3 rounded-lg bg-danger/10 px-3 py-2 text-caption text-danger">
+          {error}
+        </p>
+      )}
+
+      {(state === 'enabled' || state === 'disabled') && (
+        <p className="mt-3 text-caption leading-relaxed text-text-muted">{t('settings.push.note')}</p>
+      )}
+    </Card>
+  )
+}
+
 // ---------------------------------------------------------------------------
 // ---------------------------------------------------------------------------
 // Página Ajustes `/settings` (settings.md)
 // Página Ajustes `/settings` (settings.md)
 // ---------------------------------------------------------------------------
 // ---------------------------------------------------------------------------
@@ -1630,6 +1816,11 @@ export default function Settings() {
           </Card>
           </Card>
         </div>
         </div>
 
 
+        {/* Notificaciones push (Web Push nativo, SPEC-PUSH §2) */}
+        <div className="lg:col-span-7">
+          <PushNotificationsCard reduce={reduce} onSaved={notify} />
+        </div>
+
         {/* Gestión de routers — solo con backend (modo live) */}
         {/* Gestión de routers — solo con backend (modo live) */}
         {!isDemo && (
         {!isDemo && (
           <div className="lg:col-span-12">
           <div className="lg:col-span-12">