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

feat(alerts): add expiring exceptions with hit counters (#2301)

Nacho 15 часов назад
Родитель
Сommit
aa8ef0d257

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

@@ -74,6 +74,33 @@
     "configButton": "Configure alerts",
     "configTitle": "Alert settings",
     "configDescription": "Choose what gets recorded and what notifies you, per category. On \"Nothing\" the category disappears from the history and the bell.",
+    "exceptions": {
+      "title": "Exceptions",
+      "description": "Mute future alerts that match a type, a host and a target. Alerts already in the feed are not removed.",
+      "empty": "No exceptions yet.",
+      "anyType": "Any type",
+      "anyHost": "Any host",
+      "kind": "Alert type",
+      "host": "Host",
+      "hostPlaceholder": "Router ID or MAC (empty = any)",
+      "target": "Target",
+      "targetPlaceholder": "Port, domain or MAC (empty = any)",
+      "comment": "Note",
+      "commentPlaceholder": "Why this exception exists",
+      "expires": "Expires",
+      "expiresOn": "Expires {{date}}",
+      "never": "Never expires",
+      "lastHit": "Last hit {{date}}",
+      "hits": "Hits: {{count}}",
+      "expired": "Expired",
+      "add": "Add exception",
+      "edit": "Edit exception",
+      "save": "Save",
+      "delete": "Delete exception",
+      "saveError": "Could not save the exception.",
+      "loadError": "Could not load the exceptions.",
+      "hint": "Empty fields match anything. Host matches the alert's router or its MAC. Target matches any value carried by the alert (port, domain, MAC)."
+    },
     "configSaved": "Saved",
     "configSaveError": "Could not save — please try again",
     "categories": {

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

@@ -74,6 +74,33 @@
     "configButton": "Configurar alertas",
     "configTitle": "Configuración de alertas",
     "configDescription": "Elige qué se registra y qué te notifica, por categoría. En \"Nada\" la categoría desaparece del historial y de la campana.",
+    "exceptions": {
+      "title": "Excepciones",
+      "description": "Silencia futuras alertas que casen por tipo, host y destino. Las que ya están en el feed no se borran.",
+      "empty": "Todavía no hay excepciones.",
+      "anyType": "Cualquier tipo",
+      "anyHost": "Cualquier host",
+      "kind": "Tipo de alerta",
+      "host": "Host",
+      "hostPlaceholder": "ID del router o MAC (vacío = cualquiera)",
+      "target": "Destino",
+      "targetPlaceholder": "Puerto, dominio o MAC (vacío = cualquiera)",
+      "comment": "Nota",
+      "commentPlaceholder": "Por qué existe esta excepción",
+      "expires": "Caduca",
+      "expiresOn": "Caduca el {{date}}",
+      "never": "No caduca",
+      "lastHit": "Último impacto {{date}}",
+      "hits": "Impactos: {{count}}",
+      "expired": "Caducada",
+      "add": "Añadir excepción",
+      "edit": "Editar excepción",
+      "save": "Guardar",
+      "delete": "Borrar excepción",
+      "saveError": "No se pudo guardar la excepción.",
+      "loadError": "No se pudieron cargar las excepciones.",
+      "hint": "Los campos vacíos casan con todo. El host casa con el router de la alerta o con su MAC. El destino casa con cualquier valor de la alerta (puerto, dominio, MAC)."
+    },
     "configSaved": "Guardado",
     "configSaveError": "No se pudo guardar — inténtalo de nuevo",
     "categories": {

+ 27 - 0
app/public/locales/ru/translation.json

@@ -80,6 +80,33 @@
     "configButton": "Настроить оповещения",
     "configTitle": "Настройки оповещений",
     "configDescription": "Выберите, что записывать, а что присылать с уведомлением, по каждой категории. На \"Ничего\" категория исчезает из истории и из колокольчика.",
+    "exceptions": {
+      "title": "Исключения",
+      "description": "Отключает будущие оповещения, совпадающие по типу, хосту и цели. Уже показанные оповещения не удаляются.",
+      "empty": "Исключений пока нет.",
+      "anyType": "Любой тип",
+      "anyHost": "Любой хост",
+      "kind": "Тип оповещения",
+      "host": "Хост",
+      "hostPlaceholder": "ID роутера или MAC (пусто = любой)",
+      "target": "Цель",
+      "targetPlaceholder": "Порт, домен или MAC (пусто = любая)",
+      "comment": "Заметка",
+      "commentPlaceholder": "Зачем нужно это исключение",
+      "expires": "Истекает",
+      "expiresOn": "Истекает {{date}}",
+      "never": "Без срока",
+      "lastHit": "Последнее срабатывание {{date}}",
+      "hits": "Срабатываний: {{count}}",
+      "expired": "Истекло",
+      "add": "Добавить исключение",
+      "edit": "Изменить исключение",
+      "save": "Сохранить",
+      "delete": "Удалить исключение",
+      "saveError": "Не удалось сохранить исключение.",
+      "loadError": "Не удалось загрузить исключения.",
+      "hint": "Пустые поля совпадают со всем. Хост совпадает с роутером оповещения или его MAC. Цель совпадает с любым значением оповещения (порт, домен, MAC)."
+    },
     "configSaved": "Сохранено",
     "configSaveError": "Не удалось сохранить. Попробуйте ещё раз",
     "categories": {

+ 27 - 0
app/public/locales/zh/translation.json

@@ -1179,6 +1179,33 @@
     "configButton": "配置告警",
     "configTitle": "告警设置",
     "configDescription": "每个事件都会保留在你的历史中并计入铃铛。按类别选择通知你的内容。",
+    "exceptions": {
+      "title": "例外",
+      "description": "对符合类型、主机和目标的未来告警静音。已在列表中的告警不会被删除。",
+      "empty": "暂无例外。",
+      "anyType": "任意类型",
+      "anyHost": "任意主机",
+      "kind": "告警类型",
+      "host": "主机",
+      "hostPlaceholder": "路由器 ID 或 MAC(留空 = 任意)",
+      "target": "目标",
+      "targetPlaceholder": "端口、域名或 MAC(留空 = 任意)",
+      "comment": "备注",
+      "commentPlaceholder": "创建此例外的原因",
+      "expires": "到期",
+      "expiresOn": "{{date}} 到期",
+      "never": "永不过期",
+      "lastHit": "上次命中 {{date}}",
+      "hits": "命中 {{count}} 次",
+      "expired": "已过期",
+      "add": "添加例外",
+      "edit": "编辑例外",
+      "save": "保存",
+      "delete": "删除例外",
+      "saveError": "无法保存例外。",
+      "loadError": "无法加载例外。",
+      "hint": "留空的字段匹配任何内容。主机会匹配告警的路由器或其 MAC;目标会匹配告警中的任意值(端口、域名、MAC)。"
+    },
     "configSaved": "已保存",
     "configSaveError": "无法保存,请重试",
     "categories": {

+ 352 - 0
app/src/components/AlertExceptions.tsx

@@ -0,0 +1,352 @@
+import { useCallback, useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { motion } from 'framer-motion'
+import { Check, Pencil, Plus, ShieldOff, Trash2, X } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import {
+  Select,
+  SelectContent,
+  SelectItem,
+  SelectTrigger,
+  SelectValue,
+} from '@/components/ui/select'
+import { useNetPulse } from '@/data/DataProvider'
+import { cn } from '@/lib/utils'
+
+interface AlertException {
+  id: number
+  kind: string
+  host: string
+  target: string
+  comment: string
+  expiresAt: number
+  createdAt: number
+  hits: number
+  lastHit: number
+}
+
+interface Draft {
+  kind: string
+  host: string
+  target: string
+  comment: string
+  expires: string
+}
+
+const ANY = '__any__'
+const HOST_LIST_ID = 'alert-exception-hosts'
+
+const emptyDraft = (): Draft => ({ kind: '', host: '', target: '', comment: '', expires: '' })
+
+function dateValue(ms: number): string {
+  if (!ms) return ''
+  const d = new Date(ms)
+  const pad = (n: number) => String(n).padStart(2, '0')
+  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
+}
+
+function endOfDay(value: string): number {
+  if (!value) return 0
+  const [ys, ms, ds] = value.split('-')
+  const y = Number(ys) || 1970
+  const m = Number(ms) || 1
+  const d = Number(ds) || 1
+  return new Date(y, m - 1, d, 23, 59, 59).getTime()
+}
+
+export function AlertExceptions() {
+  const { t, i18n } = useTranslation()
+  const { routers, isDemo } = useNetPulse()
+  const [items, setItems] = useState<AlertException[]>([])
+  const [loading, setLoading] = useState(true)
+  const [error, setError] = useState('')
+  const [draft, setDraft] = useState<Draft | null>(null)
+  const [editId, setEditId] = useState<number | null>(null)
+  const [saving, setSaving] = useState(false)
+
+  const fetchItems = useCallback(async () => {
+    try {
+      const res = await fetch('/api/alerts/exceptions')
+      if (!res.ok) {
+        setError(t('alerts.exceptions.loadError'))
+        return
+      }
+      setItems(await res.json())
+      setError('')
+    } catch {
+      setError(t('alerts.exceptions.loadError'))
+    } finally {
+      setLoading(false)
+    }
+  }, [t])
+
+  useEffect(() => {
+    if (isDemo) {
+      setLoading(false)
+      return
+    }
+    void fetchItems()
+  }, [fetchItems, isDemo])
+
+  const rawTypes = t('alerts.types', { returnObjects: true })
+  const typeOptions =
+    rawTypes && typeof rawTypes === 'object'
+      ? Object.keys(rawTypes as Record<string, unknown>)
+          .map((slug) => ({ slug, label: t(`alerts.types.${slug}.title`) }))
+          .sort((a, b) => a.label.localeCompare(b.label))
+      : []
+
+  const startCreate = () => { setDraft(emptyDraft()); setEditId(null); setError('') }
+  const startEdit = (x: AlertException) => {
+    setDraft({ kind: x.kind, host: x.host, target: x.target, comment: x.comment, expires: dateValue(x.expiresAt) })
+    setEditId(x.id)
+    setError('')
+  }
+  const cancel = () => { setDraft(null); setEditId(null); setError('') }
+
+  const save = async () => {
+    if (!draft || saving) return
+    setSaving(true)
+    try {
+      const body = JSON.stringify({
+        kind: draft.kind,
+        host: draft.host.trim(),
+        target: draft.target.trim(),
+        comment: draft.comment.trim(),
+        expiresAt: endOfDay(draft.expires),
+      })
+      const res = await fetch(editId ? `/api/alerts/exceptions/${editId}` : '/api/alerts/exceptions', {
+        method: editId ? 'PUT' : 'POST',
+        headers: { 'Content-Type': 'application/json' },
+        body,
+      })
+      if (!res.ok) {
+        setError(t('alerts.exceptions.saveError'))
+        return
+      }
+      cancel()
+      await fetchItems()
+    } catch {
+      setError(t('alerts.exceptions.saveError'))
+    } finally {
+      setSaving(false)
+    }
+  }
+
+  const remove = async (id: number) => {
+    try {
+      const res = await fetch(`/api/alerts/exceptions/${id}`, { method: 'DELETE' })
+      if (!res.ok) {
+        setError(t('alerts.exceptions.saveError'))
+        return
+      }
+      await fetchItems()
+    } catch {
+      setError(t('alerts.exceptions.saveError'))
+    }
+  }
+
+  const extraKind = draft?.kind && !typeOptions.some((o) => o.slug === draft.kind) ? draft.kind : ''
+  const typeLabel = (kind: string) => (kind ? t(`alerts.types.${kind}.title`) : t('alerts.exceptions.anyType'))
+  const dateLabel = (ms: number) => new Date(ms).toLocaleDateString(i18n.language)
+  const lastHitLabel = (ms: number) => new Date(ms).toLocaleString(i18n.language)
+
+  // La demo pública no tiene backend de escritura: la sección no se muestra
+  // para no enseñar un error de carga.
+  if (isDemo) return null
+  if (loading) return <p className="text-caption text-text-muted">{t('common.loading')}</p>
+
+  return (
+    <div className="space-y-4">
+      <div className="flex items-center justify-between gap-3">
+        <div className="min-w-0">
+          <h3 className="text-sm font-semibold text-text-primary">{t('alerts.exceptions.title')}</h3>
+          <p className="mt-0.5 text-caption text-text-muted">{t('alerts.exceptions.description')}</p>
+        </div>
+        {!draft && (
+          <Button size="sm" variant="outline" onClick={startCreate} className="shrink-0 gap-1.5">
+            <Plus className="h-3.5 w-3.5" />
+            {t('alerts.exceptions.add')}
+          </Button>
+        )}
+      </div>
+
+      {error && <p className="text-caption text-danger" role="alert">{error}</p>}
+
+      {items.length === 0 && !draft && (
+        <p className="py-4 text-center text-caption text-text-muted">{t('alerts.exceptions.empty')}</p>
+      )}
+
+      {items.map((x) => {
+        const expired = x.expiresAt > 0 && x.expiresAt <= Date.now()
+        return (
+          <div
+            key={x.id}
+            className={cn(
+              'flex items-start gap-3 rounded-xl border border-border bg-elevated p-3',
+              expired && 'opacity-60',
+            )}
+          >
+            <span className={cn(
+              'flex h-9 w-9 shrink-0 items-center justify-center rounded-lg',
+              expired ? 'bg-danger/10 text-danger' : 'bg-accent/10 text-accent',
+            )}>
+              <ShieldOff className="h-4 w-4" strokeWidth={1.75} />
+            </span>
+            <div className="min-w-0 flex-1">
+              <div className="flex flex-wrap items-center gap-1.5">
+                <span className="text-sm font-medium text-text-primary">{typeLabel(x.kind)}</span>
+                <span className="rounded-md bg-surface px-1.5 py-0.5 text-[11px] text-text-muted">
+                  {x.host || t('alerts.exceptions.anyHost')}
+                </span>
+                {x.target && (
+                  <span className="rounded-md bg-surface px-1.5 py-0.5 text-[11px] text-text-muted">
+                    {x.target}
+                  </span>
+                )}
+                {expired && (
+                  <span className="rounded-md bg-danger/10 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-[0.05em] text-danger">
+                    {t('alerts.exceptions.expired')}
+                  </span>
+                )}
+              </div>
+              {x.comment && <p className="mt-0.5 truncate text-caption text-text-muted">{x.comment}</p>}
+              <p className="mt-1 text-caption text-text-muted">
+                {t('alerts.exceptions.hits', { count: x.hits })}
+                {' · '}
+                {x.expiresAt > 0
+                  ? t('alerts.exceptions.expiresOn', { date: dateLabel(x.expiresAt) })
+                  : t('alerts.exceptions.never')}
+                {x.lastHit > 0 && ` · ${t('alerts.exceptions.lastHit', { date: lastHitLabel(x.lastHit) })}`}
+              </p>
+            </div>
+            <Button
+              size="icon"
+              variant="ghost"
+              onClick={() => startEdit(x)}
+              aria-label={t('alerts.exceptions.edit')}
+              className="h-8 w-8 text-text-muted hover:text-accent"
+            >
+              <Pencil className="h-3.5 w-3.5" />
+            </Button>
+            <Button
+              size="icon"
+              variant="ghost"
+              onClick={() => void remove(x.id)}
+              aria-label={t('alerts.exceptions.delete')}
+              className="h-8 w-8 text-text-muted hover:text-danger"
+            >
+              <Trash2 className="h-3.5 w-3.5" />
+            </Button>
+          </div>
+        )
+      })}
+
+      {draft && (
+        <motion.div
+          initial={{ opacity: 0, y: -8 }}
+          animate={{ opacity: 1, y: 0 }}
+          className="rounded-xl border border-accent/30 bg-accent-soft/20 p-4"
+        >
+          <h4 className="mb-3 text-sm font-semibold text-text-primary">
+            {editId ? t('alerts.exceptions.edit') : t('alerts.exceptions.add')}
+          </h4>
+          <div className="grid gap-3 sm:grid-cols-2">
+            <div>
+              <label htmlFor="exception-kind" className="mb-1 block text-caption font-medium text-text-secondary">
+                {t('alerts.exceptions.kind')}
+              </label>
+              <Select
+                value={draft.kind || ANY}
+                onValueChange={(v) => setDraft({ ...draft, kind: v === ANY ? '' : v })}
+              >
+                <SelectTrigger id="exception-kind" size="sm" className="h-8">
+                  <SelectValue />
+                </SelectTrigger>
+                <SelectContent>
+                  <SelectItem value={ANY}>{t('alerts.exceptions.anyType')}</SelectItem>
+                  {extraKind && <SelectItem value={extraKind}>{extraKind}</SelectItem>}
+                  {typeOptions.map((o) => (
+                    <SelectItem key={o.slug} value={o.slug}>{o.label}</SelectItem>
+                  ))}
+                </SelectContent>
+              </Select>
+            </div>
+            <div>
+              <label htmlFor="exception-host" className="mb-1 block text-caption font-medium text-text-secondary">
+                {t('alerts.exceptions.host')}
+              </label>
+              <Input
+                id="exception-host"
+                list={HOST_LIST_ID}
+                value={draft.host}
+                onChange={(e) => setDraft({ ...draft, host: e.target.value })}
+                placeholder={t('alerts.exceptions.hostPlaceholder')}
+                className="h-8 text-sm"
+              />
+              <datalist id={HOST_LIST_ID}>
+                {routers.map((r) => (
+                  <option key={r.id} value={r.id}>{r.name}</option>
+                ))}
+              </datalist>
+            </div>
+            <div>
+              <label htmlFor="exception-target" className="mb-1 block text-caption font-medium text-text-secondary">
+                {t('alerts.exceptions.target')}
+              </label>
+              <Input
+                id="exception-target"
+                value={draft.target}
+                onChange={(e) => setDraft({ ...draft, target: e.target.value })}
+                placeholder={t('alerts.exceptions.targetPlaceholder')}
+                className="h-8 text-sm"
+              />
+            </div>
+            <div>
+              <label htmlFor="exception-expires" className="mb-1 block text-caption font-medium text-text-secondary">
+                {t('alerts.exceptions.expires')}
+              </label>
+              <Input
+                id="exception-expires"
+                type="date"
+                value={draft.expires}
+                onChange={(e) => setDraft({ ...draft, expires: e.target.value })}
+                className="h-8 text-sm"
+              />
+            </div>
+            <div className="sm:col-span-2">
+              <label htmlFor="exception-comment" className="mb-1 block text-caption font-medium text-text-secondary">
+                {t('alerts.exceptions.comment')}
+              </label>
+              <Input
+                id="exception-comment"
+                value={draft.comment}
+                onChange={(e) => setDraft({ ...draft, comment: e.target.value })}
+                placeholder={t('alerts.exceptions.commentPlaceholder')}
+                maxLength={280}
+                className="h-8 text-sm"
+              />
+            </div>
+          </div>
+          <p className="mt-2 text-caption text-text-muted">{t('alerts.exceptions.hint')}</p>
+          <div className="mt-4 flex justify-end gap-2">
+            <Button size="sm" variant="ghost" onClick={cancel} disabled={saving} className="gap-1.5">
+              <X className="h-3.5 w-3.5" />
+              {t('common.cancel')}
+            </Button>
+            <Button
+              size="sm"
+              onClick={() => void save()}
+              disabled={saving || (!draft.kind && !draft.host.trim() && !draft.target.trim())}
+              className="gap-1.5"
+            >
+              <Check className="h-3.5 w-3.5" />
+              {editId ? t('alerts.exceptions.save') : t('alerts.exceptions.add')}
+            </Button>
+          </div>
+        </motion.div>
+      )}
+    </div>
+  )
+}

+ 4 - 0
app/src/pages/Alerts.tsx

@@ -60,6 +60,7 @@ import type { FeedDay, FeedEvent, FeedSpark } from '@/data/alertFeed'
 import { useNetPulse } from '@/data/DataProvider'
 import { readUnreadOnly, writeUnreadOnly } from '@/lib/alertViewPrefs'
 import { RulesManager } from '@/components/RulesManager'
+import { AlertExceptions } from '@/components/AlertExceptions'
 import { cn } from '@/lib/utils'
 
 // ---------------------------------------------------------------------------
@@ -1102,6 +1103,9 @@ export default function Alerts() {
               <div className="mt-4 border-t border-border/60 pt-4">
                 <RulesManager />
               </div>
+              <div className="mt-4 border-t border-border/60 pt-4">
+                <AlertExceptions />
+              </div>
             </div>
           </motion.section>
         )}

+ 8 - 0
server-go/internal/alerts/alerts.go

@@ -588,6 +588,14 @@ func (e *Engine) insertaLocked(ev AlertEvent, now time.Time, skipDedup bool) boo
 		}
 		e.dedup[key] = now.UnixMilli()
 	}
+	// #2292: una excepción activa (tipo, host, destino) descarta la alerta y
+	// cuenta el impacto. Va después del dedup para que una condición
+	// persistente no sume un impacto por tick.
+	if e.db != nil && !ev.seeded {
+		if _, ok := MatchException(e.db, ev, now); ok {
+			return false
+		}
+	}
 	// #833: si el ID estaba limpiado y la condición se re-dispara, la alerta
 	// vuelve al feed (dismissed solo oculta el histórico, no el presente).
 	if _, was := e.dismissed[ev.ID]; was {

+ 229 - 0
server-go/internal/alerts/exceptions.go

@@ -0,0 +1,229 @@
+package alerts
+
+import (
+	"database/sql"
+	"errors"
+	"fmt"
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// Exception (#2292) descarta futuras alertas que casan por tipo, host y
+// destino. Los tres campos son opcionales, pero al menos uno debe estar
+// puesto: una excepción vacía silenciaría todo. ExpiresAt 0 = sin caducidad.
+// Epochs en milisegundos, como el resto de la BD.
+type Exception struct {
+	ID        int64  `json:"id"`
+	Kind      string `json:"kind"`
+	Host      string `json:"host"`
+	Target    string `json:"target"`
+	Comment   string `json:"comment"`
+	ExpiresAt int64  `json:"expiresAt"`
+	CreatedAt int64  `json:"createdAt"`
+	Hits      int64  `json:"hits"`
+	LastHit   int64  `json:"lastHit"`
+}
+
+// Expired indica si la excepción ya no aplica. Sin fecha (0) nunca caduca.
+func (x Exception) Expired(now time.Time) bool {
+	return x.ExpiresAt > 0 && x.ExpiresAt <= now.UnixMilli()
+}
+
+var (
+	ErrExceptionNotFound = errors.New("excepción no encontrada")
+	ErrExceptionInvalid  = errors.New("excepción inválida")
+)
+
+const (
+	exceptionKindMax    = 64
+	exceptionHostMax    = 128
+	exceptionTargetMax  = 128
+	exceptionCommentMax = 280
+)
+
+// ValidateException comprueba los límites y que la excepción no sea vacía.
+func ValidateException(x Exception) error {
+	x.Kind = strings.TrimSpace(x.Kind)
+	x.Host = strings.TrimSpace(x.Host)
+	x.Target = strings.TrimSpace(x.Target)
+	if x.Kind == "" && x.Host == "" && x.Target == "" {
+		return fmt.Errorf("%w: tipo, host o destino requerido", ErrExceptionInvalid)
+	}
+	if len(x.Kind) > exceptionKindMax || len(x.Host) > exceptionHostMax ||
+		len(x.Target) > exceptionTargetMax || len(x.Comment) > exceptionCommentMax {
+		return fmt.Errorf("%w: campo demasiado largo", ErrExceptionInvalid)
+	}
+	if x.ExpiresAt < 0 {
+		return fmt.Errorf("%w: caducidad inválida", ErrExceptionInvalid)
+	}
+	return nil
+}
+
+const exceptionColumns = "id, kind, host, target, comment, expires_at, created_at, hits, last_hit"
+
+func scanException(scan func(...any) error) (Exception, error) {
+	var x Exception
+	err := scan(&x.ID, &x.Kind, &x.Host, &x.Target, &x.Comment, &x.ExpiresAt, &x.CreatedAt, &x.Hits, &x.LastHit)
+	return x, err
+}
+
+// ListExceptions devuelve todas, activas y caducadas, las más nuevas primero.
+func ListExceptions(d *db.DB) ([]Exception, error) {
+	if d == nil {
+		return nil, nil
+	}
+	rows, err := d.Query("SELECT " + exceptionColumns + " FROM alert_exceptions ORDER BY id DESC")
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	out := []Exception{}
+	for rows.Next() {
+		x, err := scanException(rows.Scan)
+		if err != nil {
+			return nil, err
+		}
+		out = append(out, x)
+	}
+	return out, rows.Err()
+}
+
+// GetException carga una por id.
+func GetException(d *db.DB, id int64) (Exception, error) {
+	if d == nil {
+		return Exception{}, ErrExceptionNotFound
+	}
+	x, err := scanException(d.QueryRow("SELECT "+exceptionColumns+" FROM alert_exceptions WHERE id = ?", id).Scan)
+	if errors.Is(err, sql.ErrNoRows) {
+		return Exception{}, ErrExceptionNotFound
+	}
+	return x, err
+}
+
+// CreateException valida, inserta y devuelve la fila con su id.
+func CreateException(d *db.DB, in Exception) (Exception, error) {
+	in.Kind = strings.TrimSpace(in.Kind)
+	in.Host = strings.TrimSpace(in.Host)
+	in.Target = strings.TrimSpace(in.Target)
+	in.Comment = strings.TrimSpace(in.Comment)
+	if err := ValidateException(in); err != nil {
+		return Exception{}, err
+	}
+	in.CreatedAt = time.Now().UnixMilli()
+	res, err := d.Exec(
+		`INSERT INTO alert_exceptions (kind, host, target, comment, expires_at, created_at)
+		 VALUES (?, ?, ?, ?, ?, ?)`,
+		in.Kind, in.Host, in.Target, in.Comment, in.ExpiresAt, in.CreatedAt)
+	if err != nil {
+		return Exception{}, err
+	}
+	in.ID, _ = res.LastInsertId()
+	in.Hits = 0
+	in.LastHit = 0
+	return in, nil
+}
+
+// UpdateException cambia el ámbito y la caducidad. Los impactos se conservan.
+func UpdateException(d *db.DB, id int64, in Exception) (Exception, error) {
+	in.Kind = strings.TrimSpace(in.Kind)
+	in.Host = strings.TrimSpace(in.Host)
+	in.Target = strings.TrimSpace(in.Target)
+	in.Comment = strings.TrimSpace(in.Comment)
+	if err := ValidateException(in); err != nil {
+		return Exception{}, err
+	}
+	res, err := d.Exec(
+		`UPDATE alert_exceptions SET kind = ?, host = ?, target = ?, comment = ?, expires_at = ? WHERE id = ?`,
+		in.Kind, in.Host, in.Target, in.Comment, in.ExpiresAt, id)
+	if err != nil {
+		return Exception{}, err
+	}
+	if n, _ := res.RowsAffected(); n == 0 {
+		return Exception{}, ErrExceptionNotFound
+	}
+	return GetException(d, id)
+}
+
+// DeleteException borra una excepción.
+func DeleteException(d *db.DB, id int64) error {
+	res, err := d.Exec("DELETE FROM alert_exceptions WHERE id = ?", id)
+	if err != nil {
+		return err
+	}
+	if n, _ := res.RowsAffected(); n == 0 {
+		return ErrExceptionNotFound
+	}
+	return nil
+}
+
+// MatchException busca una excepción activa que case con el evento, suma un
+// impacto y la devuelve. El orden por id hace determinista el desempate.
+func MatchException(d *db.DB, ev AlertEvent, now time.Time) (Exception, bool) {
+	if d == nil {
+		return Exception{}, false
+	}
+	rows, err := d.Query(
+		"SELECT "+exceptionColumns+" FROM alert_exceptions WHERE expires_at = 0 OR expires_at > ? ORDER BY id",
+		now.UnixMilli())
+	if err != nil {
+		return Exception{}, false
+	}
+	// La BD abre UNA sola conexión (db.go: SetMaxOpenConns(1)): el UPDATE no
+	// puede ejecutarse con el iterador abierto o se queda esperando para
+	// siempre. Se cierra antes de escribir.
+	var match *Exception
+	for rows.Next() {
+		x, err := scanException(rows.Scan)
+		if err != nil {
+			break
+		}
+		if x.matches(ev) {
+			match = &x
+			break
+		}
+	}
+	_ = rows.Close()
+	if match == nil {
+		return Exception{}, false
+	}
+	match.Hits++
+	match.LastHit = now.UnixMilli()
+	_, _ = d.Exec("UPDATE alert_exceptions SET hits = hits + 1, last_hit = ? WHERE id = ?", match.LastHit, match.ID)
+	return *match, true
+}
+
+func (x Exception) matches(ev AlertEvent) bool {
+	if x.Kind != "" && !strings.EqualFold(x.Kind, ev.Type) {
+		return false
+	}
+	if x.Host != "" && !exceptionHostMatches(x.Host, ev) {
+		return false
+	}
+	if x.Target != "" && !exceptionTargetMatches(x.Target, ev) {
+		return false
+	}
+	return true
+}
+
+// exceptionHostMatches casa con el router del evento o con la MAC que lleve
+// en las variables (alertas de cliente).
+func exceptionHostMatches(host string, ev AlertEvent) bool {
+	if ev.RouterID != "" && strings.EqualFold(host, ev.RouterID) {
+		return true
+	}
+	mac := ev.Vars["mac"]
+	return mac != "" && strings.EqualFold(host, mac)
+}
+
+// exceptionTargetMatches casa con cualquier valor de las variables del
+// evento (puerto, dominio, MAC, nombre...). El destino vacío casa con todo.
+func exceptionTargetMatches(target string, ev AlertEvent) bool {
+	for _, v := range ev.Vars {
+		if strings.EqualFold(target, v) {
+			return true
+		}
+	}
+	return false
+}

+ 194 - 0
server-go/internal/alerts/exceptions_test.go

@@ -0,0 +1,194 @@
+package alerts
+
+import (
+	"errors"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+func openExceptionsDB(t *testing.T) *db.DB {
+	t.Helper()
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	return d
+}
+
+func TestExceptionCRUD(t *testing.T) {
+	d := openExceptionsDB(t)
+	expires := time.Now().Add(7 * 24 * time.Hour).UnixMilli()
+
+	x, err := CreateException(d, Exception{
+		Kind: "high-temperature", Host: "gw", Target: "70", Comment: "horno del salón", ExpiresAt: expires,
+	})
+	if err != nil {
+		t.Fatalf("create: %v", err)
+	}
+	if x.ID == 0 || x.CreatedAt == 0 {
+		t.Fatalf("id/created missing: %+v", x)
+	}
+
+	list, err := ListExceptions(d)
+	if err != nil || len(list) != 1 {
+		t.Fatalf("list: err=%v len=%d", err, len(list))
+	}
+
+	updated, err := UpdateException(d, x.ID, Exception{
+		Kind: "high-temperature", Host: "gw", Target: "", Comment: "ya no", ExpiresAt: 0,
+	})
+	if err != nil {
+		t.Fatalf("update: %v", err)
+	}
+	if updated.Comment != "ya no" || updated.Target != "" || updated.ExpiresAt != 0 {
+		t.Fatalf("update not applied: %+v", updated)
+	}
+
+	if err := DeleteException(d, x.ID); err != nil {
+		t.Fatalf("delete: %v", err)
+	}
+	list, _ = ListExceptions(d)
+	if len(list) != 0 {
+		t.Fatalf("expected 0 after delete, got %d", len(list))
+	}
+	if err := DeleteException(d, x.ID); !errors.Is(err, ErrExceptionNotFound) {
+		t.Fatalf("second delete: %v", err)
+	}
+}
+
+func TestExceptionValidation(t *testing.T) {
+	d := openExceptionsDB(t)
+	if _, err := CreateException(d, Exception{}); !errors.Is(err, ErrExceptionInvalid) {
+		t.Fatalf("empty exception must be invalid: %v", err)
+	}
+	if _, err := CreateException(d, Exception{Kind: strings.Repeat("x", exceptionKindMax+1)}); !errors.Is(err, ErrExceptionInvalid) {
+		t.Fatalf("long kind must be invalid: %v", err)
+	}
+	if _, err := CreateException(d, Exception{Kind: "x", ExpiresAt: -1}); !errors.Is(err, ErrExceptionInvalid) {
+		t.Fatalf("negative expiry must be invalid: %v", err)
+	}
+}
+
+func TestExceptionMatching(t *testing.T) {
+	d := openExceptionsDB(t)
+	now := time.Now()
+	event := AlertEvent{
+		Category: CatSystem, Type: "high-temperature", RouterID: "gw", Title: "hot",
+		Vars: map[string]string{"mac": "AA:BB:CC:DD:EE:FF", "port": "lan5"},
+	}
+
+	cases := []struct {
+		name string
+		x    Exception
+		want bool
+	}{
+		{"all three", Exception{Kind: "high-temperature", Host: "gw", Target: "lan5"}, true},
+		{"any kind on host", Exception{Host: "gw"}, true},
+		{"mac as host", Exception{Host: "aa:bb:cc:dd:ee:ff"}, true},
+		{"wrong kind", Exception{Kind: "link-down", Host: "gw"}, false},
+		{"wrong host", Exception{Kind: "high-temperature", Host: "ap1"}, false},
+		{"target in vars", Exception{Target: "LAN5"}, true},
+		{"target missing", Exception{Target: "lan9"}, false},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			x, err := CreateException(d, tc.x)
+			if err != nil {
+				t.Fatalf("create: %v", err)
+			}
+			_, ok := MatchException(d, event, now)
+			if ok != tc.want {
+				t.Fatalf("match = %v, want %v (exception %+v)", ok, tc.want, x)
+			}
+			_ = DeleteException(d, x.ID)
+		})
+	}
+}
+
+func TestExceptionExpiredDoesNotMatchAndCountsHits(t *testing.T) {
+	d := openExceptionsDB(t)
+	now := time.Now()
+	x, err := CreateException(d, Exception{Kind: "high-temperature", Host: "gw", ExpiresAt: now.Add(time.Hour).UnixMilli()})
+	if err != nil {
+		t.Fatalf("create: %v", err)
+	}
+	event := AlertEvent{Category: CatSystem, Type: "high-temperature", RouterID: "gw", Title: "hot"}
+
+	if _, ok := MatchException(d, event, now); !ok {
+		t.Fatal("active exception must match")
+	}
+	if _, ok := MatchException(d, event, now); !ok {
+		t.Fatal("second match must also match")
+	}
+	got, _ := GetException(d, x.ID)
+	if got.Hits != 2 || got.LastHit == 0 {
+		t.Fatalf("hits not counted: %+v", got)
+	}
+
+	if _, err := UpdateException(d, x.ID, Exception{Kind: "high-temperature", Host: "gw", ExpiresAt: now.Add(-time.Minute).UnixMilli()}); err != nil {
+		t.Fatalf("expire: %v", err)
+	}
+	expired, _ := GetException(d, x.ID)
+	if !expired.Expired(now) {
+		t.Fatalf("exception should be expired: %+v", expired)
+	}
+	if _, ok := MatchException(d, event, now); ok {
+		t.Fatal("expired exception must not match")
+	}
+}
+
+func TestEngineSuppressesMatchingException(t *testing.T) {
+	d := openExceptionsDB(t)
+	if _, err := CreateException(d, Exception{Kind: "high-temperature", Host: "gw"}); err != nil {
+		t.Fatalf("create: %v", err)
+	}
+	e := New(d, nil)
+
+	blocked := e.Emit(AlertEvent{
+		ID: "a1", Category: CatSystem, Severity: "warn", Type: "high-temperature",
+		RouterID: "gw", Title: "hot",
+	})
+	if blocked {
+		t.Fatal("matching alert must be suppressed")
+	}
+	if len(e.List()) != 0 {
+		t.Fatalf("feed should be empty, got %d", len(e.List()))
+	}
+	xs, _ := ListExceptions(d)
+	if len(xs) != 1 || xs[0].Hits != 1 {
+		t.Fatalf("hit not counted: %+v", xs)
+	}
+
+	allowed := e.Emit(AlertEvent{
+		ID: "a2", Category: CatSystem, Severity: "warn", Type: "link-down",
+		RouterID: "gw", Title: "link",
+	})
+	if !allowed || len(e.List()) != 1 {
+		t.Fatalf("non-matching alert must pass: ok=%v feed=%d", allowed, len(e.List()))
+	}
+}
+
+func TestExceptionSchemaRecreatedOnOldDatabase(t *testing.T) {
+	dir := t.TempDir()
+	d, err := db.Open(dir)
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	if _, err := d.Exec("DROP TABLE alert_exceptions"); err != nil {
+		t.Fatalf("drop: %v", err)
+	}
+	d.Close()
+
+	d2, err := db.Open(dir)
+	if err != nil {
+		t.Fatalf("reopen: %v", err)
+	}
+	defer d2.Close()
+	if _, err := CreateException(d2, Exception{Kind: "high-temperature"}); err != nil {
+		t.Fatalf("schema not recreated: %v", err)
+	}
+}

+ 15 - 0
server-go/internal/db/db.go

@@ -436,6 +436,21 @@ CREATE TABLE IF NOT EXISTS alert_log (
   resolves      TEXT NOT NULL DEFAULT ''
 );
 CREATE INDEX IF NOT EXISTS idx_alert_log_ts ON alert_log(ts DESC);
+-- Excepciones de alertas (#2292): descartan futuras alertas que casan por
+-- tipo, host y destino, con caducidad y contador de impactos. expires_at 0 =
+-- sin caducidad. Epochs en milisegundos, como el resto de la BD.
+CREATE TABLE IF NOT EXISTS alert_exceptions (
+  id         INTEGER PRIMARY KEY AUTOINCREMENT,
+  kind       TEXT NOT NULL DEFAULT '',
+  host       TEXT NOT NULL DEFAULT '',
+  target     TEXT NOT NULL DEFAULT '',
+  comment    TEXT NOT NULL DEFAULT '',
+  expires_at INTEGER NOT NULL DEFAULT 0,
+  created_at INTEGER NOT NULL,
+  hits       INTEGER NOT NULL DEFAULT 0,
+  last_hit   INTEGER NOT NULL DEFAULT 0
+);
+CREATE INDEX IF NOT EXISTS idx_alert_exceptions_exp ON alert_exceptions(expires_at);
 
 -- Rack canvas (fase 1): racks, montajes, cables y perfil físico por MAC.
 -- La identidad de dispositivo en NetPulse es la MAC (no hay tabla devices):

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

@@ -76,6 +76,9 @@ func TestRutasAdminDevuelven403ParaRolUser(t *testing.T) {
 		{"POST", "/api/alert-rules"},
 		{"PUT", "/api/alert-rules/1"},
 		{"DELETE", "/api/alert-rules/1"},
+		{"POST", "/api/alerts/exceptions"},
+		{"PUT", "/api/alerts/exceptions/1"},
+		{"DELETE", "/api/alerts/exceptions/1"},
 		{"POST", "/api/usteer/aa:bb:cc:dd:ee:ff/kick"},
 	}
 	for _, rt := range adminOnly {
@@ -94,6 +97,7 @@ func TestRutasAdminDevuelven403ParaRolUser(t *testing.T) {
 		"/api/alerts/silenced",
 		"/api/alerts/impostor-approved",
 		"/api/alerts/impostor-rule",
+		"/api/alerts/exceptions",
 		"/api/alert-rules",
 	}
 	for _, p := range readable {

+ 104 - 0
server-go/internal/httpapi/alert_exceptions_api.go

@@ -0,0 +1,104 @@
+// alert_exceptions_api.go — CRUD de excepciones de alertas (#2292).
+// GET es de lectura para cualquier sesión; las mutaciones son de admin.
+package httpapi
+
+import (
+	"errors"
+	"net/http"
+	"strconv"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+type alertExceptionBody struct {
+	Kind      string `json:"kind"`
+	Host      string `json:"host"`
+	Target    string `json:"target"`
+	Comment   string `json:"comment"`
+	ExpiresAt int64  `json:"expiresAt"` // ms; 0 = sin caducidad
+}
+
+func (b alertExceptionBody) toException() alerts.Exception {
+	return alerts.Exception{
+		Kind:      b.Kind,
+		Host:      b.Host,
+		Target:    b.Target,
+		Comment:   b.Comment,
+		ExpiresAt: b.ExpiresAt,
+	}
+}
+
+func (s *server) handleAlertExceptionsList(w http.ResponseWriter, _ *http.Request) {
+	xs, err := alerts.ListExceptions(s.db)
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
+		return
+	}
+	writeJSON(w, http.StatusOK, xs)
+}
+
+func (s *server) handleAlertExceptionsCreate(w http.ResponseWriter, r *http.Request) {
+	var body alertExceptionBody
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	if body.ExpiresAt > 0 && body.ExpiresAt <= time.Now().UnixMilli() {
+		writeError(w, http.StatusBadRequest, "invalid_expires", "la caducidad debe ser futura")
+		return
+	}
+	x, err := alerts.CreateException(s.db, body.toException())
+	if err != nil {
+		if errors.Is(err, alerts.ErrExceptionInvalid) {
+			writeError(w, http.StatusBadRequest, "invalid_exception", err.Error())
+			return
+		}
+		writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
+		return
+	}
+	writeJSON(w, http.StatusCreated, x)
+}
+
+func (s *server) handleAlertExceptionsUpdate(w http.ResponseWriter, r *http.Request) {
+	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
+	if err != nil || id <= 0 {
+		writeError(w, http.StatusBadRequest, "invalid_id", "id inválido")
+		return
+	}
+	var body alertExceptionBody
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	x, err := alerts.UpdateException(s.db, id, body.toException())
+	if err != nil {
+		switch {
+		case errors.Is(err, alerts.ErrExceptionNotFound):
+			writeError(w, http.StatusNotFound, "not_found", err.Error())
+		case errors.Is(err, alerts.ErrExceptionInvalid):
+			writeError(w, http.StatusBadRequest, "invalid_exception", err.Error())
+		default:
+			writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
+		}
+		return
+	}
+	writeJSON(w, http.StatusOK, x)
+}
+
+func (s *server) handleAlertExceptionsDelete(w http.ResponseWriter, r *http.Request) {
+	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
+	if err != nil || id <= 0 {
+		writeError(w, http.StatusBadRequest, "invalid_id", "id inválido")
+		return
+	}
+	if err := alerts.DeleteException(s.db, id); err != nil {
+		if errors.Is(err, alerts.ErrExceptionNotFound) {
+			writeError(w, http.StatusNotFound, "not_found", err.Error())
+			return
+		}
+		writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}

+ 77 - 0
server-go/internal/httpapi/alert_exceptions_api_test.go

@@ -0,0 +1,77 @@
+package httpapi_test
+
+import (
+	"fmt"
+	"net/http"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+func TestAlertExceptionsAPI(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	res := get(t, ts.URL, "/api/alerts/exceptions", cookie)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("list empty: %d", res.StatusCode)
+	}
+	res.Body.Close()
+
+	expires := time.Now().Add(24 * time.Hour).UnixMilli()
+	body := fmt.Sprintf(`{"kind":"high-temperature","host":"gw","target":"lan5","comment":"known","expiresAt":%d}`, expires)
+	res = doJSON(t, "POST", ts.URL, "/api/alerts/exceptions", cookie, body)
+	if res.StatusCode != http.StatusCreated {
+		t.Fatalf("create: %d", res.StatusCode)
+	}
+	res.Body.Close()
+
+	xs, err := alerts.ListExceptions(ts.db)
+	if err != nil || len(xs) != 1 {
+		t.Fatalf("list after create: err=%v len=%d", err, len(xs))
+	}
+	id := xs[0].ID
+
+	body = fmt.Sprintf(`{"kind":"high-temperature","host":"gw","target":"","comment":"updated","expiresAt":%d}`, expires)
+	res = doJSON(t, "PUT", ts.URL, fmt.Sprintf("/api/alerts/exceptions/%d", id), cookie, body)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("update: %d", res.StatusCode)
+	}
+	res.Body.Close()
+
+	got, _ := alerts.GetException(ts.db, id)
+	if got.Comment != "updated" || got.Target != "" {
+		t.Fatalf("update not applied: %+v", got)
+	}
+
+	res = doJSON(t, "POST", ts.URL, "/api/alerts/exceptions", cookie, `{"kind":"","host":"","target":"","comment":""}`)
+	if res.StatusCode != http.StatusBadRequest {
+		t.Fatalf("empty exception must be 400, got %d", res.StatusCode)
+	}
+	res.Body.Close()
+
+	past := time.Now().Add(-time.Hour).UnixMilli()
+	res = doJSON(t, "POST", ts.URL, "/api/alerts/exceptions", cookie, fmt.Sprintf(`{"kind":"x","expiresAt":%d}`, past))
+	if res.StatusCode != http.StatusBadRequest {
+		t.Fatalf("past expiry must be 400, got %d", res.StatusCode)
+	}
+	res.Body.Close()
+
+	res = doJSON(t, "DELETE", ts.URL, fmt.Sprintf("/api/alerts/exceptions/%d", id), cookie, "")
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("delete: %d", res.StatusCode)
+	}
+	res.Body.Close()
+
+	xs, _ = alerts.ListExceptions(ts.db)
+	if len(xs) != 0 {
+		t.Fatalf("expected 0 after delete, got %d", len(xs))
+	}
+
+	res = doJSON(t, "DELETE", ts.URL, fmt.Sprintf("/api/alerts/exceptions/%d", id), cookie, "")
+	if res.StatusCode != http.StatusNotFound {
+		t.Fatalf("second delete must be 404, got %d", res.StatusCode)
+	}
+	res.Body.Close()
+}

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

@@ -487,6 +487,11 @@ func NewHandler(d Deps) http.Handler {
 	mux.Handle("POST /api/alert-rules", auth.RequireAdmin(http.HandlerFunc(s.handleAlertRulesCreate)))
 	mux.Handle("PUT /api/alert-rules/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleAlertRulesUpdate)))
 	mux.Handle("DELETE /api/alert-rules/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleAlertRulesDelete)))
+	// #2292: excepciones por tipo/host/destino con caducidad e impactos.
+	mux.HandleFunc("GET /api/alerts/exceptions", s.handleAlertExceptionsList)
+	mux.Handle("POST /api/alerts/exceptions", auth.RequireAdmin(http.HandlerFunc(s.handleAlertExceptionsCreate)))
+	mux.Handle("PUT /api/alerts/exceptions/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleAlertExceptionsUpdate)))
+	mux.Handle("DELETE /api/alerts/exceptions/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleAlertExceptionsDelete)))
 	mux.HandleFunc("GET /api/baselines", s.handleBaselines)
 	mux.HandleFunc("GET /api/internet-health", s.handleInternetHealth)
 	mux.HandleFunc("GET /api/presence", s.handlePresenceStatus)