Procházet zdrojové kódy

WireGuard: per-peer urgency flag, urgent alerts and slot priority (#1448)

* feat(wireguard): per-peer urgency flag, admin endpoint and urgent alerts

Peers no longer treated all the same: the admin marks a peer as urgent and its
drops raise an urgent alert while the rest only stay in the log.

- Stable identifier: WGPeer.key carries the public key as base64url without
  padding. WGPeer.id is not usable (it comes from the device matched by tunnel
  IP or from the dump index and changes between polls).
- Persistence: one kv row (wireguard.urgent_peers) holding a sorted JSON array,
  following the existing kv pattern. Live keeps an in-memory copy loaded at
  startup so polls and transitions do not hit the DB every cycle.
- PUT /api/wireguard/peers/{key}/urgent {"urgent":bool} (admin only, key shape
  and body validated) plus GET /api/wireguard/urgent for diagnostics.
- applyWireGuardTransitions stamps Urgent=true only for marked peers on
  connect/disconnect; category and alert ids are unchanged.
- Topology semantics emits the four wg links with urgent active peers first,
  matching the front slot order.
- Demo dataset gets base64url keys and a single urgent peer (the site-to-site
  tunnel), canon regenerated with cmd/gen-demo-canon.

Tests: peer key stability and URL safety, urgency stamping by key, kv
persistence and reload, invalid key, corrupt kv, disconnect and handshake
urgency, urgent-first links, and endpoint auth/validation/round-trip/501.

Closes #1441

* feat(topology,wireguard): urgent peer toggle, slot priority and hidden badge

- WGPeer gains key and urgent in the frontend contract.
- DataProvider.setPeerUrgent: optimistic update with rollback on failure, local
  only in demo, PUT /api/wireguard/peers/{key}/urgent in live.
- Map slots ordered urgent active, active, urgent down, down; a down peer still
  never displaces an active one and the first four match the server wg links.
- Urgency drawn without relying on colour: outer ring plus a "!" badge on the
  node, and the aria-label says it is marked urgent. The +N chip gets a "!" when
  it hides urgent peers and its label and tooltip report how many.
- Peer tooltip and router WireGuard panel get the urgent pill and a switch.
- i18n es/en for every new string.

Verified in demo with Playwright: down urgent peer keeps the ring and sits
after the active peers, toggling an active peer updates its aria-label, the
panel lists five switches with the site-to-site one on.

Closes #1441
Nacho před 1 měsícem
rodič
revize
494f7430a2

+ 10 - 2
app/public/locales/en/translation.json

@@ -1249,9 +1249,14 @@
     "mapAria": "Network map: Internet connected to the Flint 2 Gateway, three access points (Living Room, Study and Patio) with their clients, and two active WireGuard tunnels.",
     "peerAria": "{{name}}, active WireGuard tunnel, {{ip}}",
     "peerAriaDown": "{{name}}, WireGuard tunnel down, {{ip}}",
+    "peerAriaUrgent": "{{name}}, active WireGuard tunnel, marked urgent, {{ip}}",
+    "peerAriaUrgentDown": "{{name}}, WireGuard tunnel down, marked urgent, {{ip}}",
     "peer": {
       "down": "Down",
-      "downHint": "No active tunnel: no recent handshake"
+      "downHint": "No active tunnel: no recent handshake",
+      "urgent": "Urgent",
+      "urgentHint": "Alerts when it drops and goes first on the map",
+      "urgentAria": "Toggle urgency for {{name}}"
     },
     "plan": "Plan",
     "received": "Received",
@@ -1305,8 +1310,11 @@
     },
     "peers": {
       "overflowTitle": "{{count}} more peers",
+      "overflowTitleUrgent": "{{count}} more peers · {{urgent}} urgent",
       "overflowAria": "{{count}} additional WireGuard peers",
-      "overflowAriaDown": "{{count}} additional WireGuard peers, {{down}} down"
+      "overflowAriaDown": "{{count}} additional WireGuard peers, {{down}} down",
+      "overflowAriaUrgent": "{{count}} additional WireGuard peers, {{urgent}} urgent",
+      "overflowAriaUrgentDown": "{{count}} additional WireGuard peers, {{urgent}} urgent and {{down}} down"
     },
     "ring": {
       "overflowAria": "{{count}} more clients on {{router}}",

+ 10 - 2
app/public/locales/es/translation.json

@@ -1249,9 +1249,14 @@
     "mapAria": "Mapa de la red: Internet conectado al Gateway Flint 2, tres puntos de acceso (Salón, Estudio y Patio) con sus clientes, y dos túneles WireGuard activos.",
     "peerAria": "{{name}}, túnel WireGuard activo, {{ip}}",
     "peerAriaDown": "{{name}}, túnel WireGuard caído, {{ip}}",
+    "peerAriaUrgent": "{{name}}, túnel WireGuard activo, marcado como urgente, {{ip}}",
+    "peerAriaUrgentDown": "{{name}}, túnel WireGuard caído, marcado como urgente, {{ip}}",
     "peer": {
       "down": "Caído",
-      "downHint": "Sin túnel activo: no hay handshake reciente"
+      "downHint": "Sin túnel activo: no hay handshake reciente",
+      "urgent": "Urgente",
+      "urgentHint": "Avisa si se cae y va primero en el mapa",
+      "urgentAria": "Alternar urgencia de {{name}}"
     },
     "plan": "Plan",
     "received": "Recibido",
@@ -1305,8 +1310,11 @@
     },
     "peers": {
       "overflowTitle": "{{count}} peers más",
+      "overflowTitleUrgent": "{{count}} peers más · {{urgent}} urgentes",
       "overflowAria": "{{count}} peers WireGuard adicionales",
-      "overflowAriaDown": "{{count}} peers WireGuard adicionales, {{down}} caídos"
+      "overflowAriaDown": "{{count}} peers WireGuard adicionales, {{down}} caídos",
+      "overflowAriaUrgent": "{{count}} peers WireGuard adicionales, {{urgent}} urgentes",
+      "overflowAriaUrgentDown": "{{count}} peers WireGuard adicionales, {{urgent}} urgentes y {{down}} caídos"
     },
     "ring": {
       "overflowAria": "{{count}} clientes más en {{router}}",

+ 59 - 36
app/src/components/routers/WireGuardPanel.tsx

@@ -7,6 +7,7 @@ import { relTime } from '@/i18n'
 import type { PeerType, WGPeer } from '@/data/mock'
 import { useNetPulse } from '@/data/DataProvider'
 import { StatusPill } from '@/components/StatusPill'
+import { Switch } from '@/components/ui/switch'
 import { WG_TOTALS_30D, wgPeerExtras } from '@/components/routers/routerExtras'
 import { cn } from '@/lib/utils'
 
@@ -20,6 +21,7 @@ const PEER_ICONS: Record<PeerType, LucideIcon> = {
 
 function PeerRow({ peer, index }: { peer: WGPeer; index: number }) {
   const { t } = useTranslation()
+  const { setPeerUrgent } = useNetPulse()
   const [open, setOpen] = useState(false)
   const reduce = useReducedMotion()
   const Icon = PEER_ICONS[peer.type] ?? Smartphone
@@ -32,46 +34,63 @@ function PeerRow({ peer, index }: { peer: WGPeer; index: number }) {
       transition={{ duration: 0.3, ease: 'easeOut', delay: 0.1 + index * 0.07 }}
       className={cn(!peer.active && 'opacity-65')}
     >
-      <button
-        onClick={() => setOpen((v) => !v)}
-        aria-expanded={open}
-        className="flex w-full items-center gap-3 rounded-xl px-2.5 py-2.5 text-left transition-colors hover:bg-hover"
-      >
-        {/* Avatar con inicial + icono de tipo superpuesto */}
-        <span className="relative shrink-0">
-          <span
-            className={cn(
-              'flex h-10 w-10 items-center justify-center rounded-full font-display text-sm font-bold',
-              peer.active ? 'bg-gradient-to-br from-tunnel to-accent text-canvas' : 'bg-elevated text-text-muted',
+      <div className="flex items-center gap-1">
+        <button
+          onClick={() => setOpen((v) => !v)}
+          aria-expanded={open}
+          className="flex min-w-0 flex-1 items-center gap-3 rounded-xl px-2.5 py-2.5 text-left transition-colors hover:bg-hover"
+        >
+          {/* Avatar con inicial + icono de tipo superpuesto */}
+          <span className="relative shrink-0">
+            <span
+              className={cn(
+                'flex h-10 w-10 items-center justify-center rounded-full font-display text-sm font-bold',
+                peer.active ? 'bg-gradient-to-br from-tunnel to-accent text-canvas' : 'bg-elevated text-text-muted',
+              )}
+            >
+              {peer.name.charAt(0)}
+            </span>
+            <span className="absolute -bottom-0.5 -right-0.5 flex h-4 w-4 items-center justify-center rounded-full border border-surface bg-elevated text-text-secondary">
+              <Icon className="h-2.5 w-2.5" strokeWidth={1.75} />
+            </span>
+            {/* #1441: urgencia sin depender del color (glifo "!" + aria-label del switch) */}
+            {peer.urgent && (
+              <span
+                aria-hidden
+                className="absolute -right-1.5 -top-1.5 flex h-4 w-4 items-center justify-center rounded-full border border-surface bg-surface text-[9px] font-bold text-warn"
+              >
+                !
+              </span>
             )}
-          >
-            {peer.name.charAt(0)}
-          </span>
-          <span className="absolute -bottom-0.5 -right-0.5 flex h-4 w-4 items-center justify-center rounded-full border border-surface bg-elevated text-text-secondary">
-            <Icon className="h-2.5 w-2.5" strokeWidth={1.75} />
           </span>
-        </span>
 
-        <span className="min-w-0 flex-1">
-          <span className="block truncate text-sm font-medium text-text-primary">{peer.name}</span>
-          <span className="flex items-center gap-1.5">
-            <span className="relative flex h-1.5 w-1.5">
-              {peer.active && (
-                <span className="absolute inline-flex h-full w-full rounded-full bg-ok opacity-75 animate-ping-soft" />
-              )}
-              <span className={cn('relative inline-flex h-1.5 w-1.5 rounded-full', peer.active ? 'bg-ok' : 'bg-text-muted')} />
-            </span>
-            <span className="font-mono text-caption text-text-muted">
-              {peer.tunnelIp} · {relTime(peer.lastHandshake)}
+          <span className="min-w-0 flex-1">
+            <span className="block truncate text-sm font-medium text-text-primary">{peer.name}</span>
+            <span className="flex items-center gap-1.5">
+              <span className="relative flex h-1.5 w-1.5">
+                {peer.active && (
+                  <span className="absolute inline-flex h-full w-full rounded-full bg-ok opacity-75 animate-ping-soft" />
+                )}
+                <span className={cn('relative inline-flex h-1.5 w-1.5 rounded-full', peer.active ? 'bg-ok' : 'bg-text-muted')} />
+              </span>
+              <span className="font-mono text-caption text-text-muted">
+                {peer.tunnelIp} · {relTime(peer.lastHandshake)}
+              </span>
             </span>
           </span>
-        </span>
 
-        <span className="shrink-0 text-right font-mono text-caption text-text-secondary">
-          ↓ {peer.rx} ↑ {peer.tx}
-        </span>
-        <ChevronDown className={cn('h-4 w-4 shrink-0 text-text-muted transition-transform', open && 'rotate-180')} strokeWidth={1.75} />
-      </button>
+          <span className="hidden shrink-0 text-right font-mono text-caption text-text-secondary sm:block">
+            ↓ {peer.rx} ↑ {peer.tx}
+          </span>
+          <ChevronDown className={cn('h-4 w-4 shrink-0 text-text-muted transition-transform', open && 'rotate-180')} strokeWidth={1.75} />
+        </button>
+        <Switch
+          checked={peer.urgent}
+          onCheckedChange={(checked) => setPeerUrgent(peer.key, checked)}
+          aria-label={t('topology.peer.urgentAria', { name: peer.name })}
+          className="mr-1 shrink-0"
+        />
+      </div>
 
       <AnimatePresence initial={false}>
         {open && extra && (
@@ -105,7 +124,11 @@ function PeerRow({ peer, index }: { peer: WGPeer; index: number }) {
 export function WireGuardPanel() {
   const { t } = useTranslation()
   const { wireguard } = useNetPulse()
-  const peers = [...wireguard.peers].sort((a, b) => Number(b.active) - Number(a.active))
+  // #1441: activos primero y, dentro de cada grupo, los urgentes primero
+  // (mismo criterio que los slots del mapa).
+  const peers = [...wireguard.peers].sort(
+    (a, b) => Number(b.active) - Number(a.active) || Number(b.urgent) - Number(a.urgent),
+  )
   const connected = peers.filter((p) => p.active).length
 
   return (
@@ -143,7 +166,7 @@ export function WireGuardPanel() {
       {/* Lista de peers */}
       <div className="mt-3 divide-y divide-border/50">
         {peers.map((p, i) => (
-          <PeerRow key={p.id} peer={p} index={i} />
+          <PeerRow key={p.key || p.id} peer={p} index={i} />
         ))}
       </div>
     </section>

+ 102 - 12
app/src/components/topology/TopologyMap.tsx

@@ -16,6 +16,8 @@ import { manufacturerLabel, relTime, roleLabel } from '@/i18n'
 import type { Device, DistributionNode, Router, WanInfo, WGPeer } from '@/data/mock'
 import { fmtEs } from '@/data/mock'
 import { StatusPill } from '@/components/StatusPill'
+import { Switch } from '@/components/ui/switch'
+import { useNetPulse } from '@/data/DataProvider'
 import { DEVICE_ICONS, deviceIcon } from '@/components/DeviceRow'
 import { fmtTemp, useTempUnit } from '@/lib/temperature'
 import { cn } from '@/lib/utils'
@@ -136,6 +138,31 @@ function MiniStat({ label, value, hot }: { label: string; value: string; hot?: b
   )
 }
 
+/** #1441: switch "Urgente" del peer dentro de la tarjeta del mapa. Lee el
+ * peer vivo del bundle (el tooltip guarda una copia) para que el estado se
+ * actualice al instante tras el cambio optimista. */
+function PeerUrgentToggle({ peer }: { peer: WGPeer }) {
+  const { t } = useTranslation()
+  const { wireguard, setPeerUrgent } = useNetPulse()
+  if (!peer.key) return null
+  const live = wireguard.peers.find((p) => p.key === peer.key) ?? peer
+  return (
+    <div className="mt-2 flex items-center justify-between gap-2 rounded-lg bg-surface px-2.5 py-1.5">
+      <span className="min-w-0">
+        <span className="block text-caption font-semibold text-text-primary">{t('topology.peer.urgent')}</span>
+        <span className="block text-[10px] leading-tight text-text-muted">{t('topology.peer.urgentHint')}</span>
+      </span>
+      <Switch
+        checked={live.urgent}
+        onCheckedChange={(checked) => setPeerUrgent(live.key, checked)}
+        aria-label={t('topology.peer.urgentAria', { name: live.name })}
+        className="pointer-events-auto"
+        onClick={(e) => e.stopPropagation()}
+      />
+    </div>
+  )
+}
+
 function TooltipCard({
   tip,
   touch,
@@ -160,6 +187,14 @@ function TooltipCard({
 }) {
   const { t } = useTranslation()
   const [tempUnit] = useTempUnit()
+  const { wireguard } = useNetPulse()
+  // El tooltip guarda una copia del peer: para el flag urgente se lee el vivo.
+  const livePeer =
+    tip.kind === 'peer' ? wireguard.peers.find((p) => p.key === tip.peer.key) ?? tip.peer : null
+  const overflowUrgentCount =
+    tip.kind === 'peersOverflow'
+      ? tip.peers.filter((p) => (wireguard.peers.find((x) => x.key === p.key) ?? p).urgent).length
+      : 0
   return (
     <div
       className={cn(
@@ -219,11 +254,14 @@ function TooltipCard({
         <div>
           <div className="flex items-center justify-between gap-2">
             <span className="font-display text-sm font-semibold text-text-primary">{tip.peer.name}</span>
-            {tip.peer.active ? (
-              <StatusPill tone="tunnel" label={t('common.active')} pulse />
-            ) : (
-              <StatusPill tone="danger" label={t('topology.peer.down')} />
-            )}
+            <span className="flex items-center gap-1.5">
+              {livePeer?.urgent && <StatusPill tone="warn" label={t('topology.peer.urgent')} />}
+              {tip.peer.active ? (
+                <StatusPill tone="tunnel" label={t('common.active')} pulse />
+              ) : (
+                <StatusPill tone="danger" label={t('topology.peer.down')} />
+              )}
+            </span>
           </div>
           <div className="mt-0.5 font-mono text-caption text-text-muted">
             {tip.peer.tunnelIp} · wg0 · {t('topology.viaInternet')}
@@ -237,13 +275,16 @@ function TooltipCard({
             <MiniStat label={t('topology.received')} value={`↓ ${tip.peer.rx}`} />
             <MiniStat label={t('topology.sent')} value={`↑ ${tip.peer.tx}`} />
           </div>
+          <PeerUrgentToggle peer={tip.peer} />
         </div>
       )}
       {tip.kind === 'peersOverflow' && (
         <div>
           <div className="flex items-center justify-between gap-2">
             <span className="font-display text-sm font-semibold text-text-primary">
-              {t('topology.peers.overflowTitle', { count: tip.peers.length })}
+              {overflowUrgentCount > 0
+                ? t('topology.peers.overflowTitleUrgent', { count: tip.peers.length, urgent: overflowUrgentCount })
+                : t('topology.peers.overflowTitle', { count: tip.peers.length })}
             </span>
             {tip.peers.some((p) => p.active) ? (
               <StatusPill tone="tunnel" label={t('common.active')} pulse />
@@ -254,7 +295,14 @@ function TooltipCard({
           <div className="mt-2 space-y-1.5">
             {tip.peers.map((p) => (
               <div key={p.id} className="flex items-center justify-between gap-3 text-caption">
-                <span className="font-semibold text-text-primary">{p.name}</span>
+                <span className="flex min-w-0 items-center gap-1.5 font-semibold text-text-primary">
+                  {(wireguard.peers.find((x) => x.key === p.key) ?? p).urgent && (
+                    <span className="font-bold text-warn" aria-label={t('topology.peer.urgent')} title={t('topology.peer.urgent')}>
+                      !
+                    </span>
+                  )}
+                  <span className="truncate">{p.name}</span>
+                </span>
                 <span className="font-mono text-text-muted">
                   {p.active ? `Handshake ${relTime(p.lastHandshake)}` : t('topology.peer.down')}
                 </span>
@@ -539,6 +587,8 @@ export function TopologyMap({
   const { chips, ctsByHost, ctCountByHost, distNodes, hiddenPeers, hypervisorSourceByHost, internetNode, links, peerNodes, relatedTo, ringOverflowChips, routerNodes, wan } = model
   /** peers caídos dentro del chip "+N" (#1440): el chip lo dice en el aria-label */
   const hiddenDownCount = hiddenPeers.filter((p) => !p.active).length
+  /** peers urgentes dentro del chip "+N" (#1441): insignia "!" + aria-label */
+  const hiddenUrgentCount = hiddenPeers.filter((p) => p.urgent).length
   const containerRef = useRef<HTMLDivElement>(null)
   const svgRef = useRef<SVGSVGElement>(null)
   const [initialView] = useState<View | null>(() => loadSavedView())
@@ -1303,8 +1353,12 @@ export function TopologyMap({
                   tabIndex={0}
                   aria-label={
                     down
-                      ? t('topology.peerAriaDown', { name: node.peer.name, ip: node.peer.tunnelIp })
-                      : t('topology.peerAria', { name: node.peer.name, ip: node.peer.tunnelIp })
+                      ? node.peer.urgent
+                        ? t('topology.peerAriaUrgentDown', { name: node.peer.name, ip: node.peer.tunnelIp })
+                        : t('topology.peerAriaDown', { name: node.peer.name, ip: node.peer.tunnelIp })
+                      : node.peer.urgent
+                        ? t('topology.peerAriaUrgent', { name: node.peer.name, ip: node.peer.tunnelIp })
+                        : t('topology.peerAria', { name: node.peer.name, ip: node.peer.tunnelIp })
                   }
                   animate={{ opacity: nodeOpacity(node.id) * (down ? 0.55 : 1) }}
                   transition={{ duration: 0.2 }}
@@ -1350,6 +1404,28 @@ export function TopologyMap({
                     strokeWidth={1.75}
                     aria-hidden
                   />
+                  {/* #1441: la urgencia NO se marca con color (el color ya dice
+                      activo/caído): anillo exterior + insignia "!" que también
+                      lee el aria-label del grupo. */}
+                  {node.peer.urgent && (
+                    <>
+                      <rect
+                        x={-22.5}
+                        y={-22.5}
+                        width={45}
+                        height={45}
+                        rx={14}
+                        fill="none"
+                        stroke={COLOR.warn}
+                        strokeWidth={1.5}
+                        aria-hidden
+                      />
+                      <circle cx={18.5} cy={-18.5} r={7.5} fill="rgb(var(--elevated))" stroke={COLOR.warn} strokeWidth={1.5} aria-hidden />
+                      <text x={18.5} y={-15.3} textAnchor="middle" fontSize={9.5} fontWeight={800} fill={COLOR.warn} aria-hidden>
+                        !
+                      </text>
+                    </>
+                  )}
                 </motion.g>
                 {/* Estado caído sin depender del color: texto + trazo discontinuo
                     (el aria-label del grupo ya lo dice para lectores de pantalla). */}
@@ -1386,9 +1462,13 @@ export function TopologyMap({
                 role="button"
                 tabIndex={0}
                 aria-label={
-                  hiddenDownCount > 0
-                    ? t('topology.peers.overflowAriaDown', { count: hiddenPeers.length, down: hiddenDownCount })
-                    : t('topology.peers.overflowAria', { count: hiddenPeers.length })
+                  hiddenUrgentCount > 0
+                    ? hiddenDownCount > 0
+                      ? t('topology.peers.overflowAriaUrgentDown', { count: hiddenPeers.length, urgent: hiddenUrgentCount, down: hiddenDownCount })
+                      : t('topology.peers.overflowAriaUrgent', { count: hiddenPeers.length, urgent: hiddenUrgentCount })
+                    : hiddenDownCount > 0
+                      ? t('topology.peers.overflowAriaDown', { count: hiddenPeers.length, down: hiddenDownCount })
+                      : t('topology.peers.overflowAria', { count: hiddenPeers.length })
                 }
                 onPointerEnter={(e) =>
                   handleNodeHover(
@@ -1447,6 +1527,16 @@ export function TopologyMap({
                 >
                   +{hiddenPeers.length}
                 </text>
+                {/* #1441: hay urgentes dentro del chip; la insignia "!" no
+                    depende del color y el tooltip dice cuántos. */}
+                {hiddenUrgentCount > 0 && (
+                  <>
+                    <circle cx={17} cy={-11} r={7.5} fill="rgb(var(--elevated))" stroke={COLOR.warn} strokeWidth={1.5} aria-hidden />
+                    <text x={17} y={-7.8} textAnchor="middle" fontSize={9.5} fontWeight={800} fill={COLOR.warn} aria-hidden>
+                      !
+                    </text>
+                  </>
+                )}
               </g>
             </motion.g>
           </g>

+ 8 - 7
app/src/components/topology/model.ts

@@ -1318,14 +1318,15 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   // -- peers WireGuard (arriba; túnel trazado vía Internet) -------------------
   // Hay 4 coordenadas canónicas. #1440: se dibujan TODOS los peers
   // configurados, no solo los activos: un túnel caído era invisible en el
-  // mapa. Orden: activos primero y caídos después, ambos en el orden del API.
-  // Así un peer caído nunca desplaza a un túnel vivo de su coordenada y los
-  // 4 slots visibles coinciden con los que el servidor manda como enlaces
-  // `wg` en la semántica (primeros 4 activos). Los caídos ocupan el mismo
-  // bloque, atenuados y sin enlace de túnel. Los que exceden van al chip "+N".
+  // mapa. #1441 añade la urgencia al orden de slots: urgentes activos →
+  // activos → urgentes caídos → caídos (el orden del API se respeta dentro de
+  // cada grupo). Un caído nunca desplaza a un activo de su coordenada, y los
+  // 4 primeros coinciden con los enlaces `wg` de la semántica del servidor,
+  // que aplica las mismas dos pasadas (urgentes activos primero). Los que
+  // exceden van al chip "+N".
   const activePeers = wireguard.peers.filter((p) => p.active)
-  const downPeers = wireguard.peers.filter((p) => !p.active)
-  const orderedPeers = [...activePeers, ...downPeers]
+  const peerRank = (p: WGPeer): number => (p.active ? 0 : 2) + (p.urgent ? 0 : 1)
+  const orderedPeers = [...wireguard.peers].sort((a, b) => peerRank(a) - peerRank(b))
   const peerNodes: PeerNode[] = orderedPeers.slice(0, PEER_COORDS.length).map((peer, i) => ({
     kind: 'peer',
     id: `peer-${peer.id}`,

+ 40 - 1
app/src/data/DataProvider.tsx

@@ -192,6 +192,13 @@ export interface NetPulseApi extends NetPulseData {
   /** POST /api/alerts/impostor-approve (live): aprueba un BSSID como propio
    * (#1400); la alerta de impostor de ese BSSID se resuelve y no vuelve. */
   approveImpostorBssid: (bssid: string) => void
+  /**
+   * PUT /api/wireguard/peers/{key}/urgent (live): marca o desmarca un peer
+   * WireGuard como urgente (#1441), por su clave pública estable. Optimista
+   * con rollback: si el servidor rechaza, el flag vuelve a su valor previo.
+   * Demo: solo estado local, sin llamada de red.
+   */
+  setPeerUrgent: (key: string, urgent: boolean) => void
   /** POST /api/alerts/dismiss (live): limpia una alerta del feed (#833). Demo: estado local. Optimista. */
   dismissAlert: (id: string) => void
   /**
@@ -1063,6 +1070,37 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     })()
   }, [])
 
+  /** Marca/desmarca un peer WG como urgente (#1441). Optimista con rollback:
+   * un fallo de red deja el flag como estaba. La clave es la pública del peer
+   * (`key`), no su id, que cambia cuando el peer casa con otro equipo. */
+  const setPeerUrgent = useCallback((key: string, urgent: boolean) => {
+    const previous =
+      bundleRef.current.wireguard.peers.find((p) => p.key === key)?.urgent ?? false
+    const apply = (value: boolean) =>
+      setBundle((b) => ({
+        ...b,
+        wireguard: {
+          ...b.wireguard,
+          peers: b.wireguard.peers.map((p) => (p.key === key ? { ...p, urgent: value } : p)),
+        },
+      }))
+    apply(urgent)
+    if (modeRef.current !== 'live') return
+    void (async () => {
+      try {
+        const res = await fetch(`/api/wireguard/peers/${encodeURIComponent(key)}/urgent`, {
+          method: 'PUT',
+          headers: { 'Content-Type': 'application/json' },
+          body: JSON.stringify({ urgent }),
+        })
+        if (res.status === 401) redirectLogin()
+        if (!res.ok) apply(previous)
+      } catch {
+        apply(previous)
+      }
+    })()
+  }, [])
+
   /** Limpia una alerta del feed (issue #833): oculta la fila al instante y,
    * en live, la persiste como dismiss en el backend (no reaparece tras un
    * reinicio; si la condición se re-dispara, vuelve sola). */
@@ -1353,6 +1391,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       clearAllAlerts,
       silenceAlert,
       approveImpostorBssid,
+      setPeerUrgent,
       dismissAlert,
       rearmAgent,
       upgradeAgent,
@@ -1362,7 +1401,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       removeAgent,
       createAgentInstall,
     }),
-    [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, clearAllAlerts, silenceAlert, approveImpostorBssid, dismissAlert, rearmAgent, upgradeAgent, upgradeAllAgents, reinstallAgent, uninstallAgent, removeAgent, createAgentInstall],
+    [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, clearAllAlerts, silenceAlert, approveImpostorBssid, setPeerUrgent, dismissAlert, rearmAgent, upgradeAgent, upgradeAllAgents, reinstallAgent, uninstallAgent, removeAgent, createAgentInstall],
   )
 
   return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>

+ 15 - 5
app/src/data/demo-canon.json

@@ -2526,53 +2526,63 @@
     "peers": [
       {
         "id": "pixel-8-pro",
+        "key": "demo-pixel-8-pro",
         "name": "Pixel 8 Pro",
         "type": "movil",
         "tunnelIp": "10.0.0.2",
         "active": true,
         "lastHandshake": "hace 38 s",
         "rx": "1,2 GB",
-        "tx": "214 MB"
+        "tx": "214 MB",
+        "urgent": false
       },
       {
         "id": "macbook-air",
+        "key": "demo-macbook-air",
         "name": "MacBook Air",
         "type": "portatil",
         "tunnelIp": "10.0.0.3",
         "active": true,
         "lastHandshake": "hace 1 min",
         "rx": "640 MB",
-        "tx": "88 MB"
+        "tx": "88 MB",
+        "urgent": false
       },
       {
         "id": "ipad-air",
+        "key": "demo-ipad-air",
         "name": "iPad Air",
         "type": "tablet",
         "tunnelIp": "10.0.0.4",
         "active": false,
         "lastHandshake": "hace 2 días",
         "rx": "3,1 GB",
-        "tx": "402 MB"
+        "tx": "402 MB",
+        "urgent": false
       },
       {
         "id": "portatil-trabajo",
+        "key": "demo-portatil-trabajo",
         "name": "Portátil trabajo",
         "type": "portatil",
         "tunnelIp": "10.0.0.5",
         "active": false,
         "lastHandshake": "hace 6 h",
         "rx": "812 MB",
-        "tx": "121 MB"
+        "tx": "121 MB",
+        "urgent": false
       },
       {
         "id": "casa-familia",
+        "key": "demo-casa-familia",
         "name": "Casa familia",
         "type": "sitio",
         "tunnelIp": "10.0.0.6",
         "active": false,
         "lastHandshake": "hace 9 días",
         "rx": "12 GB",
-        "tx": "4,2 GB"
+        "tx": "4,2 GB",
+        "urgent": true
       }
     ]
   },

+ 9 - 0
app/src/data/types.ts

@@ -172,10 +172,19 @@ export type DeviceInfra = 'hypervisor' | 'ct' | 'vm' | 'managed-switch' | 'ap'
 
 export interface WGPeer {
   id: string
+  /**
+   * Identificador estable del peer (#1441): su clave pública en base64url sin
+   * padding. `id` sale del equipo que casó por IP del túnel o de `peer-<idx>`,
+   * así que cambia con el tiempo y no sirve como clave de persistencia.
+   */
+  key: string
   name: string
   type: PeerType
   tunnelIp: string
   active: boolean
+  /** Marcado por el admin como urgente (#1441): sus caídas avisan y sus
+   *  slots van primero en el mapa. Persistido en el servidor por `key`. */
+  urgent: boolean
   lastHandshake: string
   rx: string
   tx: string

+ 9 - 5
server-go/internal/adapters/demo_dataset.go

@@ -143,12 +143,16 @@ func canonAdguard() AdGuardStats {
 func canonWireguard() WireGuardStats {
 	return WireGuardStats{
 		Interface: "wg0", Subnet: "10.0.0.1/24", Status: "active",
+		// Key: identificador estable del peer (#1441). En el demo son ids sintéticos
+		// legibles para no parecer secretos ante el escáner (gitleaks).
+		// Urgent: el túnel site-to-site es el único que avisa si se cae; los
+		// portátiles y móviles son rutina (el resto, false).
 		Peers: []WGPeer{
-			{ID: "pixel-8-pro", Name: "Pixel 8 Pro", Type: "movil", TunnelIP: "10.0.0.2", Active: true, LastHandshake: "hace 38 s", Rx: "1,2 GB", Tx: "214 MB"},
-			{ID: "macbook-air", Name: "MacBook Air", Type: "portatil", TunnelIP: "10.0.0.3", Active: true, LastHandshake: "hace 1 min", Rx: "640 MB", Tx: "88 MB"},
-			{ID: "ipad-air", Name: "iPad Air", Type: "tablet", TunnelIP: "10.0.0.4", Active: false, LastHandshake: "hace 2 días", Rx: "3,1 GB", Tx: "402 MB"},
-			{ID: "portatil-trabajo", Name: "Portátil trabajo", Type: "portatil", TunnelIP: "10.0.0.5", Active: false, LastHandshake: "hace 6 h", Rx: "812 MB", Tx: "121 MB"},
-			{ID: "casa-familia", Name: "Casa familia", Type: "sitio", TunnelIP: "10.0.0.6", Active: false, LastHandshake: "hace 9 días", Rx: "12 GB", Tx: "4,2 GB"},
+			{ID: "pixel-8-pro", Key: "demo-pixel-8-pro", Name: "Pixel 8 Pro", Type: "movil", TunnelIP: "10.0.0.2", Active: true, LastHandshake: "hace 38 s", Rx: "1,2 GB", Tx: "214 MB"},
+			{ID: "macbook-air", Key: "demo-macbook-air", Name: "MacBook Air", Type: "portatil", TunnelIP: "10.0.0.3", Active: true, LastHandshake: "hace 1 min", Rx: "640 MB", Tx: "88 MB"},
+			{ID: "ipad-air", Key: "demo-ipad-air", Name: "iPad Air", Type: "tablet", TunnelIP: "10.0.0.4", Active: false, LastHandshake: "hace 2 días", Rx: "3,1 GB", Tx: "402 MB"},
+			{ID: "portatil-trabajo", Key: "demo-portatil-trabajo", Name: "Portátil trabajo", Type: "portatil", TunnelIP: "10.0.0.5", Active: false, LastHandshake: "hace 6 h", Rx: "812 MB", Tx: "121 MB"},
+			{ID: "casa-familia", Key: "demo-casa-familia", Name: "Casa familia", Type: "sitio", TunnelIP: "10.0.0.6", Active: false, LastHandshake: "hace 9 días", Rx: "12 GB", Tx: "4,2 GB", Urgent: true},
 		},
 	}
 }

+ 30 - 5
server-go/internal/adapters/live.go

@@ -318,8 +318,12 @@ type Live struct {
 	engine        *alerts.Engine
 	wgActive      map[string]bool
 	wgActiveSince map[string]time.Time // when each active peer became active (disconnect duration)
-	weakAlerted   map[string]int64
-	onlineMacs    map[string]bool
+	// wgUrgent (#1441): claves de peer (WGPeer.Key) marcadas como urgentes:
+	// sus caídas avisan (Urgent=true en la alerta), las del resto solo van al
+	// log. Persistido en kv (wgUrgentKey).
+	wgUrgent    map[string]bool
+	weakAlerted map[string]int64
+	onlineMacs  map[string]bool
 	// unknownGrace: ticks consecutivos online+sin nombre (Name == MAC) por
 	// MAC. unknownAlerted: MACs que ya dispararon la alerta de desconocido
 	// (issue #248, persistido en kv: cada MAC alerta UNA sola vez).
@@ -480,6 +484,7 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		engine:               alerts.New(d, nil),
 		wgActive:             map[string]bool{},
 		wgActiveSince:        map[string]time.Time{},
+		wgUrgent:             map[string]bool{},
 		weakAlerted:          map[string]int64{},
 		onlineMacs:           map[string]bool{},
 		unknownGrace:         map[string]int{},
@@ -550,6 +555,8 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 			l.impostorEnabled = enRaw != "0"
 		}
 	}
+	// #1441: peers marcados como urgentes (persistidos en kv).
+	l.loadWGUrgent()
 	l.SetRouters(initial)
 	return l
 }
@@ -2560,7 +2567,12 @@ func (l *Live) pollWireGuard(devices []Device) *WireGuardStats {
 			peerNames[d.IP] = WGPeerName{ID: d.ID, Name: d.Name, Type: d.Type}
 		}
 	}
-	stats, err := GetWireGuardStats(l.pool, gw.SSHAddr(), l.cfg.WGInterface, "", peerNames)
+	// #1441: copia del conjunto de urgentes para estamparlo en cada peer sin
+	// tener el mutex tomado durante el sondeo SSH.
+	l.mu.Lock()
+	urgent := l.wgUrgentCopyLocked()
+	l.mu.Unlock()
+	stats, err := GetWireGuardStats(l.pool, gw.SSHAddr(), l.cfg.WGInterface, "", peerNames, urgent)
 	if err != nil {
 		log.Printf("[netpulse] WireGuard no disponible: %v", err)
 		return &WireGuardStats{Interface: l.cfg.WGInterface, Subnet: "", Status: "inactive", Peers: []WGPeer{}}
@@ -2575,6 +2587,11 @@ func (l *Live) pollWireGuard(devices []Device) *WireGuardStats {
 // peers whose active state changed since the last successful poll, and keeps
 // wgActive/wgActiveSince in sync. A peer that was never active cannot emit a
 // disconnect; the first post-boot cycle never emits a connect (warmup).
+//
+// #1441: la alerta de un peer URGENTE sale con Urgent=true (aviso push); la de
+// un peer normal con Urgent=false (solo queda en el log). La categoría y los
+// IDs no cambian: lo único que distingue a un site-to-site de un portátil es
+// el flag que puso el admin.
 func (l *Live) applyWireGuardTransitions(stats *WireGuardStats, gwID string) {
 	activeNow := map[string]bool{}
 	for _, p := range stats.Peers {
@@ -2584,6 +2601,14 @@ func (l *Live) applyWireGuardTransitions(stats *WireGuardStats, gwID string) {
 	}
 	l.mu.Lock()
 	defer l.mu.Unlock()
+	// Urgencia por peer: el flag viene estampado del sondeo (Urgent) y, por si
+	// el llamador construyó los WGPeer a mano, se cruza con el conjunto
+	// persistido por Key o por ID.
+	urgentNow := map[string]bool{}
+	for _, p := range stats.Peers {
+		urgentNow[p.ID] = p.Urgent || l.wgUrgent[p.Key] || l.wgUrgent[p.ID]
+	}
+
 	// Disconnects: previously active peers no longer present in activeNow.
 	for id := range l.wgActive {
 		if activeNow[id] {
@@ -2599,7 +2624,7 @@ func (l *Live) applyWireGuardTransitions(stats *WireGuardStats, gwID string) {
 		l.engine.Emit(AlertEvent{
 			ID:          fmt.Sprintf("alert-wg-down-%s-%d", id, time.Now().UnixMilli()),
 			Category:    alerts.CatVPN,
-			Urgent:      false,
+			Urgent:      urgentNow[id],
 			Severity:    "info",
 			Title:       "WireGuard disconnect",
 			Description: fmt.Sprintf("%s disconnected after %s", name, dur),
@@ -2625,7 +2650,7 @@ func (l *Live) applyWireGuardTransitions(stats *WireGuardStats, gwID string) {
 			l.engine.Emit(AlertEvent{
 				ID:          fmt.Sprintf("alert-wg-%s-%d", id, time.Now().UnixMilli()),
 				Category:    alerts.CatVPN,
-				Urgent:      false,
+				Urgent:      urgentNow[id],
 				Severity:    "info",
 				Title:       "WireGuard handshake",
 				Description: name + " connected",

+ 15 - 9
server-go/internal/adapters/topo_semantics.go

@@ -737,17 +737,23 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 			wiredLink(dn.HostDeviceID, d)
 		}
 	}
-	// túneles WG: peers activos con coordenada canónica (máx 4)
+	// túneles WG: peers activos con coordenada canónica (máx 4). #1441: los
+	// urgentes primero, igual que el orden de slots del mapa (urgentes
+	// activos → activos → urgentes caídos → caídos): los 4 enlaces del
+	// servidor tienen que ser exactamente los 4 nodos que el front dibuja.
 	n := 0
-	for _, p := range wg.Peers {
-		if !p.Active {
-			continue
-		}
-		if n >= maxTopoPeerChips {
-			break
+	for pass := 0; pass < 2 && n < maxTopoPeerChips; pass++ {
+		wantUrgent := pass == 0
+		for _, p := range wg.Peers {
+			if !p.Active || p.Urgent != wantUrgent {
+				continue
+			}
+			if n >= maxTopoPeerChips {
+				break
+			}
+			sem.Links = append(sem.Links, TopoLink{From: "peer-" + p.ID, To: "internet", Kind: "wg"})
+			n++
 		}
-		sem.Links = append(sem.Links, TopoLink{From: "peer-" + p.ID, To: "internet", Kind: "wg"})
-		n++
 	}
 
 	// -- anillos por router --------------------------------------------------

+ 9 - 1
server-go/internal/adapters/types.go

@@ -120,7 +120,12 @@ type AdGuardStats struct {
 
 // WGPeer es un peer WireGuard (bytes formateados ES: "1,2 GB").
 type WGPeer struct {
-	ID            string `json:"id"`
+	ID string `json:"id"`
+	// Key es el identificador ESTABLE del peer (#1441): la clave pública en
+	// base64url. ID no sirve para persistir nada (depende de los devices de
+	// NetPulse o del índice del dump) y la pubkey en base64 estándar lleva
+	// '+' y '/' y rompería la ruta del endpoint.
+	Key           string `json:"key"`
 	Name          string `json:"name"`
 	Type          string `json:"type"`
 	TunnelIP      string `json:"tunnelIp"`
@@ -128,6 +133,9 @@ type WGPeer struct {
 	LastHandshake string `json:"lastHandshake"`
 	Rx            string `json:"rx"`
 	Tx            string `json:"tx"`
+	// Urgent (#1441): el peer merece notificación cuando se cae (túnel
+	// site-to-site, servidor). Un portátil o un móvil que entra y sale no.
+	Urgent bool `json:"urgent"`
 }
 
 // WireGuardStats (quirk: Status siempre "active" si `wg show` respondió).

+ 35 - 5
server-go/internal/adapters/wireguard.go

@@ -5,6 +5,7 @@
 package adapters
 
 import (
+	"encoding/base64"
 	"fmt"
 	"strconv"
 	"strings"
@@ -290,13 +291,36 @@ func parseWGServerNames(gl string) map[string]string {
 	return out
 }
 
+// WGPeerKey devuelve el identificador ESTABLE y apto para URL de un peer
+// WireGuard (#1441): la clave pública en base64url sin padding (43 chars).
+// Es el único dato que identifica al peer entre sondeos y reinicios: WGPeer.ID
+// sale del device de NetPulse que casó por IP del túnel o, si no hay ninguno,
+// del índice del dump ("peer-3"), que cambia al reordenar los peers.
+// base64url porque una pubkey WireGuard lleva '+' y '/' (base64 estándar) y
+// esos caracteres rompen el path del endpoint de urgencia.
+func WGPeerKey(pubkey string) string {
+	pk := strings.TrimSpace(pubkey)
+	if pk == "" {
+		return ""
+	}
+	raw, err := base64.StdEncoding.DecodeString(pk)
+	if err != nil {
+		// Pubkey no estándar (dump de AmneziaWG o firmware raro): se
+		// translitera a mano en vez de descartarla.
+		return strings.NewReplacer("+", "-", "/", "_", "=", "").Replace(pk)
+	}
+	return base64.RawURLEncoding.EncodeToString(raw)
+}
+
 // buildWGPeer convierte un peer del dump en un WGPeer, resolviendo el nombre
 // con la prioridad de siempre (nombre de device NetPulse → description UCI →
 // nombre del config wireguard_server (GL.iNet) → tunnelIP → "Peer <pubkey8>",
 // issues #659/#1433) y asignando el fallback de ID
 // "peer-<idx>" con un contador global (idx) para que los peers de varias
-// interfaces no colisionen (#713).
-func buildWGPeer(p WGDumpPeer, peerNames map[string]WGPeerName, descs map[string]string, nowSec int64, idx int) WGPeer {
+// interfaces no colisionen (#713). urgent (#1441): claves de peer marcadas
+// como importantes, por Key y, como cortesía, por ID (las llamadas antiguas y
+// los tests construyen WGPeer sin Key).
+func buildWGPeer(p WGDumpPeer, peerNames map[string]WGPeerName, descs map[string]string, nowSec int64, idx int, urgent map[string]bool) WGPeer {
 	tunnelIP := ""
 	if parts := strings.Split(p.AllowedIPs, ","); len(parts) > 0 {
 		tunnelIP = strings.Replace(parts[0], "/32", "", 1)
@@ -331,10 +355,12 @@ func buildWGPeer(p WGDumpPeer, peerNames map[string]WGPeerName, descs map[string
 	if p.HandshakeSec > 0 {
 		lastHandshake = relTime(p.HandshakeSec, nowSec)
 	}
+	key := WGPeerKey(p.Pubkey)
 	return WGPeer{
-		ID: id, Name: name, Type: typ, TunnelIP: tunnelIP,
+		ID: id, Key: key, Name: name, Type: typ, TunnelIP: tunnelIP,
 		Active: active, LastHandshake: lastHandshake,
 		Rx: fmtBytes(float64(p.RxBytes)), Tx: fmtBytes(float64(p.TxBytes)),
+		Urgent: urgent[key] || urgent[id],
 	}
 }
 
@@ -352,7 +378,11 @@ func buildWGPeer(p WGDumpPeer, peerNames map[string]WGPeerName, descs map[string
 // acumulan los peers de las que responden); si TODAS fallan se devuelve
 // Status "inactive" SIN error, para que pollWireGuard no loguee "no
 // disponible" en cada tick.
-func GetWireGuardStats(pool sshRunner, host, iface, subnet string, peerNames map[string]WGPeerName) (*WireGuardStats, error) {
+//
+// urgent (#1441): conjunto de claves de peer (WGPeer.Key) marcadas como
+// importantes por el admin; se estampa en cada WGPeer para que el mapa y las
+// alertas sepan a quién tratar distinto. nil = ninguno.
+func GetWireGuardStats(pool sshRunner, host, iface, subnet string, peerNames map[string]WGPeerName, urgent map[string]bool) (*WireGuardStats, error) {
 	ifaces := wgInterfaces(pool, host, iface)
 	stats := &WireGuardStats{
 		Interface: strings.Join(ifaces, ", "),
@@ -392,7 +422,7 @@ func GetWireGuardStats(pool sshRunner, host, iface, subnet string, peerNames map
 			descs[k] = v
 		}
 		for _, p := range ParseWGDump(dump) {
-			stats.Peers = append(stats.Peers, buildWGPeer(p, peerNames, descs, nowSec, idx))
+			stats.Peers = append(stats.Peers, buildWGPeer(p, peerNames, descs, nowSec, idx, urgent))
 			idx++
 		}
 	}

+ 9 - 9
server-go/internal/adapters/wireguard_test.go

@@ -195,7 +195,7 @@ func TestGetWireGuardStatsGLServerNames(t *testing.T) {
 		}
 		return "", fmt.Errorf("comando inesperado: %s", cmd)
 	}}
-	stats, err := GetWireGuardStats(f, "host", "auto", "", nil)
+	stats, err := GetWireGuardStats(f, "host", "auto", "", nil, nil)
 	if err != nil {
 		t.Fatalf("GetWireGuardStats: %v", err)
 	}
@@ -235,7 +235,7 @@ func TestGetWireGuardStatsUciDescWinsOverGL(t *testing.T) {
 		}
 		return "", fmt.Errorf("comando inesperado: %s", cmd)
 	}}
-	stats, err := GetWireGuardStats(f, "host", "auto", "", nil)
+	stats, err := GetWireGuardStats(f, "host", "auto", "", nil, nil)
 	if err != nil {
 		t.Fatalf("GetWireGuardStats: %v", err)
 	}
@@ -379,7 +379,7 @@ func TestGetWireGuardStatsSingleInterface(t *testing.T) {
 		}
 		return "", fmt.Errorf("comando inesperado: %s", cmd)
 	}}
-	stats, err := GetWireGuardStats(f, "host", "auto", "", nil)
+	stats, err := GetWireGuardStats(f, "host", "auto", "", nil, nil)
 	if err != nil {
 		t.Fatalf("GetWireGuardStats: %v", err)
 	}
@@ -421,7 +421,7 @@ func TestGetWireGuardStatsMultipleInterfaces(t *testing.T) {
 		}
 		return "", fmt.Errorf("comando inesperado: %s", cmd)
 	}}
-	stats, err := GetWireGuardStats(f, "host", "auto", "", nil)
+	stats, err := GetWireGuardStats(f, "host", "auto", "", nil, nil)
 	if err != nil {
 		t.Fatalf("GetWireGuardStats: %v", err)
 	}
@@ -450,7 +450,7 @@ func TestGetWireGuardStatsNoInterfaces(t *testing.T) {
 		}
 		return "", fmt.Errorf("comando inesperado: %s", cmd)
 	}}
-	stats, err := GetWireGuardStats(f, "host", "auto", "", nil)
+	stats, err := GetWireGuardStats(f, "host", "auto", "", nil, nil)
 	if err != nil {
 		t.Fatalf("GetWireGuardStats: %v", err)
 	}
@@ -476,7 +476,7 @@ func TestGetWireGuardStatsExplicitFilter(t *testing.T) {
 		}
 		return "", fmt.Errorf("comando inesperado: %s", cmd)
 	}}
-	stats, err := GetWireGuardStats(f, "host", "wg1", "", nil)
+	stats, err := GetWireGuardStats(f, "host", "wg1", "", nil, nil)
 	if err != nil {
 		t.Fatalf("GetWireGuardStats: %v", err)
 	}
@@ -523,7 +523,7 @@ func TestGetWireGuardStatsOneInterfaceFails(t *testing.T) {
 		}
 		return "", fmt.Errorf("comando inesperado: %s", cmd)
 	}}
-	stats, err := GetWireGuardStats(f, "host", "auto", "", nil)
+	stats, err := GetWireGuardStats(f, "host", "auto", "", nil, nil)
 	if err != nil {
 		t.Fatalf("GetWireGuardStats: %v (no debe abortar por una interfaz caída)", err)
 	}
@@ -545,7 +545,7 @@ func TestGetWireGuardStatsAllFail(t *testing.T) {
 		}
 		return "", fmt.Errorf("exit status 1")
 	}}
-	stats, err := GetWireGuardStats(f, "host", "auto", "", nil)
+	stats, err := GetWireGuardStats(f, "host", "auto", "", nil, nil)
 	if err != nil {
 		t.Fatalf("GetWireGuardStats: %v (todas fallan → inactive sin error)", err)
 	}
@@ -576,7 +576,7 @@ func TestGetWireGuardStatsAmneziaWG(t *testing.T) {
 		}
 		return "", fmt.Errorf("comando inesperado: %s", cmd)
 	}}
-	stats, err := GetWireGuardStats(f, "host", "auto", "", nil)
+	stats, err := GetWireGuardStats(f, "host", "auto", "", nil, nil)
 	if err != nil {
 		t.Fatalf("GetWireGuardStats: %v", err)
 	}

+ 130 - 0
server-go/internal/adapters/wireguard_urgent.go

@@ -0,0 +1,130 @@
+package adapters
+
+// wireguard_urgent.go — flag "urgente" por peer WireGuard (#1441).
+//
+// No todos los peers importan igual: un túnel site-to-site o un servidor
+// merece aviso cuando se cae; un portátil o un móvil que entra y sale es
+// rutina y solo debe quedar en el log. El admin marca peers a mano y la
+// decisión se persiste.
+//
+// Persistencia: UNA clave kv (`wireguard.urgent_peers`) con un JSON de claves
+// de peer (WGPeer.Key, la pubkey en base64url). No hace falta tabla nueva: la
+// lista es pequeña, se lee entera y el patrón kv ya es el que usan los demás
+// ajustes del repo (impostor_allowlist_v1, alerts.impostor_enabled...). Un
+// id estable de peer es la pubkey; el ID de WGPeer no vale (sale del device
+// que casó por IP del túnel o del índice del dump y cambia entre sondeos).
+//
+// Live mantiene el conjunto en memoria (como impostorAllow) para que las
+// transiciones y el snapshot no consulten la BD en cada vuelta; el setter
+// escribe kv y memoria a la vez.
+
+import (
+	"encoding/json"
+	"fmt"
+	"regexp"
+	"sort"
+)
+
+// wgUrgentKey: clave kv con la lista JSON de claves de peer urgentes.
+const wgUrgentKey = "wireguard.urgent_peers"
+
+// wgPeerKeyRe valida una clave de peer tal como la genera WGPeerKey
+// (base64url sin padding, 43 chars para pubkeys de 32 bytes). El rango de
+// longitud deja sitio a las claves transliteradas a mano y a las del demo,
+// pero corta cualquier intento de escribir basura en el kv.
+var wgPeerKeyRe = regexp.MustCompile(`^[A-Za-z0-9_-]{8,64}$`)
+
+// WireGuardPeerUrgent dice si una clave de peer está marcada como urgente.
+func (l *Live) WireGuardPeerUrgent(key string) bool {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	return l.wgUrgent[key]
+}
+
+// SetWireGuardPeerUrgent (#1441) marca o desmarca un peer como urgente.
+// Persiste en kv y actualiza la copia en memoria: el siguiente snapshot
+// (/api/overview) y la siguiente transición ya ven el flag nuevo, sin
+// reiniciar ni esperar a un sondeo. Devuelve error si la clave no tiene la
+// forma esperada (la validación de tamaño/caracteres vive aquí, junto al
+// almacenamiento, para que el endpoint no pueda guardar cualquier cosa).
+func (l *Live) SetWireGuardPeerUrgent(key string, urgent bool) error {
+	if !wgPeerKeyRe.MatchString(key) {
+		return fmt.Errorf("invalid peer key %q", key)
+	}
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	if l.wgUrgent == nil {
+		l.wgUrgent = map[string]bool{}
+	}
+	if urgent {
+		l.wgUrgent[key] = true
+	} else {
+		delete(l.wgUrgent, key)
+	}
+	l.saveWGUrgentLocked()
+	return nil
+}
+
+// WireGuardUrgentPeers devuelve las claves marcadas, ordenadas. La usa el
+// endpoint de lectura y sirve para depurar qué quedó persistido.
+func (l *Live) WireGuardUrgentPeers() []string {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	out := make([]string, 0, len(l.wgUrgent))
+	for k := range l.wgUrgent {
+		out = append(out, k)
+	}
+	sort.Strings(out)
+	return out
+}
+
+// wgUrgentCopyLocked: copia del conjunto para pasarla al adapter sin el mutex
+// tomado. Caller holds l.mu.
+func (l *Live) wgUrgentCopyLocked() map[string]bool {
+	out := make(map[string]bool, len(l.wgUrgent))
+	for k := range l.wgUrgent {
+		out[k] = true
+	}
+	return out
+}
+
+// loadWGUrgent (#1441) lee la lista persistida al arrancar. Ausente, vacía o
+// corrupta → sin peers urgentes (nunca rompe el arranque por un ajuste).
+func (l *Live) loadWGUrgent() {
+	if l.db == nil {
+		return
+	}
+	var raw string
+	if err := l.db.QueryRow("SELECT value FROM kv WHERE key = ?", wgUrgentKey).Scan(&raw); err != nil {
+		return
+	}
+	var list []string
+	if json.Unmarshal([]byte(raw), &list) != nil {
+		return
+	}
+	for _, k := range list {
+		if wgPeerKeyRe.MatchString(k) {
+			l.wgUrgent[k] = true
+		}
+	}
+}
+
+// saveWGUrgentLocked: persiste la lista en kv (lista ordenada para que el
+// valor no cambie de forma si no cambia el contenido). Caller holds l.mu.
+func (l *Live) saveWGUrgentLocked() {
+	if l.db == nil {
+		return
+	}
+	list := make([]string, 0, len(l.wgUrgent))
+	for k := range l.wgUrgent {
+		list = append(list, k)
+	}
+	sort.Strings(list)
+	raw, err := json.Marshal(list)
+	if err != nil {
+		return
+	}
+	_, _ = l.db.Exec(
+		"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+		wgUrgentKey, string(raw))
+}

+ 259 - 0
server-go/internal/adapters/wireguard_urgent_test.go

@@ -0,0 +1,259 @@
+// wireguard_urgent_test.go — #1441: flag urgente por peer WireGuard
+// (clave estable, persistencia en kv y Urgent en las alertas de transición).
+package adapters
+
+import (
+	"encoding/base64"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// realPubkey: una pubkey WireGuard de 32 bytes en base64 estándar (44 chars,
+// con '=' final). La de los fixtures reales del repo también vale.
+func realPubkey(seed byte) string {
+	raw := make([]byte, 32)
+	for i := range raw {
+		raw[i] = seed + byte(i)
+	}
+	return base64.StdEncoding.EncodeToString(raw)
+}
+
+func TestWGPeerKeyIsURLSafeAndStable(t *testing.T) {
+	pub := realPubkey(1)
+	key := WGPeerKey(pub)
+	if len(key) != 43 {
+		t.Fatalf("key len = %d (%q), want 43 (base64url sin padding)", len(key), key)
+	}
+	if strings.ContainsAny(key, "+/=") {
+		t.Errorf("key %q lleva caracteres que rompen el path", key)
+	}
+	if again := WGPeerKey(pub); again != key {
+		t.Errorf("key no estable: %q != %q", again, key)
+	}
+	if other := WGPeerKey(realPubkey(2)); other == key {
+		t.Errorf("dos pubkeys distintas comparten key %q", key)
+	}
+	if WGPeerKey("") != "" {
+		t.Error("pubkey vacía debería dar key vacía")
+	}
+	// Pubkey no estándar (no decodifica): se translitera, sin '+' ni '/'.
+	if got := WGPeerKey("ab+cd/ef=="); strings.ContainsAny(got, "+/=") || got == "" {
+		t.Errorf("transliteración de pubkey rara: %q", got)
+	}
+}
+
+func TestBuildWGPeerStampsUrgencyByKey(t *testing.T) {
+	pub := realPubkey(7)
+	key := WGPeerKey(pub)
+	descs := map[string]string{}
+	peer := buildWGPeer(WGDumpPeer{Pubkey: pub, AllowedIPs: "10.0.0.9/32", HandshakeSec: time.Now().Unix()},
+		nil, descs, time.Now().Unix(), 1, map[string]bool{key: true})
+	if peer.Key != key {
+		t.Fatalf("Key: %q, want %q", peer.Key, key)
+	}
+	if !peer.Urgent {
+		t.Error("el peer marcado por Key debería salir Urgent=true")
+	}
+	other := buildWGPeer(WGDumpPeer{Pubkey: realPubkey(8), AllowedIPs: "10.0.0.10/32"},
+		nil, descs, time.Now().Unix(), 2, map[string]bool{key: true})
+	if other.Urgent {
+		t.Error("un peer sin marcar no puede salir Urgent=true")
+	}
+	if other.Key == key {
+		t.Error("peers distintos no pueden compartir Key")
+	}
+}
+
+// newUrgentLive: Live con BD real (tabla kv de db.Open) y engine para VPN.
+func newUrgentLive(t *testing.T) (*Live, *db.DB) {
+	t.Helper()
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	l := NewLive(nil, d, nil, nil)
+	if err := l.engine.SetConfig(map[string]string{alerts.CatVPN: alerts.LevelAll}); err != nil {
+		t.Fatalf("SetConfig vpn: %v", err)
+	}
+	return l, d
+}
+
+func TestSetWireGuardPeerUrgentPersistsInKV(t *testing.T) {
+	l, d := newUrgentLive(t)
+	key := WGPeerKey(realPubkey(3))
+	if err := l.SetWireGuardPeerUrgent(key, true); err != nil {
+		t.Fatalf("SetWireGuardPeerUrgent(true): %v", err)
+	}
+	if !l.WireGuardPeerUrgent(key) {
+		t.Error("el peer debería quedar marcado en memoria")
+	}
+	if got := l.WireGuardUrgentPeers(); len(got) != 1 || got[0] != key {
+		t.Errorf("WireGuardUrgentPeers = %v, want [%s]", got, key)
+	}
+	var raw string
+	if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", wgUrgentKey).Scan(&raw); err != nil {
+		t.Fatalf("kv: %v", err)
+	}
+	if !strings.Contains(raw, key) {
+		t.Errorf("kv %q no contiene la clave %q", raw, key)
+	}
+	// Reinicio: un Live nuevo sobre la misma BD recupera el flag.
+	reloaded := NewLive(nil, d, nil, nil)
+	if !reloaded.WireGuardPeerUrgent(key) {
+		t.Error("el flag no sobrevive a un reinicio del servidor")
+	}
+	// Desmarcar lo quita de memoria y del kv.
+	if err := reloaded.SetWireGuardPeerUrgent(key, false); err != nil {
+		t.Fatalf("SetWireGuardPeerUrgent(false): %v", err)
+	}
+	if reloaded.WireGuardPeerUrgent(key) {
+		t.Error("el peer debería quedar desmarcado")
+	}
+	if got := reloaded.WireGuardUrgentPeers(); len(got) != 0 {
+		t.Errorf("WireGuardUrgentPeers = %v, want vacío", got)
+	}
+	// Y un tercer arranque no lo resucita.
+	if NewLive(nil, d, nil, nil).WireGuardPeerUrgent(key) {
+		t.Error("el flag desmarcado no debe reaparecer tras reiniciar")
+	}
+}
+
+func TestSetWireGuardPeerUrgentRejectsInvalidKey(t *testing.T) {
+	l, _ := newUrgentLive(t)
+	for _, key := range []string{"", "con espacio", "a/b", strings.Repeat("x", 65)} {
+		if err := l.SetWireGuardPeerUrgent(key, true); err == nil {
+			t.Errorf("clave %q aceptada, debería rechazarse", key)
+		}
+	}
+}
+
+// Corrupto/no lista: el arranque no se rompe y no hay urgentes.
+func TestLoadWGUrgentIgnoresGarbage(t *testing.T) {
+	_, d := newUrgentLive(t)
+	if _, err := d.Exec(`INSERT INTO kv (key, value) VALUES (?, ?)`, wgUrgentKey, `{"no":"es una lista"}`); err != nil {
+		t.Fatalf("seed kv: %v", err)
+	}
+	reloaded := NewLive(nil, d, nil, nil)
+	if got := reloaded.WireGuardUrgentPeers(); len(got) != 0 {
+		t.Errorf("kv corrupto no debe producir urgentes: %v", got)
+	}
+}
+
+// dropOnePeer: un ciclo de caída para un peer concreto y su alerta (el engine
+// deduplica por categoría+título+router durante 5 min, así que un test de dos
+// peers necesita dos Live separados, igual que dos incidentes reales).
+func dropOnePeer(t *testing.T, peer WGPeer) AlertEvent {
+	t.Helper()
+	l, _ := newUrgentLive(t)
+	l.wgActive = map[string]bool{peer.ID: true}
+	l.wgActiveSince = map[string]time.Time{peer.ID: time.Now().Add(-2 * time.Hour)}
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{peer}}, "gw")
+	for _, ev := range l.engine.List() {
+		if ev.Type == alerts.TypeWireguardDisconnect {
+			return ev
+		}
+	}
+	t.Fatalf("sin alerta de caída para %s", peer.Name)
+	return AlertEvent{}
+}
+
+// La alerta de caída de un peer urgente sale con Urgent=true; la de uno
+// normal sigue en false. Categoría e ID no cambian (#1348/#1441).
+func TestWireGuardDisconnectUrgencyFollowsFlag(t *testing.T) {
+	urgent := WGPeer{ID: "site-a", Key: WGPeerKey(realPubkey(11)), Name: "Site A", Active: false}
+	l, _ := newUrgentLive(t)
+	if err := l.SetWireGuardPeerUrgent(urgent.Key, true); err != nil {
+		t.Fatalf("marcar urgente: %v", err)
+	}
+	l.wgActive = map[string]bool{urgent.ID: true}
+	l.wgActiveSince = map[string]time.Time{urgent.ID: time.Now().Add(-2 * time.Hour)}
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{urgent}}, "gw")
+
+	byPeer := map[string]AlertEvent{}
+	for _, ev := range l.engine.List() {
+		if ev.Type == alerts.TypeWireguardDisconnect {
+			byPeer[ev.Vars["peer"]] = ev
+		}
+	}
+	site, ok := byPeer["Site A"]
+	if !ok {
+		t.Fatalf("sin alerta de caída para Site A: %v", byPeer)
+	}
+	if !site.Urgent {
+		t.Error("la caída de un peer urgente debe salir Urgent=true")
+	}
+	if site.Category != alerts.CatVPN {
+		t.Errorf("categoría: %q, want %q", site.Category, alerts.CatVPN)
+	}
+	if !strings.HasPrefix(site.ID, "alert-wg-down-") {
+		t.Errorf("ID: %q, want prefijo alert-wg-down-", site.ID)
+	}
+
+	laptop := dropOnePeer(t, WGPeer{ID: "laptop", Key: WGPeerKey(realPubkey(12)), Name: "Laptop", Active: false})
+	if laptop.Urgent {
+		t.Error("la caída de un peer normal debe seguir en Urgent=false")
+	}
+	if laptop.Category != alerts.CatVPN {
+		t.Errorf("categoría del peer normal: %q, want %q", laptop.Category, alerts.CatVPN)
+	}
+}
+
+// El handshake de un peer urgente también avisa; el de uno normal, no.
+func TestWireGuardHandshakeUrgencyFollowsFlag(t *testing.T) {
+	l, _ := newUrgentLive(t)
+	urgentKey := WGPeerKey(realPubkey(21))
+	if err := l.SetWireGuardPeerUrgent(urgentKey, true); err != nil {
+		t.Fatalf("marcar urgente: %v", err)
+	}
+	l.wgActive = map[string]bool{"otro": true}
+	l.wgActiveSince = map[string]time.Time{"otro": time.Now()}
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
+		{ID: "site-a", Key: urgentKey, Name: "Site A", Active: true},
+		{ID: "otro", Key: WGPeerKey(realPubkey(22)), Name: "Otro", Active: true},
+	}}, "gw")
+
+	handshakes := map[string]bool{}
+	for _, ev := range l.engine.List() {
+		if ev.Type == alerts.TypeWireguardHandshake {
+			handshakes[ev.Vars["peer"]] = ev.Urgent
+		}
+	}
+	if u, ok := handshakes["Site A"]; !ok || !u {
+		t.Errorf("handshake de Site A: urgente=%v (presente=%v), want true", u, ok)
+	}
+}
+
+// Los 4 enlaces WG de la semántica son los mismos 4 nodos que dibuja el mapa:
+// urgentes activos primero, después los activos normales (#1441).
+func TestTopoSemanticsWGLinksUrgentFirst(t *testing.T) {
+	wg := WireGuardStats{Peers: []WGPeer{
+		{ID: "a", Active: true},
+		{ID: "b", Active: true},
+		{ID: "c", Active: true},
+		{ID: "site-to-site", Active: true, Urgent: true},
+		{ID: "quinta", Active: true},
+		{ID: "caido", Active: false},
+		{ID: "caido-urgente", Active: false, Urgent: true},
+	}}
+	sem := BuildTopoSemantics([]Router{{ID: "gw", Name: "GW", RoleBadge: "Principal"}}, nil, wg, nil, "", nil, nil, nil)
+	got := []string{}
+	for _, l := range sem.Links {
+		if l.Kind == "wg" {
+			got = append(got, l.From)
+		}
+	}
+	want := []string{"peer-site-to-site", "peer-a", "peer-b", "peer-c"}
+	if len(got) != len(want) {
+		t.Fatalf("enlaces wg: %v, want %v", got, want)
+	}
+	for i := range want {
+		if got[i] != want[i] {
+			t.Fatalf("enlaces wg: %v, want %v", got, want)
+		}
+	}
+}

+ 2 - 0
server-go/internal/httpapi/admin_gate_test.go

@@ -61,6 +61,8 @@ func TestRutasAdminDevuelven403ParaRolUser(t *testing.T) {
 		{"DELETE", "/api/config/routers/rt2"},
 		{"GET", "/api/config/sshkey"},
 		{"GET", "/api/config/discover"},
+		{"PUT", "/api/wireguard/peers/qooNaqES5pnpfSeBQ6WNQmMYVIyiTYqiY75NtQmhLJ8/urgent"},
+		{"GET", "/api/wireguard/urgent"},
 	}
 	for _, rt := range adminOnly {
 		if got := do(t, rt.method, ts.URL, rt.path, userCookie).StatusCode; got != 403 {

+ 1 - 0
server-go/internal/httpapi/server.go

@@ -418,6 +418,7 @@ func NewHandler(d Deps) http.Handler {
 	mux.HandleFunc("GET /api/path/destinations", s.handlePathDestinations)
 	mux.HandleFunc("GET /api/metrics", s.handleMetrics)
 	mux.HandleFunc("GET /api/topology", s.handleTopology)
+	s.registerWireGuardUrgentRoutes(mux)
 	mux.HandleFunc("GET /api/usteer", s.handleUsteer)
 	mux.HandleFunc("POST /api/usteer/{mac}/kick", s.handleUsteerKick)
 	s.registerReanchorRoutes(mux)

+ 71 - 0
server-go/internal/httpapi/wireguard_urgent.go

@@ -0,0 +1,71 @@
+// wireguard_urgent.go — flag "urgente" por peer WireGuard (#1441).
+//
+//	PUT /api/wireguard/peers/{key}/urgent  body {"urgent":true|false}
+//	GET /api/wireguard/urgent              claves marcadas (diagnóstico)
+//
+// `key` es el WGPeer.Key que sirve /api/overview (la clave pública en
+// base64url): el único identificador del peer que sobrevive a sondeos y
+// reinicios. El flag viaja en el propio WGPeer (`urgent`) y decide si sus
+// caídas avisan o solo quedan en el log (adapters.applyWireGuardTransitions).
+package httpapi
+
+import (
+	"net/http"
+	"regexp"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+)
+
+// wgPeerKeyPathRe: forma aceptada de la clave en el path. Misma regla que el
+// almacenamiento del adapter (base64url, 43 chars para una pubkey real); se
+// valida AQUÍ antes de tocar el adapter para no pasar basura al kv.
+var wgPeerKeyPathRe = regexp.MustCompile(`^[A-Za-z0-9_-]{8,64}$`)
+
+func (s *server) registerWireGuardUrgentRoutes(mux *http.ServeMux) {
+	mux.Handle("PUT /api/wireguard/peers/{key}/urgent", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		key := r.PathValue("key")
+		if !wgPeerKeyPathRe.MatchString(key) {
+			writeError(w, http.StatusBadRequest, "invalid_peer", "invalid WireGuard peer key")
+			return
+		}
+		var body struct {
+			Urgent *bool `json:"urgent"`
+		}
+		if st := readJSONBody(w, r, &body); st != 0 {
+			writeBodyError(w, st, "invalid_body", "body JSON inválido")
+			return
+		}
+		if body.Urgent == nil {
+			writeError(w, http.StatusBadRequest, "invalid_body", "urgent is required")
+			return
+		}
+		setter, ok := s.adapter.(interface {
+			SetWireGuardPeerUrgent(string, bool) error
+		})
+		if !ok {
+			writeError(w, http.StatusNotImplemented, "not_supported", "adapter does not support WireGuard peer urgency")
+			return
+		}
+		if err := setter.SetWireGuardPeerUrgent(key, *body.Urgent); err != nil {
+			writeError(w, http.StatusBadRequest, "invalid_peer", err.Error())
+			return
+		}
+		writeJSON(w, http.StatusOK, map[string]any{"key": key, "urgent": *body.Urgent})
+	})))
+
+	// Diagnóstico: qué peers quedaron marcados en la BD. Sirve para comprobar
+	// una persistencia y para entender un aviso que llega (o no llega) sin
+	// rebuscar en la tabla kv a mano.
+	mux.Handle("GET /api/wireguard/urgent", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		reader, ok := s.adapter.(interface{ WireGuardUrgentPeers() []string })
+		if !ok {
+			writeJSON(w, http.StatusOK, map[string]any{"peers": []string{}})
+			return
+		}
+		peers := reader.WireGuardUrgentPeers()
+		if peers == nil {
+			peers = []string{}
+		}
+		writeJSON(w, http.StatusOK, map[string]any{"peers": peers})
+	})))
+}

+ 237 - 0
server-go/internal/httpapi/wireguard_urgent_test.go

@@ -0,0 +1,237 @@
+// wireguard_urgent_test.go — endpoint del flag urgente por peer (#1441):
+// auth admin, validación de clave y cuerpo, y round-trip de persistencia.
+//
+// El adapter demo NO implementa el flag (el endpoint responde 501), así que
+// los casos de escritura usan un stub que embebe *adapters.Demo y añade el
+// setter/lector, igual que el Live real los añade sobre el Snapshotter.
+package httpapi_test
+
+import (
+	"encoding/json"
+	"net/http"
+	"net/http/httptest"
+	"sort"
+	"strings"
+	"sync"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/apitoken"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/channelplan"
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/configbackup"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/orchestr"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+)
+
+// wgUrgentAdapter: demo + el flag urgente en memoria (lo que en producción
+// hace Live con la tabla kv).
+type wgUrgentAdapter struct {
+	*adapters.Demo
+	mu     sync.Mutex
+	urgent map[string]bool
+}
+
+func (a *wgUrgentAdapter) SetWireGuardPeerUrgent(key string, urgent bool) error {
+	a.mu.Lock()
+	defer a.mu.Unlock()
+	if a.urgent == nil {
+		a.urgent = map[string]bool{}
+	}
+	if urgent {
+		a.urgent[key] = true
+	} else {
+		delete(a.urgent, key)
+	}
+	return nil
+}
+
+func (a *wgUrgentAdapter) WireGuardUrgentPeers() []string {
+	a.mu.Lock()
+	defer a.mu.Unlock()
+	out := make([]string, 0, len(a.urgent))
+	for k := range a.urgent {
+		out = append(out, k)
+	}
+	sort.Strings(out)
+	return out
+}
+
+// makeWGUrgentServer: réplica de makeTestServer con el adapter del flag.
+func makeWGUrgentServer(t *testing.T) *testServer {
+	t.Helper()
+	auth.SetTrustProxy(true)
+	t.Cleanup(func() { auth.SetTrustProxy(false) })
+	dataDir := t.TempDir()
+	cfg, err := config.Load(map[string]string{
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
+		"DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
+	}, dataDir)
+	if err != nil {
+		t.Fatalf("config: %v", err)
+	}
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	secret, err := auth.EnsureSessionSecret(d, cfg)
+	if err != nil {
+		t.Fatalf("secret: %v", err)
+	}
+	if err := auth.EnsureUsers(d, cfg); err != nil {
+		t.Fatalf("users: %v", err)
+	}
+	if err := apitoken.EnsureSchema(d); err != nil {
+		t.Fatalf("api_tokens schema: %v", err)
+	}
+	configBackup, err := configbackup.NewStore(d)
+	if err != nil {
+		t.Fatalf("config backup store: %v", err)
+	}
+	handler := httpapi.NewHandler(httpapi.Deps{
+		Config: cfg, DB: d,
+		Adapter:      &wgUrgentAdapter{Demo: adapters.NewDemo()},
+		Hub:          sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil }),
+		Secret:       secret,
+		Started:      time.Now(),
+		TokenStore:   apitoken.NewStore(d, secret),
+		ConfigBackup: configBackup,
+		Orchestr:     orchestr.New(d),
+		Agents:       adapters.NewAgentRegistry(0),
+		ChannelPlan:  channelplan.NewStore(d.DB),
+	})
+	srv := httptest.NewServer(handler)
+	ts := &testServer{Server: srv, db: d, secret: secret}
+	t.Cleanup(func() {
+		srv.Close()
+		d.Close()
+	})
+	return ts
+}
+
+// wgPeerKey: identificador url-safe con la forma que acepta el endpoint
+// (8-64 chars). Sintético a propósito: una pubkey real dispara el escáner.
+const wgPeerKey = "test-peer-urgent-key"
+
+func putUrgent(t *testing.T, base, key, body, cookie string) (int, map[string]any) {
+	t.Helper()
+	req, _ := http.NewRequest("PUT", base+"/api/wireguard/peers/"+key+"/urgent", strings.NewReader(body))
+	req.Header.Set("Content-Type", "application/json")
+	if cookie != "" {
+		req.Header.Set("Cookie", "session="+cookie)
+	}
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("PUT urgent: %v", err)
+	}
+	defer res.Body.Close()
+	out := map[string]any{}
+	_ = json.NewDecoder(res.Body).Decode(&out)
+	return res.StatusCode, out
+}
+
+func urgentKeys(t *testing.T, base, cookie string) []string {
+	t.Helper()
+	req, _ := http.NewRequest("GET", base+"/api/wireguard/urgent", nil)
+	req.Header.Set("Cookie", "session="+cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("GET urgent: %v", err)
+	}
+	defer res.Body.Close()
+	var body struct {
+		Peers []string `json:"peers"`
+	}
+	if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
+		t.Fatalf("decode: %v", err)
+	}
+	return body.Peers
+}
+
+func TestWireGuardPeerUrgentRequiresAdminSession(t *testing.T) {
+	ts := makeWGUrgentServer(t)
+	// Sin sesión → 401.
+	if got, _ := putUrgent(t, ts.URL, wgPeerKey, `{"urgent":true}`, ""); got != http.StatusUnauthorized {
+		t.Errorf("sin sesión: %d, want 401", got)
+	}
+	// Sesión de rol user → 403.
+	_, adminCookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	userCookie := createUserAndLogin(t, ts.URL, adminCookie, "viewer", "clave12345", "user")
+	if got, _ := putUrgent(t, ts.URL, wgPeerKey, `{"urgent":true}`, userCookie); got != http.StatusForbidden {
+		t.Errorf("rol user: %d, want 403", got)
+	}
+}
+
+func TestWireGuardPeerUrgentValidatesInput(t *testing.T) {
+	ts := makeWGUrgentServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	cases := []struct {
+		name, key, body string
+		wantStatus      int
+	}{
+		{"clave con +", "abc+def", `{"urgent":true}`, http.StatusBadRequest},
+		// '/' no llega al handler: la ruta no casa (por eso la API expone la
+		// pubkey en base64url).
+		{"clave con /", "abc/def", `{"urgent":true}`, http.StatusNotFound},
+		{"clave demasiado corta", "abc", `{"urgent":true}`, http.StatusBadRequest},
+		{"sin urgent", wgPeerKey, `{}`, http.StatusBadRequest},
+		{"urgent no booleano", wgPeerKey, `{"urgent":"si"}`, http.StatusBadRequest},
+	}
+	for _, c := range cases {
+		got, _ := putUrgent(t, ts.URL, c.key, c.body, cookie)
+		if got != c.wantStatus {
+			t.Errorf("%s: %d, want %d", c.name, got, c.wantStatus)
+		}
+	}
+}
+
+func TestWireGuardPeerUrgentRoundTrip(t *testing.T) {
+	ts := makeWGUrgentServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	if keys := urgentKeys(t, ts.URL, cookie); len(keys) != 0 {
+		t.Fatalf("arranque con urgentes: %v", keys)
+	}
+	got, body := putUrgent(t, ts.URL, wgPeerKey, `{"urgent":true}`, cookie)
+	if got != http.StatusOK {
+		t.Fatalf("marcar: %d (%v)", got, body)
+	}
+	if body["urgent"] != true || body["key"] != wgPeerKey {
+		t.Errorf("respuesta: %v", body)
+	}
+	if keys := urgentKeys(t, ts.URL, cookie); len(keys) != 1 || keys[0] != wgPeerKey {
+		t.Errorf("lectura tras marcar: %v, want [%s]", keys, wgPeerKey)
+	}
+	// Idempotente: marcar dos veces no duplica.
+	if got, _ := putUrgent(t, ts.URL, wgPeerKey, `{"urgent":true}`, cookie); got != http.StatusOK {
+		t.Fatalf("marcar de nuevo: %d", got)
+	}
+	if keys := urgentKeys(t, ts.URL, cookie); len(keys) != 1 {
+		t.Errorf("lectura tras re-marcar: %v, want 1 entrada", keys)
+	}
+	// Desmarcar lo quita.
+	if got, _ := putUrgent(t, ts.URL, wgPeerKey, `{"urgent":false}`, cookie); got != http.StatusOK {
+		t.Fatalf("desmarcar: %d", got)
+	}
+	if keys := urgentKeys(t, ts.URL, cookie); len(keys) != 0 {
+		t.Errorf("lectura tras desmarcar: %v, want vacío", keys)
+	}
+}
+
+// El adapter demo (el de /api/overview del modo demo) NO soporta el flag: el
+// endpoint lo dice con 501 en vez de fingir que guardó.
+func TestWireGuardPeerUrgentNotSupportedInDemoAdapter(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	if got, _ := putUrgent(t, ts.URL, wgPeerKey, `{"urgent":true}`, cookie); got != http.StatusNotImplemented {
+		t.Errorf("adapter demo: %d, want 501", got)
+	}
+	if keys := urgentKeys(t, ts.URL, cookie); len(keys) != 0 {
+		t.Errorf("adapter demo no debe listar urgentes: %v", keys)
+	}
+}