4
0
Эх сурвалжийг харах

feat(alerts): custom alert rules with threshold, duration and scope (#331) (#352)

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 сар өмнө
parent
commit
4082f9dc83

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

@@ -1398,5 +1398,42 @@
     "ms": "ms",
     "noData": "No data",
     "caption": "TCP probes every 5s from the collector daemon"
+  },
+  "alertRules": {
+    "title": "Custom rules",
+    "description": "Create rules with threshold, duration and scope to generate automatic alerts.",
+    "empty": "No custom rules yet. Create one to get started.",
+    "create": "New rule",
+    "edit": "Edit rule",
+    "update": "Save",
+    "name": "Name",
+    "namePlaceholder": "e.g. High CPU on patio",
+    "category": "Category",
+    "metric": "Metric",
+    "operator": "Condition",
+    "threshold": "Threshold",
+    "duration": "Duration",
+    "severity": "Severity",
+    "scope": "Scope",
+    "scopeGlobal": "All routers",
+    "scopeRouter": "Specific routers",
+    "duration1m": "1 minute",
+    "duration5m": "5 minutes",
+    "duration10m": "10 minutes",
+    "duration30m": "30 minutes",
+    "duration1h": "1 hour",
+    "metrics": {
+      "cpu": "CPU (%)",
+      "ram": "RAM (%)",
+      "temp": "Temperature (°C)",
+      "latency_ms": "Latency (ms)",
+      "rx_bps": "Download (bps)",
+      "tx_bps": "Upload (bps)"
+    },
+    "sev": {
+      "info": "Info",
+      "warn": "Warning",
+      "critical": "Critical"
+    }
   }
 }

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

@@ -1398,5 +1398,42 @@
     "ms": "ms",
     "noData": "Sin datos",
     "caption": "Sondas TCP cada 5s desde el daemon collector"
+  },
+  "alertRules": {
+    "title": "Reglas personalizadas",
+    "description": "Crea reglas con umbral, duración y alcance para generar alertas automáticas.",
+    "empty": "Sin reglas personalizadas. Crea una para empezar.",
+    "create": "Nueva regla",
+    "edit": "Editar regla",
+    "update": "Guardar",
+    "name": "Nombre",
+    "namePlaceholder": "p.ej. CPU alto en patio",
+    "category": "Categoría",
+    "metric": "Métrica",
+    "operator": "Condición",
+    "threshold": "Umbral",
+    "duration": "Duración",
+    "severity": "Severidad",
+    "scope": "Alcance",
+    "scopeGlobal": "Todos los routers",
+    "scopeRouter": "Routers específicos",
+    "duration1m": "1 minuto",
+    "duration5m": "5 minutos",
+    "duration10m": "10 minutos",
+    "duration30m": "30 minutos",
+    "duration1h": "1 hora",
+    "metrics": {
+      "cpu": "CPU (%)",
+      "ram": "RAM (%)",
+      "temp": "Temperatura (°C)",
+      "latency_ms": "Latencia (ms)",
+      "rx_bps": "Descarga (bps)",
+      "tx_bps": "Subida (bps)"
+    },
+    "sev": {
+      "info": "Info",
+      "warn": "Aviso",
+      "critical": "Crítico"
+    }
   }
 }

+ 339 - 0
app/src/components/RulesManager.tsx

@@ -0,0 +1,339 @@
+import { useCallback, useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { motion } from 'framer-motion'
+import {
+  AlertTriangle,
+  Check,
+  Globe,
+  Info,
+  OctagonX,
+  Plus,
+  Router,
+  Server,
+  Shield,
+  Signal,
+  Trash2,
+  Users,
+} from 'lucide-react'
+import type { LucideIcon } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Switch } from '@/components/ui/switch'
+import {
+  Select,
+  SelectContent,
+  SelectItem,
+  SelectTrigger,
+  SelectValue,
+} from '@/components/ui/select'
+import { cn } from '@/lib/utils'
+
+interface AlertRule {
+  id: string
+  name: string
+  category: string
+  enabled: boolean
+  condition: {
+    metric: string
+    operator: string
+    threshold: number
+    duration: number
+  }
+  scope: {
+    type: 'global' | 'router'
+    routerIds?: string[]
+  }
+  severity: 'info' | 'warn' | 'critical'
+}
+
+const CAT_ICONS: Record<string, { icon: LucideIcon; color: string }> = {
+  router: { icon: Router, color: 'text-warn' },
+  internet: { icon: Globe, color: 'text-info' },
+  clients: { icon: Users, color: 'text-accent' },
+  signal: { icon: Signal, color: 'text-tunnel' },
+  vpn: { icon: Shield, color: 'text-tunnel' },
+  system: { icon: Server, color: 'text-ok' },
+}
+
+const SEV_COLORS: Record<string, string> = {
+  info: 'bg-info/10 text-info',
+  warn: 'bg-warn/10 text-warn',
+  critical: 'bg-danger/10 text-danger',
+}
+
+const METRICS = [
+  'cpu', 'ram', 'temp', 'latency_ms', 'rx_bps', 'tx_bps',
+] as const
+
+const OPERATORS = [
+  { value: 'gt', label: '>' },
+  { value: 'gte', label: '>=' },
+  { value: 'lt', label: '<' },
+  { value: 'lte', label: '<=' },
+  { value: 'eq', label: '=' },
+] as const
+
+const DURATIONS = [
+  { value: 60_000_000_000, labelKey: 'alertRules.duration1m' },
+  { value: 300_000_000_000, labelKey: 'alertRules.duration5m' },
+  { value: 600_000_000_000, labelKey: 'alertRules.duration10m' },
+  { value: 1_800_000_000_000, labelKey: 'alertRules.duration30m' },
+  { value: 3_600_000_000_000, labelKey: 'alertRules.duration1h' },
+] as const
+
+const CATEGORIES = ['router', 'internet', 'clients', 'signal', 'vpn', 'system'] as const
+const SEVERITIES = ['info', 'warn', 'critical'] as const
+
+function emptyRule(): Omit<AlertRule, 'id' | 'createdAt' | 'updatedAt'> {
+  return {
+    name: '',
+    category: 'router',
+    enabled: true,
+    condition: { metric: 'cpu', operator: 'gt', threshold: 90, duration: 600_000_000_000 },
+    scope: { type: 'global' },
+    severity: 'warn',
+  }
+}
+
+export function RulesManager() {
+  const { t } = useTranslation()
+  const [rules, setRules] = useState<AlertRule[]>([])
+  const [loading, setLoading] = useState(true)
+  const [editing, setEditing] = useState<Omit<AlertRule, 'id' | 'createdAt' | 'updatedAt'> | null>(null)
+  const [editId, setEditId] = useState<string | null>(null)
+
+  const fetchRules = useCallback(async () => {
+    try {
+      const res = await fetch('/api/alert-rules')
+      if (res.ok) setRules(await res.json())
+    } finally {
+      setLoading(false)
+    }
+  }, [])
+
+  useEffect(() => { void fetchRules() }, [fetchRules])
+
+  const saveRule = async () => {
+    if (!editing) return
+    const body = JSON.stringify(editing)
+    if (editId) {
+      await fetch(`/api/alert-rules/${editId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body })
+    } else {
+      await fetch('/api/alert-rules', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body })
+    }
+    setEditing(null)
+    setEditId(null)
+    await fetchRules()
+  }
+
+  const deleteRule = async (id: string) => {
+    await fetch(`/api/alert-rules/${id}`, { method: 'DELETE' })
+    await fetchRules()
+  }
+
+  const toggleRule = async (rule: AlertRule) => {
+    await fetch(`/api/alert-rules/${rule.id}`, {
+      method: 'PUT',
+      headers: { 'Content-Type': 'application/json' },
+      body: JSON.stringify({ ...rule, enabled: !rule.enabled }),
+    })
+    await fetchRules()
+  }
+
+  const startEdit = (rule: AlertRule) => {
+    setEditing({ name: rule.name, category: rule.category, enabled: rule.enabled, condition: rule.condition, scope: rule.scope, severity: rule.severity })
+    setEditId(rule.id)
+  }
+
+  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">
+        <div>
+          <h3 className="text-sm font-semibold text-text-primary">{t('alertRules.title')}</h3>
+          <p className="mt-0.5 text-caption text-text-muted">{t('alertRules.description')}</p>
+        </div>
+        {!editing && (
+          <Button
+            size="sm"
+            variant="outline"
+            onClick={() => { setEditing(emptyRule()); setEditId(null) }}
+            className="gap-1.5"
+          >
+            <Plus className="h-3.5 w-3.5" />
+            {t('alertRules.create')}
+          </Button>
+        )}
+      </div>
+
+      {rules.length === 0 && !editing && (
+        <p className="py-4 text-center text-caption text-text-muted">{t('alertRules.empty')}</p>
+      )}
+
+      {rules.map((rule) => {
+        const meta = CAT_ICONS[rule.category] ?? { icon: Info, color: 'text-text-muted' }
+        const CatIcon = meta.icon
+        return (
+          <div key={rule.id} className="flex items-center gap-3 rounded-xl border border-border bg-elevated p-3">
+            <span className={cn('flex h-9 w-9 shrink-0 items-center justify-center rounded-lg', SEV_COLORS[rule.severity])}>
+              <CatIcon className="h-4 w-4" strokeWidth={1.75} />
+            </span>
+            <div className="min-w-0 flex-1">
+              <div className="flex items-center gap-2">
+                <span className="truncate text-sm font-medium text-text-primary">{rule.name}</span>
+                <span className={cn('rounded-md px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-[0.05em]', SEV_COLORS[rule.severity])}>
+                  {rule.severity}
+                </span>
+              </div>
+              <p className="mt-0.5 truncate text-caption text-text-muted">
+                {rule.condition.metric} {OPERATORS.find(o => o.value === rule.condition.operator)?.label} {rule.condition.threshold}
+                {' / '}
+                {rule.condition.duration / 1_000_000_000}s
+                {' / '}
+                {rule.scope.type === 'global' ? t('alertRules.scopeGlobal') : t('alertRules.scopeRouter')}
+              </p>
+            </div>
+            <Switch checked={rule.enabled} onCheckedChange={() => toggleRule(rule)} />
+            <Button size="icon" variant="ghost" onClick={() => startEdit(rule)} className="h-8 w-8 text-text-muted hover:text-accent">
+              <Info className="h-3.5 w-3.5" />
+            </Button>
+            <Button size="icon" variant="ghost" onClick={() => deleteRule(rule.id)} className="h-8 w-8 text-text-muted hover:text-danger">
+              <Trash2 className="h-3.5 w-3.5" />
+            </Button>
+          </div>
+        )
+      })}
+
+      {editing && (
+        <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('alertRules.edit') : t('alertRules.create')}
+          </h4>
+          <div className="grid gap-3 sm:grid-cols-2">
+            <div>
+              <label className="mb-1 block text-caption font-medium text-text-secondary">{t('alertRules.name')}</label>
+              <Input
+                value={editing.name}
+                onChange={(e) => setEditing({ ...editing, name: e.target.value })}
+                placeholder={t('alertRules.namePlaceholder')}
+                className="h-8 text-sm"
+              />
+            </div>
+            <div>
+              <label className="mb-1 block text-caption font-medium text-text-secondary">{t('alertRules.category')}</label>
+              <Select value={editing.category} onValueChange={(v) => setEditing({ ...editing, category: v })}>
+                <SelectTrigger size="sm" className="h-8">
+                  <SelectValue />
+                </SelectTrigger>
+                <SelectContent>
+                  {CATEGORIES.map((c) => (
+                    <SelectItem key={c} value={c}>{t(`alerts.categories.${c}`)}</SelectItem>
+                  ))}
+                </SelectContent>
+              </Select>
+            </div>
+            <div>
+              <label className="mb-1 block text-caption font-medium text-text-secondary">{t('alertRules.metric')}</label>
+              <Select value={editing.condition.metric} onValueChange={(v) => setEditing({ ...editing, condition: { ...editing.condition, metric: v } })}>
+                <SelectTrigger size="sm" className="h-8">
+                  <SelectValue />
+                </SelectTrigger>
+                <SelectContent>
+                  {METRICS.map((m) => (
+                    <SelectItem key={m} value={m}>{t(`alertRules.metrics.${m}`)}</SelectItem>
+                  ))}
+                </SelectContent>
+              </Select>
+            </div>
+            <div className="flex gap-2">
+              <div className="flex-1">
+                <label className="mb-1 block text-caption font-medium text-text-secondary">{t('alertRules.operator')}</label>
+                <Select value={editing.condition.operator} onValueChange={(v) => setEditing({ ...editing, condition: { ...editing.condition, operator: v } })}>
+                  <SelectTrigger size="sm" className="h-8">
+                    <SelectValue />
+                  </SelectTrigger>
+                  <SelectContent>
+                    {OPERATORS.map((o) => (
+                      <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
+                    ))}
+                  </SelectContent>
+                </Select>
+              </div>
+              <div className="flex-1">
+                <label className="mb-1 block text-caption font-medium text-text-secondary">{t('alertRules.threshold')}</label>
+                <Input
+                  type="number"
+                  value={editing.condition.threshold}
+                  onChange={(e) => setEditing({ ...editing, condition: { ...editing.condition, threshold: Number(e.target.value) } })}
+                  className="h-8 text-sm"
+                />
+              </div>
+            </div>
+            <div>
+              <label className="mb-1 block text-caption font-medium text-text-secondary">{t('alertRules.duration')}</label>
+              <Select
+                value={String(editing.condition.duration)}
+                onValueChange={(v) => setEditing({ ...editing, condition: { ...editing.condition, duration: Number(v) } })}
+              >
+                <SelectTrigger size="sm" className="h-8">
+                  <SelectValue />
+                </SelectTrigger>
+                <SelectContent>
+                  {DURATIONS.map((d) => (
+                    <SelectItem key={d.value} value={String(d.value)}>{t(d.labelKey)}</SelectItem>
+                  ))}
+                </SelectContent>
+              </Select>
+            </div>
+            <div>
+              <label className="mb-1 block text-caption font-medium text-text-secondary">{t('alertRules.severity')}</label>
+              <Select value={editing.severity} onValueChange={(v) => setEditing({ ...editing, severity: v })}>
+                <SelectTrigger size="sm" className="h-8">
+                  <SelectValue />
+                </SelectTrigger>
+                <SelectContent>
+                  {SEVERITIES.map((s) => (
+                    <SelectItem key={s} value={s}>{t(`alertRules.sev.${s}`)}</SelectItem>
+                  ))}
+                </SelectContent>
+              </Select>
+            </div>
+            <div>
+              <label className="mb-1 block text-caption font-medium text-text-secondary">{t('alertRules.scope')}</label>
+              <Select
+                value={editing.scope.type}
+                onValueChange={(v) => setEditing({ ...editing, scope: { type: v as 'global' | 'router', routerIds: editing.scope.routerIds } })}
+              >
+                <SelectTrigger size="sm" className="h-8">
+                  <SelectValue />
+                </SelectTrigger>
+                <SelectContent>
+                  <SelectItem value="global">{t('alertRules.scopeGlobal')}</SelectItem>
+                  <SelectItem value="router">{t('alertRules.scopeRouter')}</SelectItem>
+                </SelectContent>
+              </Select>
+            </div>
+          </div>
+          <div className="mt-4 flex justify-end gap-2">
+            <Button
+              size="sm"
+              variant="ghost"
+              onClick={() => { setEditing(null); setEditId(null) }}
+            >
+              {t('common.cancel')}
+            </Button>
+            <Button size="sm" onClick={saveRule} disabled={!editing.name} className="gap-1.5">
+              <Check className="h-3.5 w-3.5" />
+              {editId ? t('alertRules.update') : t('alertRules.create')}
+            </Button>
+          </div>
+        </motion.div>
+      )}
+    </div>
+  )
+}

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

@@ -47,6 +47,7 @@ import {
 import { buildAlertFeed, buildLiveFeed, DAY_ORDER, KIND_LABELS } from '@/data/alertFeed'
 import type { AlertKind, FeedDay, FeedEvent, FeedSpark } from '@/data/alertFeed'
 import { useNetPulse } from '@/data/DataProvider'
+import { RulesManager } from '@/components/RulesManager'
 import { cn } from '@/lib/utils'
 
 // ---------------------------------------------------------------------------
@@ -708,6 +709,9 @@ export default function Alerts() {
                   )
                 })}
               </ul>
+              <div className="mt-4 border-t border-border/60 pt-4">
+                <RulesManager />
+              </div>
             </div>
           </motion.section>
         )}

+ 115 - 0
server-go/internal/alerts/rules.go

@@ -0,0 +1,115 @@
+package alerts
+
+import (
+	"encoding/json"
+	"fmt"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+const rulesKey = "alert-rules.v1"
+
+type RuleCondition struct {
+	Metric    string        `json:"metric"`
+	Operator  string        `json:"operator"`
+	Threshold float64       `json:"threshold"`
+	Duration  time.Duration `json:"duration"`
+}
+
+type RuleScope struct {
+	Type      string   `json:"type"`
+	RouterIDs []string `json:"routerIds,omitempty"`
+}
+
+type Rule struct {
+	ID        string        `json:"id"`
+	Name      string        `json:"name"`
+	Category  string        `json:"category"`
+	Enabled   bool          `json:"enabled"`
+	Condition RuleCondition `json:"condition"`
+	Scope     RuleScope     `json:"scope"`
+	Severity  string        `json:"severity"`
+	CreatedAt time.Time     `json:"createdAt"`
+	UpdatedAt time.Time     `json:"updatedAt"`
+}
+
+func ListRules(d *db.DB) ([]Rule, error) {
+	var raw string
+	if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", rulesKey).Scan(&raw); err != nil {
+		return []Rule{}, nil
+	}
+	var rules []Rule
+	if err := json.Unmarshal([]byte(raw), &rules); err != nil {
+		return nil, fmt.Errorf("unmarshal rules: %w", err)
+	}
+	return rules, nil
+}
+
+func GetRule(d *db.DB, id string) (*Rule, error) {
+	rules, err := ListRules(d)
+	if err != nil {
+		return nil, err
+	}
+	for _, r := range rules {
+		if r.ID == id {
+			return &r, nil
+		}
+	}
+	return nil, fmt.Errorf("regla %s no encontrada", id)
+}
+
+func SaveRules(d *db.DB, rules []Rule) error {
+	data, err := json.Marshal(rules)
+	if err != nil {
+		return fmt.Errorf("marshal rules: %w", err)
+	}
+	_, err = d.Exec(
+		"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
+		rulesKey, string(data))
+	return err
+}
+
+func CreateRule(d *db.DB, r Rule) error {
+	rules, err := ListRules(d)
+	if err != nil {
+		return err
+	}
+	if r.ID == "" {
+		r.ID = fmt.Sprintf("rule-%d", time.Now().UnixNano())
+	}
+	r.CreatedAt = time.Now()
+	r.UpdatedAt = r.CreatedAt
+	rules = append([]Rule{r}, rules...)
+	return SaveRules(d, rules)
+}
+
+func UpdateRule(d *db.DB, r Rule) error {
+	rules, err := ListRules(d)
+	if err != nil {
+		return err
+	}
+	for i, existing := range rules {
+		if existing.ID == r.ID {
+			r.CreatedAt = existing.CreatedAt
+			r.UpdatedAt = time.Now()
+			rules[i] = r
+			return SaveRules(d, rules)
+		}
+	}
+	return fmt.Errorf("regla %s no encontrada", r.ID)
+}
+
+func DeleteRule(d *db.DB, id string) error {
+	rules, err := ListRules(d)
+	if err != nil {
+		return err
+	}
+	for i, r := range rules {
+		if r.ID == id {
+			rules = append(rules[:i], rules[i+1:]...)
+			return SaveRules(d, rules)
+		}
+	}
+	return fmt.Errorf("regla %s no encontrada", id)
+}

+ 162 - 0
server-go/internal/alerts/rules_test.go

@@ -0,0 +1,162 @@
+package alerts
+
+import (
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+func TestRulesCRUD(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	rules, err := ListRules(d)
+	if err != nil {
+		t.Fatalf("list empty: %v", err)
+	}
+	if len(rules) != 0 {
+		t.Fatalf("expected 0 rules, got %d", len(rules))
+	}
+
+	r := Rule{
+		Name:     "CPU alto",
+		Category: CatRouter,
+		Enabled:  true,
+		Condition: RuleCondition{
+			Metric:    "cpu",
+			Operator:  "gt",
+			Threshold: 90,
+			Duration:  10 * time.Minute,
+		},
+		Scope:    RuleScope{Type: "global"},
+		Severity: "warn",
+	}
+	if err := CreateRule(d, r); err != nil {
+		t.Fatalf("create: %v", err)
+	}
+
+	rules, err = ListRules(d)
+	if err != nil {
+		t.Fatalf("list: %v", err)
+	}
+	if len(rules) != 1 {
+		t.Fatalf("expected 1 rule, got %d", len(rules))
+	}
+	if rules[0].Name != "CPU alto" || rules[0].ID == "" {
+		t.Fatalf("unexpected rule: %+v", rules[0])
+	}
+	if rules[0].CreatedAt.IsZero() || rules[0].UpdatedAt.IsZero() {
+		t.Fatalf("timestamps not set: %+v", rules[0])
+	}
+
+	rules[0].Enabled = false
+	if err := UpdateRule(d, rules[0]); err != nil {
+		t.Fatalf("update: %v", err)
+	}
+	got, err := GetRule(d, rules[0].ID)
+	if err != nil {
+		t.Fatalf("get: %v", err)
+	}
+	if got.Enabled {
+		t.Fatal("expected disabled after update")
+	}
+
+	if err := DeleteRule(d, rules[0].ID); err != nil {
+		t.Fatalf("delete: %v", err)
+	}
+	rules, _ = ListRules(d)
+	if len(rules) != 0 {
+		t.Fatalf("expected 0 rules after delete, got %d", len(rules))
+	}
+}
+
+func TestRulesPersistence(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	r := Rule{
+		Name:     "Latencia alta",
+		Category: CatInternet,
+		Enabled:  true,
+		Condition: RuleCondition{
+			Metric:    "latency_ms",
+			Operator:  "gt",
+			Threshold: 200,
+			Duration:  5 * time.Minute,
+		},
+		Scope:    RuleScope{Type: "global"},
+		Severity: "critical",
+	}
+	if err := CreateRule(d, r); err != nil {
+		t.Fatalf("create: %v", err)
+	}
+
+	rules, err := ListRules(d)
+	if err != nil {
+		t.Fatalf("list: %v", err)
+	}
+	if len(rules) != 1 {
+		t.Fatalf("expected 1 rule, got %d", len(rules))
+	}
+	if rules[0].Name != "Latencia alta" {
+		t.Fatalf("unexpected: %+v", rules[0])
+	}
+}
+
+func TestRuleNotFound(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	if _, err := GetRule(d, "no-existe"); err == nil {
+		t.Fatal("expected error for missing rule")
+	}
+	if err := UpdateRule(d, Rule{ID: "no-existe"}); err == nil {
+		t.Fatal("expected error for missing rule")
+	}
+	if err := DeleteRule(d, "no-existe"); err == nil {
+		t.Fatal("expected error for missing rule")
+	}
+}
+
+func TestRuleScopeRouter(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	r := Rule{
+		Name:     "Temperatura patio",
+		Category: CatSystem,
+		Enabled:  true,
+		Condition: RuleCondition{
+			Metric:    "temp",
+			Operator:  "gt",
+			Threshold: 80,
+			Duration:  3 * time.Minute,
+		},
+		Scope:    RuleScope{Type: "router", RouterIDs: []string{"patio"}},
+		Severity: "warn",
+	}
+	if err := CreateRule(d, r); err != nil {
+		t.Fatalf("create: %v", err)
+	}
+	rules, err := ListRules(d)
+	if err != nil || len(rules) != 1 {
+		t.Fatalf("list: err=%v, len=%d", err, len(rules))
+	}
+	got := &rules[0]
+	if got.Scope.Type != "router" || len(got.Scope.RouterIDs) != 1 || got.Scope.RouterIDs[0] != "patio" {
+		t.Fatalf("scope not preserved: %+v", got.Scope)
+	}
+}

+ 106 - 0
server-go/internal/httpapi/rules_api.go

@@ -0,0 +1,106 @@
+package httpapi
+
+import (
+	"net/http"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+func (s *server) handleAlertRulesList(w http.ResponseWriter, _ *http.Request) {
+	rules, err := alerts.ListRules(s.db)
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
+		return
+	}
+	writeJSON(w, http.StatusOK, rules)
+}
+
+func (s *server) handleAlertRulesGet(w http.ResponseWriter, r *http.Request) {
+	id := r.PathValue("id")
+	rule, err := alerts.GetRule(s.db, id)
+	if err != nil {
+		writeError(w, http.StatusNotFound, "not_found", err.Error())
+		return
+	}
+	writeJSON(w, http.StatusOK, rule)
+}
+
+func (s *server) handleAlertRulesCreate(w http.ResponseWriter, r *http.Request) {
+	var rule alerts.Rule
+	if st := readJSONBody(w, r, &rule); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	if err := validateRule(rule); err != nil {
+		writeError(w, http.StatusBadRequest, "invalid_rule", err.Error())
+		return
+	}
+	if err := alerts.CreateRule(s.db, rule); err != nil {
+		writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
+		return
+	}
+	writeJSON(w, http.StatusCreated, map[string]any{"ok": true})
+}
+
+func (s *server) handleAlertRulesUpdate(w http.ResponseWriter, r *http.Request) {
+	id := r.PathValue("id")
+	var rule alerts.Rule
+	if st := readJSONBody(w, r, &rule); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	rule.ID = id
+	if err := validateRule(rule); err != nil {
+		writeError(w, http.StatusBadRequest, "invalid_rule", err.Error())
+		return
+	}
+	if err := alerts.UpdateRule(s.db, rule); err != nil {
+		writeError(w, http.StatusNotFound, "not_found", err.Error())
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
+func (s *server) handleAlertRulesDelete(w http.ResponseWriter, r *http.Request) {
+	id := r.PathValue("id")
+	if err := alerts.DeleteRule(s.db, id); err != nil {
+		writeError(w, http.StatusNotFound, "not_found", err.Error())
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
+func validateRule(r alerts.Rule) error {
+	if r.Name == "" {
+		return &validationError{"nombre requerido"}
+	}
+	if !alerts.IsCategory(r.Category) {
+		return &validationError{"categoría inválida: " + r.Category}
+	}
+	validOps := map[string]bool{"gt": true, "gte": true, "lt": true, "lte": true, "eq": true}
+	if !validOps[r.Condition.Operator] {
+		return &validationError{"operador inválido: " + r.Condition.Operator}
+	}
+	if r.Condition.Metric == "" {
+		return &validationError{"métrica requerida"}
+	}
+	if r.Condition.Duration <= 0 {
+		return &validationError{"duración debe ser > 0"}
+	}
+	validScopes := map[string]bool{"global": true, "router": true}
+	if !validScopes[r.Scope.Type] {
+		return &validationError{"scope inválido: " + r.Scope.Type}
+	}
+	if r.Scope.Type == "router" && len(r.Scope.RouterIDs) == 0 {
+		return &validationError{"scope=router requiere al menos un routerId"}
+	}
+	validSeverities := map[string]bool{"info": true, "warn": true, "critical": true}
+	if !validSeverities[r.Severity] {
+		return &validationError{"severidad inválida: " + r.Severity}
+	}
+	return nil
+}
+
+type validationError struct{ msg string }
+
+func (e *validationError) Error() string { return e.msg }

+ 89 - 0
server-go/internal/httpapi/rules_api_test.go

@@ -0,0 +1,89 @@
+package httpapi_test
+
+import (
+	"net/http"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+func TestAlertRulesAPI(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	res := get(t, ts.URL, "/api/alert-rules", cookie)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("list empty: %d", res.StatusCode)
+	}
+	res.Body.Close()
+
+	body := `{"name":"CPU alto","category":"router","enabled":true,"condition":{"metric":"cpu","operator":"gt","threshold":90,"duration":600000000000},"scope":{"type":"global"},"severity":"warn"}`
+	res = doJSON(t, "POST", ts.URL, "/api/alert-rules", cookie, body)
+	if res.StatusCode != http.StatusCreated {
+		t.Fatalf("create: %d", res.StatusCode)
+	}
+	res.Body.Close()
+
+	rules, err := alerts.ListRules(ts.db)
+	if err != nil || len(rules) != 1 {
+		t.Fatalf("list after create: err=%v len=%d", err, len(rules))
+	}
+	ruleID := rules[0].ID
+
+	res = get(t, ts.URL, "/api/alert-rules/"+ruleID, cookie)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("get: %d", res.StatusCode)
+	}
+	res.Body.Close()
+
+	body = `{"name":"CPU muy alto","category":"router","enabled":false,"condition":{"metric":"cpu","operator":"gt","threshold":95,"duration":300000000000},"scope":{"type":"global"},"severity":"critical"}`
+	res = doJSON(t, "PUT", ts.URL, "/api/alert-rules/"+ruleID, cookie, body)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("update: %d", res.StatusCode)
+	}
+	res.Body.Close()
+
+	got, _ := alerts.GetRule(ts.db, ruleID)
+	if got.Enabled || got.Name != "CPU muy alto" {
+		t.Fatalf("update not applied: %+v", got)
+	}
+
+	res = doJSON(t, "DELETE", ts.URL, "/api/alert-rules/"+ruleID, cookie, "")
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("delete: %d", res.StatusCode)
+	}
+	res.Body.Close()
+
+	rules, _ = alerts.ListRules(ts.db)
+	if len(rules) != 0 {
+		t.Fatalf("expected 0 rules after delete, got %d", len(rules))
+	}
+}
+
+func TestAlertRulesValidation(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	cases := []struct {
+		name string
+		body string
+	}{
+		{"empty name", `{"name":"","category":"router","enabled":true,"condition":{"metric":"cpu","operator":"gt","threshold":90,"duration":600000000000},"scope":{"type":"global"},"severity":"warn"}`},
+		{"bad category", `{"name":"x","category":"wifi","enabled":true,"condition":{"metric":"cpu","operator":"gt","threshold":90,"duration":600000000000},"scope":{"type":"global"},"severity":"warn"}`},
+		{"bad operator", `{"name":"x","category":"router","enabled":true,"condition":{"metric":"cpu","operator":"neq","threshold":90,"duration":600000000000},"scope":{"type":"global"},"severity":"warn"}`},
+		{"no metric", `{"name":"x","category":"router","enabled":true,"condition":{"metric":"","operator":"gt","threshold":90,"duration":600000000000},"scope":{"type":"global"},"severity":"warn"}`},
+		{"zero duration", `{"name":"x","category":"router","enabled":true,"condition":{"metric":"cpu","operator":"gt","threshold":90,"duration":0},"scope":{"type":"global"},"severity":"warn"}`},
+		{"bad scope", `{"name":"x","category":"router","enabled":true,"condition":{"metric":"cpu","operator":"gt","threshold":90,"duration":600000000000},"scope":{"type":"magic"},"severity":"warn"}`},
+		{"router scope no ids", `{"name":"x","category":"router","enabled":true,"condition":{"metric":"cpu","operator":"gt","threshold":90,"duration":600000000000},"scope":{"type":"router"},"severity":"warn"}`},
+		{"bad severity", `{"name":"x","category":"router","enabled":true,"condition":{"metric":"cpu","operator":"gt","threshold":90,"duration":600000000000},"scope":{"type":"global"},"severity":"panic"}`},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			res := doJSON(t, "POST", ts.URL, "/api/alert-rules", cookie, tc.body)
+			if res.StatusCode != http.StatusBadRequest {
+				t.Fatalf("expected 400, got %d", res.StatusCode)
+			}
+			res.Body.Close()
+		})
+	}
+}

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

@@ -206,6 +206,11 @@ func NewHandler(d Deps) http.Handler {
 	mux.HandleFunc("POST /api/alerts/silence", s.handleAlertsSilence)
 	mux.HandleFunc("POST /api/alerts/unsilence", s.handleAlertsUnsilence)
 	mux.HandleFunc("GET /api/alerts/silenced", s.handleAlertsSilenced)
+	mux.HandleFunc("GET /api/alert-rules", s.handleAlertRulesList)
+	mux.HandleFunc("GET /api/alert-rules/{id}", s.handleAlertRulesGet)
+	mux.HandleFunc("POST /api/alert-rules", s.handleAlertRulesCreate)
+	mux.HandleFunc("PUT /api/alert-rules/{id}", s.handleAlertRulesUpdate)
+	mux.HandleFunc("DELETE /api/alert-rules/{id}", s.handleAlertRulesDelete)
 	mux.HandleFunc("GET /api/topology", s.handleTopology)
 	mux.HandleFunc("GET /api/dawn", s.handleDawn)
 	mux.HandleFunc("GET /api/dot11r", s.handleDot11r)