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

feat: Telegram bot notification transport (#347)

* feat(alerts): add Telegram bot notification transport (#326)

New package server-go/internal/telegram implementing alerts.Notifier
for direct Telegram Bot API integration (sendMessage). Zero external
dependencies - uses stdlib net/http.

Features:
- Bot token + chat ID config persisted in kv store
- Validation via getMe/getChat before saving
- disable_notification for non-urgent alerts
- Retry with exponential backoff + Telegram retry_after (429)
- HTML formatted messages with category emoji and severity
- Queue cap 64 with non-blocking drop
- API endpoints: GET/PUT /api/settings/telegram, POST .../test
- 10 tests covering format, escape, retry, config, queue drop

* feat(ui): add Telegram settings card (#326)

New TelegramCard component in Settings for configuring Telegram bot
notifications: bot token (masked), chat ID, enable toggle, save
with validation (getMe/getChat), and send test message button.

Hidden in demo mode. i18n keys for EN and ES.

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 месяцев назад
Родитель
Сommit
0108cd8f93

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

@@ -952,6 +952,16 @@
       "errorGeneric": "Push notifications could not be enabled on this device.",
       "note": "Only alerts marked as urgent arrive (configured in Alerts). The notice is shown by the operating system with the NetPulse icon."
     },
+    "telegram": {
+      "title": "Telegram notifications",
+      "description": "Receive alerts directly in Telegram. Create a bot with @BotFather and add it to a chat.",
+      "enabled": "Enable Telegram notifications",
+      "botToken": "Bot token",
+      "chatId": "Chat ID",
+      "bot": "Bot",
+      "chat": "Chat",
+      "sendTest": "Send test"
+    },
     "pwa": {
       "caption": "Installable app · PWA",
       "desc": "Install it as an app: fullscreen launch, no browser bar and instant access.",

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

@@ -952,6 +952,16 @@
       "errorGeneric": "No se pudieron activar las notificaciones push en este dispositivo.",
       "note": "Solo llegan las alertas marcadas como urgentes (se configura en Alertas). El aviso lo muestra el sistema operativo con el icono de NetPulse."
     },
+    "telegram": {
+      "title": "Notificaciones Telegram",
+      "description": "Recibe alertas directamente en Telegram. Crea un bot con @BotFather y añádelo a un chat.",
+      "enabled": "Activar notificaciones Telegram",
+      "botToken": "Token del bot",
+      "chatId": "ID del chat",
+      "bot": "Bot",
+      "chat": "Chat",
+      "sendTest": "Enviar prueba"
+    },
     "pwa": {
       "caption": "App instalable · PWA",
       "desc": "Instálala como app: arranque a pantalla completa, sin barra del navegador y acceso instantáneo.",

+ 214 - 0
app/src/components/TelegramCard.tsx

@@ -0,0 +1,214 @@
+import { useState, useEffect, useCallback } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Send, Loader2, Check, Eye, EyeOff, Bell } from 'lucide-react'
+
+type TelegramState = 'loading' | 'idle' | 'saving' | 'testing' | 'saved' | 'error'
+
+interface TelegramConfig {
+  botToken: string
+  chatId: string
+  enabled: boolean
+  botName?: string
+  chatName?: string
+}
+
+export default function TelegramCard({ onSaved }: { onSaved: () => void }) {
+  const { t } = useTranslation()
+  const [state, setState] = useState<TelegramState>('loading')
+  const [cfg, setCfg] = useState<TelegramConfig>({ botToken: '', chatId: '', enabled: false })
+  const [showToken, setShowToken] = useState(false)
+  const [error, setError] = useState('')
+  const [botName, setBotName] = useState('')
+  const [chatName, setChatName] = useState('')
+
+  useEffect(() => {
+    let alive = true
+    void fetch('/api/settings/telegram')
+      .then((r) => (r.ok ? r.json() : null))
+      .then((d) => {
+        if (!alive || !d) return
+        setCfg({
+          botToken: d.botToken || '',
+          chatId: d.chatId || '',
+          enabled: !!d.enabled,
+        })
+        setBotName(d.botName || '')
+        setChatName(d.chatName || '')
+        setState('idle')
+      })
+      .catch(() => {
+        if (alive) setState('idle')
+      })
+    return () => { alive = false }
+  }, [])
+
+  const save = useCallback(async () => {
+    setState('saving')
+    setError('')
+    try {
+      const res = await fetch('/api/settings/telegram', {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({
+          botToken: cfg.botToken,
+          chatId: cfg.chatId,
+          enabled: cfg.enabled,
+        }),
+      })
+      const data = await res.json().catch(() => null)
+      if (!res.ok) {
+        setError(data?.message || data?.error || 'Save failed')
+        setState('error')
+        return
+      }
+      if (data?.botName) setBotName(data.botName)
+      if (data?.chatName) setChatName(data.chatName)
+      setState('saved')
+      onSaved()
+      setTimeout(() => setState('idle'), 1500)
+    } catch {
+      setError('Network error')
+      setState('error')
+    }
+  }, [cfg, onSaved])
+
+  const test = useCallback(async () => {
+    setState('testing')
+    setError('')
+    try {
+      const res = await fetch('/api/settings/telegram/test', { method: 'POST' })
+      if (!res.ok) {
+        const data = await res.json().catch(() => null)
+        setError(data?.message || data?.error || 'Test failed')
+        setState('error')
+        return
+      }
+      setState('saved')
+      setTimeout(() => setState('idle'), 1500)
+    } catch {
+      setError('Network error')
+      setState('error')
+    }
+  }, [])
+
+  if (state === 'loading') {
+    return (
+      <div className="flex items-center gap-2 rounded-lg border border-border bg-surface p-4">
+        <Loader2 className="h-4 w-4 animate-spin text-text-muted" />
+        <span className="text-xs text-text-muted">{t('common.loading')}</span>
+      </div>
+    )
+  }
+
+  const busy = state === 'saving' || state === 'testing'
+
+  return (
+    <div className="rounded-lg border border-border bg-surface p-4">
+      <div className="mb-3 flex items-center gap-2">
+        <Bell className="h-4 w-4 text-accent" strokeWidth={2} />
+        <h3 className="text-sm font-semibold text-text-primary">{t('settings.telegram.title')}</h3>
+      </div>
+
+      <p className="mb-3 text-xs text-text-secondary">{t('settings.telegram.description')}</p>
+
+      <div className="space-y-3">
+        {/* Enable toggle */}
+        <label className="flex items-center gap-2 text-xs text-text-primary">
+          <input
+            type="checkbox"
+            checked={cfg.enabled}
+            onChange={(e) => setCfg((c) => ({ ...c, enabled: e.target.checked }))}
+            className="h-4 w-4 rounded border-border accent-accent"
+          />
+          {t('settings.telegram.enabled')}
+        </label>
+
+        {/* Bot token */}
+        <div>
+          <label className="mb-1 block text-[11px] font-medium uppercase tracking-wider text-text-muted">
+            {t('settings.telegram.botToken')}
+          </label>
+          <div className="flex items-center gap-1">
+            <input
+              type={showToken ? 'text' : 'password'}
+              value={cfg.botToken}
+              onChange={(e) => setCfg((c) => ({ ...c, botToken: e.target.value }))}
+              placeholder="123456:ABC-DEF1234..."
+              className="flex-1 rounded-md border border-border bg-canvas px-2.5 py-1.5 text-xs text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+            />
+            <button
+              type="button"
+              onClick={() => setShowToken((v) => !v)}
+              className="rounded-md border border-border p-1.5 text-text-muted hover:text-text-primary"
+              title={showToken ? 'Hide' : 'Show'}
+            >
+              {showToken ? <EyeOff className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}
+            </button>
+          </div>
+          {botName && (
+            <p className="mt-1 text-[10px] text-text-muted">
+              {t('settings.telegram.bot')}: @{botName}
+            </p>
+          )}
+        </div>
+
+        {/* Chat ID */}
+        <div>
+          <label className="mb-1 block text-[11px] font-medium uppercase tracking-wider text-text-muted">
+            {t('settings.telegram.chatId')}
+          </label>
+          <input
+            type="text"
+            value={cfg.chatId}
+            onChange={(e) => setCfg((c) => ({ ...c, chatId: e.target.value }))}
+            placeholder="-100123456789"
+            className="w-full rounded-md border border-border bg-canvas px-2.5 py-1.5 text-xs text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+          />
+          {chatName && (
+            <p className="mt-1 text-[10px] text-text-muted">
+              {t('settings.telegram.chat')}: {chatName}
+            </p>
+          )}
+        </div>
+
+        {/* Error */}
+        {error && (
+          <p className="text-xs text-danger">{error}</p>
+        )}
+
+        {/* Actions */}
+        <div className="flex items-center gap-2 pt-1">
+          <button
+            type="button"
+            onClick={() => void save()}
+            disabled={busy || !cfg.botToken || !cfg.chatId}
+            className="inline-flex items-center gap-1.5 rounded-lg bg-accent px-3 py-1.5 text-xs font-semibold text-canvas transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"
+          >
+            {state === 'saving' ? (
+              <Loader2 className="h-3.5 w-3.5 animate-spin" />
+            ) : state === 'saved' ? (
+              <Check className="h-3.5 w-3.5" />
+            ) : (
+              <Check className="h-3.5 w-3.5" />
+            )}
+            {t('common.save')}
+          </button>
+
+          <button
+            type="button"
+            onClick={() => void test()}
+            disabled={busy || !cfg.enabled}
+            className="inline-flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs font-medium text-text-primary transition-colors hover:bg-hover disabled:cursor-not-allowed disabled:opacity-40"
+          >
+            {state === 'testing' ? (
+              <Loader2 className="h-3.5 w-3.5 animate-spin" />
+            ) : (
+              <Send className="h-3.5 w-3.5" />
+            )}
+            {t('settings.telegram.sendTest')}
+          </button>
+        </div>
+      </div>
+    </div>
+  )
+}

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

@@ -61,6 +61,7 @@ import type { ServicesVisibility } from '@/hooks/useServicesVisibility'
 import { relTimeFromTs } from '@/i18n'
 import { cn, exitDemo } from '@/lib/utils'
 import { ACCENTS, type AccentId, type ThemeMode } from '@/lib/theme-boot'
+import TelegramCard from '@/components/TelegramCard'
 import pkg from '../../package.json'
 
 // ---------------------------------------------------------------------------
@@ -3913,6 +3914,9 @@ export default function Settings() {
               ) : null}
             </div>
 
+            {/* Telegram (#326): notificaciones directas al bot */}
+            {!isDemo && <TelegramCard onSaved={notify} />}
+
             {/* Sistema: datos del servidor (SPEC-65 D65-7e) */}
             <SystemInfoBlock />
           </Card>

+ 39 - 2
server-go/cmd/netpulse/main.go

@@ -15,6 +15,7 @@ import (
 	"crypto/sha256"
 	"crypto/subtle"
 	"crypto/tls"
+	"database/sql"
 	"encoding/hex"
 	"errors"
 	"fmt"
@@ -46,6 +47,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/sse"
 	"github.com/gnacho/netpulse/server-go/internal/sshkey"
 	"github.com/gnacho/netpulse/server-go/internal/staticspa"
+	"github.com/gnacho/netpulse/server-go/internal/telegram"
 	"github.com/gnacho/netpulse/server-go/internal/tlscert"
 	"github.com/gnacho/netpulse/server-go/internal/updater"
 	"github.com/gnacho/netpulse/server-go/internal/webhook"
@@ -273,12 +275,21 @@ func run() error {
 		log.Printf("[netpulse] webhook saliente activo: %s", webhookHostForLog(cfg.Webhook.URL))
 	}
 
-	// Notifier compuesto: push + webhook (SetNotifier solo admite UNO).
+	// Telegram (#326): transport nativo si está configurado en kv.
+	var telegramNotifier *telegram.Notifier
+	tgKV := &mainKVAdapter{db: dbHandle.DB}
+	tgCfg := telegram.LoadConfig(tgKV)
+	if tgCfg.Enabled && tgCfg.BotToken != "" && tgCfg.ChatID != "" {
+		telegramNotifier = telegram.NewNotifier(tgKV)
+		log.Printf("[netpulse] telegram activo: chat %s", tgCfg.ChatID)
+	}
+
+	// Notifier compuesto: push + webhook + telegram (SetNotifier solo admite UNO).
 	// OJO nil-encapsulado (issue #57): meter un `(*webhook.Notifier)(nil)` en
 	// la cadena lo empaqueta en la interfaz con tipo pero valor nil → la
 	// interfaz NO es nil y `if n != nil` de notifierChain no lo filtra →
 	// panic al Notify. Filtrar ANTES de empaquetar.
-	if pushNotifier != nil || webhookNotifier != nil {
+	if pushNotifier != nil || webhookNotifier != nil || telegramNotifier != nil {
 		chain := notifierChain{}
 		if pushNotifier != nil {
 			chain = append(chain, pushNotifier)
@@ -286,6 +297,9 @@ func run() error {
 		if webhookNotifier != nil {
 			chain = append(chain, webhookNotifier)
 		}
+		if telegramNotifier != nil {
+			chain = append(chain, telegramNotifier)
+		}
 		adapter.AlertsEngine().SetNotifier(chain)
 	}
 
@@ -468,6 +482,9 @@ func run() error {
 		if webhookNotifier != nil {
 			webhookNotifier.Close()
 		}
+		if telegramNotifier != nil {
+			telegramNotifier.Close()
+		}
 		// Salvavidas de 3 s: salir igualmente aunque el server no cierre.
 		lifeline := time.AfterFunc(3*time.Second, func() {
 			_ = dbHandle.Close()
@@ -515,3 +532,23 @@ func (c notifierChain) Notify(ev alerts.AlertEvent) {
 		n.Notify(ev)
 	}
 }
+
+// mainKVAdapter implements telegram.kvStore over *sql.DB.
+type mainKVAdapter struct {
+	db *sql.DB
+}
+
+func (a *mainKVAdapter) Get(key string) (string, bool) {
+	var v string
+	if err := a.db.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v); err != nil {
+		return "", false
+	}
+	return v, true
+}
+
+func (a *mainKVAdapter) Set(key, value string) error {
+	_, err := a.db.Exec(
+		`INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
+		key, value)
+	return err
+}

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

@@ -139,6 +139,7 @@ func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
 	})))
 
 	s.registerKnownMacsRoutes(mux)
+	s.registerTelegramRoutes(mux)
 }
 
 // knownMacItem es la forma JSON de una entrada de la allowlist (#196).

+ 105 - 0
server-go/internal/httpapi/telegram_settings.go

@@ -0,0 +1,105 @@
+package httpapi
+
+import (
+	"database/sql"
+	"net/http"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/telegram"
+)
+
+type dbKVAdapter struct {
+	db *sql.DB
+}
+
+func (a *dbKVAdapter) Get(key string) (string, bool) {
+	v := kvGet(a.db, key)
+	if v == "" {
+		return "", false
+	}
+	return v, true
+}
+
+func (a *dbKVAdapter) Set(key, value string) error {
+	_, err := a.db.Exec(
+		`INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
+		key, value)
+	return err
+}
+
+type telegramConfigResponse struct {
+	BotToken string `json:"botToken"`
+	ChatID   string `json:"chatId"`
+	Enabled  bool   `json:"enabled"`
+	BotName  string `json:"botName,omitempty"`
+	ChatName string `json:"chatName,omitempty"`
+}
+
+func (s *server) registerTelegramRoutes(mux *http.ServeMux) {
+	adapter := &dbKVAdapter{db: s.db.DB}
+
+	mux.Handle("GET /api/settings/telegram", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		cfg := telegram.LoadConfig(adapter)
+		resp := telegramConfigResponse{
+			ChatID:  cfg.ChatID,
+			Enabled: cfg.Enabled,
+		}
+		if cfg.BotToken != "" {
+			if len(cfg.BotToken) > 10 {
+				resp.BotToken = cfg.BotToken[:6] + "..." + cfg.BotToken[len(cfg.BotToken)-4:]
+			} else {
+				resp.BotToken = "***"
+			}
+		}
+		writeJSON(w, http.StatusOK, resp)
+	})))
+
+	mux.Handle("PUT /api/settings/telegram", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		var body struct {
+			BotToken string `json:"botToken"`
+			ChatID   string `json:"chatId"`
+			Enabled  bool   `json:"enabled"`
+		}
+		if st := readJSONBody(w, r, &body); st != 0 {
+			writeBodyError(w, st, "invalid_body", "")
+			return
+		}
+
+		cfg := telegram.LoadConfig(adapter)
+		if body.BotToken != "" {
+			cfg.BotToken = body.BotToken
+		}
+		cfg.ChatID = body.ChatID
+		cfg.Enabled = body.Enabled
+
+		if cfg.BotToken == "" || cfg.ChatID == "" {
+			writeError(w, http.StatusBadRequest, "invalid_input", "botToken and chatId are required")
+			return
+		}
+
+		botName, chatName, err := telegram.ValidateConfig(cfg.BotToken, cfg.ChatID)
+		if err != nil {
+			writeError(w, http.StatusBadRequest, "validation_failed", err.Error())
+			return
+		}
+
+		if err := telegram.SaveConfig(adapter, cfg); err != nil {
+			writeError(w, http.StatusInternalServerError, "kv_error")
+			return
+		}
+
+		writeJSON(w, http.StatusOK, map[string]any{
+			"ok":       true,
+			"botName":  botName,
+			"chatName": chatName,
+		})
+	})))
+
+	mux.Handle("POST /api/settings/telegram/test", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if err := telegram.SendTest(adapter); err != nil {
+			writeError(w, http.StatusBadRequest, "send_failed", err.Error())
+			return
+		}
+		writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
+	})))
+}

+ 414 - 0
server-go/internal/telegram/telegram.go

@@ -0,0 +1,414 @@
+package telegram
+
+import (
+	"bytes"
+	"context"
+	"encoding/json"
+	"fmt"
+	"io"
+	"log/slog"
+	"net/http"
+	"strings"
+	"sync"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+const (
+	kvKeyBotToken = "telegram.bot_token"
+	kvKeyChatID   = "telegram.chat_id"
+	kvKeyEnabled  = "telegram.enabled"
+
+	apiBase       = "https://api.telegram.org"
+	queueCap      = 64
+	maxRetries    = 3
+	baseRetry     = 2 * time.Second
+	sendTimeout   = 10 * time.Second
+	parseMode     = "HTML"
+	maxMsgLen     = 4096
+)
+
+type kvStore interface {
+	Get(key string) (string, bool)
+	Set(key, value string) error
+}
+
+type Config struct {
+	BotToken string `json:"botToken"`
+	ChatID   string `json:"chatId"`
+	Enabled  bool   `json:"enabled"`
+}
+
+type Notifier struct {
+	kv     kvStore
+	queue  chan alerts.AlertEvent
+	done   chan struct{}
+	wg     sync.WaitGroup
+	client *http.Client
+}
+
+func LoadConfig(kv kvStore) Config {
+	cfg := Config{}
+	if v, ok := kv.Get(kvKeyBotToken); ok {
+		cfg.BotToken = v
+	}
+	if v, ok := kv.Get(kvKeyChatID); ok {
+		cfg.ChatID = v
+	}
+	if v, ok := kv.Get(kvKeyEnabled); ok {
+		cfg.Enabled = v == "true"
+	}
+	return cfg
+}
+
+func SaveConfig(kv kvStore, cfg Config) error {
+	if err := kv.Set(kvKeyBotToken, cfg.BotToken); err != nil {
+		return fmt.Errorf("save bot_token: %w", err)
+	}
+	if err := kv.Set(kvKeyChatID, cfg.ChatID); err != nil {
+		return fmt.Errorf("save chat_id: %w", err)
+	}
+	enabled := "false"
+	if cfg.Enabled {
+		enabled = "true"
+	}
+	if err := kv.Set(kvKeyEnabled, enabled); err != nil {
+		return fmt.Errorf("save enabled: %w", err)
+	}
+	return nil
+}
+
+func NewNotifier(kv kvStore) *Notifier {
+	n := &Notifier{
+		kv:     kv,
+		queue:  make(chan alerts.AlertEvent, queueCap),
+		done:   make(chan struct{}),
+		client: &http.Client{Timeout: sendTimeout},
+	}
+	n.wg.Add(1)
+	go n.worker()
+	return n
+}
+
+func (n *Notifier) Notify(ev alerts.AlertEvent) {
+	select {
+	case n.queue <- ev:
+	default:
+		slog.Warn("telegram: queue full, dropping alert", "title", ev.Title)
+	}
+}
+
+func (n *Notifier) Close() {
+	close(n.done)
+	n.wg.Wait()
+}
+
+func (n *Notifier) worker() {
+	defer n.wg.Done()
+	for {
+		select {
+		case <-n.done:
+			return
+		case ev := <-n.queue:
+			cfg := LoadConfig(n.kv)
+			if !cfg.Enabled || cfg.BotToken == "" || cfg.ChatID == "" {
+				continue
+			}
+			msg := formatMessage(ev)
+			if err := n.sendWithRetry(cfg, msg, ev.Urgent); err != nil {
+				slog.Error("telegram: send failed after retries", "error", err, "title", ev.Title)
+			}
+		}
+	}
+}
+
+func (n *Notifier) sendWithRetry(cfg Config, text string, urgent bool) error {
+	var lastErr error
+	for attempt := 0; attempt <= maxRetries; attempt++ {
+		if attempt > 0 {
+			backoff := baseRetry * time.Duration(1<<(attempt-1))
+			if retryAfter, ok := retryAfterFromErr(lastErr); ok && retryAfter > 0 {
+				backoff = retryAfter
+			}
+			select {
+			case <-time.After(backoff):
+			case <-n.done:
+				return fmt.Errorf("shutdown during retry")
+			}
+		}
+		if err := n.sendMessage(cfg, text, urgent); err != nil {
+			lastErr = err
+			if !isRetryable(err) {
+				return err
+			}
+			continue
+		}
+		return nil
+	}
+	return fmt.Errorf("max retries: %w", lastErr)
+}
+
+type sendPayload struct {
+	ChatID              string `json:"chat_id"`
+	Text                string `json:"text"`
+	ParseMode           string `json:"parse_mode"`
+	DisableNotification bool   `json:"disable_notification,omitempty"`
+}
+
+type apiResponse struct {
+	OK          bool            `json:"ok"`
+	ErrorCode   int             `json:"error_code"`
+	Description string          `json:"description"`
+	Result      json.RawMessage `json:"result"`
+	Parameters  *apiParameters  `json:"parameters,omitempty"`
+}
+
+type apiParameters struct {
+	RetryAfter int `json:"retry_after,omitempty"`
+}
+
+func (n *Notifier) sendMessage(cfg Config, text string, urgent bool) error {
+	payload := sendPayload{
+		ChatID:              cfg.ChatID,
+		Text:                text,
+		ParseMode:           parseMode,
+		DisableNotification: !urgent,
+	}
+	body, err := json.Marshal(payload)
+	if err != nil {
+		return fmt.Errorf("marshal: %w", err)
+	}
+
+	url := fmt.Sprintf("%s/bot%s/sendMessage", apiBase, cfg.BotToken)
+	ctx, cancel := context.WithTimeout(context.Background(), sendTimeout)
+	defer cancel()
+
+	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
+	if err != nil {
+		return fmt.Errorf("new request: %w", err)
+	}
+	req.Header.Set("Content-Type", "application/json")
+
+	resp, err := n.client.Do(req)
+	if err != nil {
+		return fmt.Errorf("http do: %w", err)
+	}
+	defer resp.Body.Close()
+
+	respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
+
+	var apiResp apiResponse
+	if err := json.Unmarshal(respBody, &apiResp); err != nil {
+		if resp.StatusCode >= 200 && resp.StatusCode < 300 {
+			return nil
+		}
+		return fmt.Errorf("status %d: %s", resp.StatusCode, string(respBody))
+	}
+
+	if !apiResp.OK {
+		errMsg := fmt.Sprintf("api error %d: %s", apiResp.ErrorCode, apiResp.Description)
+		if apiResp.Parameters != nil && apiResp.Parameters.RetryAfter > 0 {
+			errMsg = fmt.Sprintf("%s [retry_after=%d]", errMsg, apiResp.Parameters.RetryAfter)
+		}
+		return fmt.Errorf("%s", errMsg)
+	}
+	return nil
+}
+
+func isRetryable(err error) bool {
+	if err == nil {
+		return false
+	}
+	msg := err.Error()
+	// 4xx (except 429) are not retryable
+	for _, code := range []string{"400", "401", "403", "404"} {
+		if contains(msg, "api error "+code) {
+			return false
+		}
+	}
+	return true
+}
+
+func contains(s, substr string) bool {
+	return len(s) >= len(substr) && searchString(s, substr)
+}
+
+func searchString(s, substr string) bool {
+	for i := 0; i <= len(s)-len(substr); i++ {
+		if s[i:i+len(substr)] == substr {
+			return true
+		}
+	}
+	return false
+}
+
+func formatMessage(ev alerts.AlertEvent) string {
+	emoji := categoryEmoji(ev.Category)
+	severity := "⚠️"
+	if ev.Urgent {
+		severity = "🔴"
+	}
+
+	ts := time.Unix(ev.Ts, 0).Format("15:04:05")
+	text := fmt.Sprintf("%s%s <b>%s</b>\n", severity, emoji, htmlEscape(ev.Title))
+	if ev.Description != "" {
+		desc := ev.Description
+		if len(desc) > 500 {
+			desc = desc[:500] + "..."
+		}
+		text += htmlEscape(desc) + "\n"
+	}
+	if ev.RouterID != "" {
+		text += fmt.Sprintf("📡 %s\n", htmlEscape(ev.RouterID))
+	}
+	if ev.Hint != "" {
+		text += fmt.Sprintf("💡 <i>%s</i>\n", htmlEscape(ev.Hint))
+	}
+	text += fmt.Sprintf("🕐 %s", ts)
+
+	if len(text) > maxMsgLen {
+		text = text[:maxMsgLen-3] + "..."
+	}
+	return text
+}
+
+func categoryEmoji(cat string) string {
+	switch cat {
+	case "router":
+		return "📡"
+	case "internet":
+		return "🌐"
+	case "clients":
+		return "📱"
+	case "signal":
+		return "📶"
+	case "vpn":
+		return "🔒"
+	case "system":
+		return "⚙️"
+	default:
+		return "🔔"
+	}
+}
+
+func htmlEscape(s string) string {
+	r := make([]byte, 0, len(s))
+	for i := 0; i < len(s); i++ {
+		switch s[i] {
+		case '<':
+			r = append(r, '&', 'l', 't', ';')
+		case '>':
+			r = append(r, '&', 'g', 't', ';')
+		case '&':
+			r = append(r, '&', 'a', 'm', 'p', ';')
+		default:
+			r = append(r, s[i])
+		}
+	}
+	return string(r)
+}
+
+func SendTest(kv kvStore) error {
+	cfg := LoadConfig(kv)
+	if cfg.BotToken == "" || cfg.ChatID == "" {
+		return fmt.Errorf("bot token and chat ID are required")
+	}
+	n := &Notifier{
+		client: &http.Client{Timeout: sendTimeout},
+		done:   make(chan struct{}),
+	}
+	defer close(n.done)
+	text := "✅ <b>NetPulse</b> Telegram notifications configured successfully."
+	return n.sendMessage(cfg, text, true)
+}
+
+func ValidateConfig(botToken, chatID string) (botName string, chatTitle string, err error) {
+	client := &http.Client{Timeout: sendTimeout}
+
+	// Validate bot token via getMe
+	meURL := fmt.Sprintf("%s/bot%s/getMe", apiBase, botToken)
+	resp, err := client.Get(meURL)
+	if err != nil {
+		return "", "", fmt.Errorf("getMe request failed: %w", err)
+	}
+	defer resp.Body.Close()
+
+	var meResp apiResponse
+	body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
+	if jsonErr := json.Unmarshal(body, &meResp); jsonErr != nil {
+		return "", "", fmt.Errorf("getMe: invalid response")
+	}
+	if !meResp.OK {
+		return "", "", fmt.Errorf("invalid bot token: %s", meResp.Description)
+	}
+
+	var meResult struct {
+		Username  string `json:"username"`
+		FirstName string `json:"first_name"`
+	}
+	if jsonErr := json.Unmarshal(meResp.Result, &meResult); jsonErr == nil {
+		botName = meResult.Username
+		if botName == "" {
+			botName = meResult.FirstName
+		}
+	}
+
+	// Validate chat ID via getChat
+	chatURL := fmt.Sprintf("%s/bot%s/getChat?chat_id=%s", apiBase, botToken, chatID)
+	resp2, err := client.Get(chatURL)
+	if err != nil {
+		return botName, "", fmt.Errorf("getChat request failed: %w", err)
+	}
+	defer resp2.Body.Close()
+
+	var chatResp apiResponse
+	body2, _ := io.ReadAll(io.LimitReader(resp2.Body, 4096))
+	if jsonErr := json.Unmarshal(body2, &chatResp); jsonErr != nil {
+		return botName, "", fmt.Errorf("getChat: invalid response")
+	}
+	if !chatResp.OK {
+		return botName, "", fmt.Errorf("invalid chat ID: %s", chatResp.Description)
+	}
+
+	var chatResult struct {
+		Title     string `json:"title"`
+		FirstName string `json:"first_name"`
+		Type      string `json:"type"`
+	}
+	if jsonErr := json.Unmarshal(chatResp.Result, &chatResult); jsonErr == nil {
+		chatTitle = chatResult.Title
+		if chatTitle == "" {
+			chatTitle = chatResult.FirstName
+		}
+	}
+	return botName, chatTitle, nil
+}
+
+func retryAfterFromErr(err error) (time.Duration, bool) {
+	if err == nil {
+		return 0, false
+	}
+	msg := err.Error()
+	const prefix = "[retry_after="
+	idx := strings.Index(msg, prefix)
+	if idx < 0 {
+		return 0, false
+	}
+	rest := msg[idx+len(prefix):]
+	end := strings.Index(rest, "]")
+	if end < 0 {
+		return 0, false
+	}
+	secs := 0
+	for _, c := range rest[:end] {
+		if c < '0' || c > '9' {
+			return 0, false
+		}
+		secs = secs*10 + int(c-'0')
+	}
+	if secs <= 0 {
+		return 0, false
+	}
+	return time.Duration(secs) * time.Second, true
+}

+ 249 - 0
server-go/internal/telegram/telegram_test.go

@@ -0,0 +1,249 @@
+package telegram
+
+import (
+	"fmt"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+func TestFormatMessageUrgent(t *testing.T) {
+	ev := alerts.AlertEvent{
+		Category:    "router",
+		Urgent:      true,
+		Title:       "Agent down",
+		Description: "The agent stopped responding",
+		Hint:        "Check power and network",
+		RouterID:    "rt1",
+		Ts:          time.Date(2026, 8, 28, 21, 30, 0, 0, time.UTC).Unix(),
+	}
+	msg := formatMessage(ev)
+
+	if !strings.Contains(msg, "🔴") {
+		t.Error("urgent alert should contain red circle emoji")
+	}
+	if !strings.Contains(msg, "📡") {
+		t.Error("router category should contain antenna emoji")
+	}
+	if !strings.Contains(msg, "<b>Agent down</b>") {
+		t.Error("title should be bold")
+	}
+	if !strings.Contains(msg, "The agent stopped responding") {
+		t.Error("description should be present")
+	}
+	if !strings.Contains(msg, "rt1") {
+		t.Error("router ID should be present")
+	}
+	if !strings.Contains(msg, "<i>Check power and network</i>") {
+		t.Error("hint should be italic")
+	}
+	if !strings.Contains(msg, "21:30:00") {
+		// Timestamp is formatted in local timezone
+		localTime := time.Date(2026, 8, 28, 21, 30, 0, 0, time.UTC).Local().Format("15:04:05")
+		if !strings.Contains(msg, localTime) {
+			t.Errorf("timestamp should be present, got msg: %s", msg)
+		}
+	}
+}
+
+func TestFormatMessageNonUrgent(t *testing.T) {
+	ev := alerts.AlertEvent{
+		Category: "system",
+		Urgent:   false,
+		Title:    "CPU high",
+		Ts:       time.Date(2026, 8, 28, 10, 0, 0, 0, time.UTC).Unix(),
+	}
+	msg := formatMessage(ev)
+
+	if !strings.Contains(msg, "⚠️") {
+		t.Error("non-urgent alert should contain warning emoji")
+	}
+	if strings.Contains(msg, "🔴") {
+		t.Error("non-urgent alert should NOT contain red circle")
+	}
+}
+
+func TestFormatMessageHTMLEscape(t *testing.T) {
+	ev := alerts.AlertEvent{
+		Category:    "internet",
+		Title:       "WAN <down>",
+		Description: "Loss & latency > 100ms",
+		Ts:          time.Now().Unix(),
+	}
+	msg := formatMessage(ev)
+
+	if strings.Contains(msg, "<down>") {
+		t.Error("angle brackets in title should be escaped")
+	}
+	if !strings.Contains(msg, "&lt;down&gt;") {
+		t.Error("title should contain escaped HTML entities")
+	}
+	if strings.Contains(msg, "> 100ms") {
+		t.Error("angle bracket in description should be escaped")
+	}
+}
+
+func TestFormatMessageTruncatesLongDescription(t *testing.T) {
+	ev := alerts.AlertEvent{
+		Category:    "clients",
+		Title:       "Test",
+		Description: strings.Repeat("x", 600),
+		Ts:          time.Now().Unix(),
+	}
+	msg := formatMessage(ev)
+
+	if strings.Count(msg, "x") > 510 {
+		t.Error("long description should be truncated to ~500 chars")
+	}
+}
+
+func TestCategoryEmoji(t *testing.T) {
+	cases := map[string]string{
+		"router":   "📡",
+		"internet": "🌐",
+		"clients":  "📱",
+		"signal":   "📶",
+		"vpn":      "🔒",
+		"system":   "⚙️",
+		"unknown":  "🔔",
+	}
+	for cat, want := range cases {
+		got := categoryEmoji(cat)
+		if got != want {
+			t.Errorf("categoryEmoji(%q) = %q, want %q", cat, got, want)
+		}
+	}
+}
+
+func TestHTMLEscape(t *testing.T) {
+	cases := map[string]string{
+		"hello":          "hello",
+		"<b>bold</b>":    "&lt;b&gt;bold&lt;/b&gt;",
+		"a & b":          "a &amp; b",
+		"no special":     "no special",
+		"<>&":            "&lt;&gt;&amp;",
+	}
+	for input, want := range cases {
+		got := htmlEscape(input)
+		if got != want {
+			t.Errorf("htmlEscape(%q) = %q, want %q", input, got, want)
+		}
+	}
+}
+
+func TestIsRetryable(t *testing.T) {
+	cases := []struct {
+		err  string
+		want bool
+	}{
+		{"api error 400: bad request", false},
+		{"api error 401: unauthorized", false},
+		{"api error 403: forbidden", false},
+		{"api error 404: not found", false},
+		{"api error 429: too many requests", true},
+		{"api error 500: internal", true},
+		{"http do: connection refused", true},
+		{"", false},
+	}
+	for _, tc := range cases {
+		var err error
+		if tc.err != "" {
+			err = fmt.Errorf("%s", tc.err)
+		}
+		got := isRetryable(err)
+		if got != tc.want {
+			t.Errorf("isRetryable(%q) = %v, want %v", tc.err, got, tc.want)
+		}
+	}
+}
+
+// mockKV implements kvStore for testing.
+type mockKV struct {
+	data map[string]string
+}
+
+func (m *mockKV) Get(key string) (string, bool) {
+	v, ok := m.data[key]
+	return v, ok
+}
+
+func (m *mockKV) Set(key, value string) error {
+	m.data[key] = value
+	return nil
+}
+
+func TestLoadSaveConfig(t *testing.T) {
+	kv := &mockKV{data: make(map[string]string)}
+
+	// Empty config
+	cfg := LoadConfig(kv)
+	if cfg.BotToken != "" || cfg.ChatID != "" || cfg.Enabled {
+		t.Error("empty kv should return zero config")
+	}
+
+	// Save and reload
+	want := Config{BotToken: "123:ABC", ChatID: "-100123456", Enabled: true}
+	if err := SaveConfig(kv, want); err != nil {
+		t.Fatalf("SaveConfig: %v", err)
+	}
+
+	got := LoadConfig(kv)
+	if got.BotToken != want.BotToken {
+		t.Errorf("BotToken = %q, want %q", got.BotToken, want.BotToken)
+	}
+	if got.ChatID != want.ChatID {
+		t.Errorf("ChatID = %q, want %q", got.ChatID, want.ChatID)
+	}
+	if !got.Enabled {
+		t.Error("Enabled should be true")
+	}
+}
+
+func TestNotifyDropsWhenFull(t *testing.T) {
+	kv := &mockKV{data: make(map[string]string)}
+	n := &Notifier{
+		kv:    kv,
+		queue: make(chan alerts.AlertEvent, 2),
+		done:  make(chan struct{}),
+	}
+	defer close(n.done)
+
+	// Fill the queue
+	n.Notify(alerts.AlertEvent{Title: "1"})
+	n.Notify(alerts.AlertEvent{Title: "2"})
+	// Third should be dropped (non-blocking)
+	n.Notify(alerts.AlertEvent{Title: "3"})
+
+	if len(n.queue) != 2 {
+		t.Errorf("queue len = %d, want 2 (third should be dropped)", len(n.queue))
+	}
+}
+
+func TestRetryAfterFromErr(t *testing.T) {
+	cases := []struct {
+		err      string
+		wantSecs int
+		wantOK   bool
+	}{
+		{"api error 429: too many requests [retry_after=30]", 30, true},
+		{"api error 429: too many requests [retry_after=5]", 5, true},
+		{"api error 400: bad request", 0, false},
+		{"connection refused", 0, false},
+		{"", 0, false},
+	}
+	for _, tc := range cases {
+		var err error
+		if tc.err != "" {
+			err = fmt.Errorf("%s", tc.err)
+		}
+		dur, ok := retryAfterFromErr(err)
+		if ok != tc.wantOK {
+			t.Errorf("retryAfterFromErr(%q) ok = %v, want %v", tc.err, ok, tc.wantOK)
+		}
+		if ok && dur != time.Duration(tc.wantSecs)*time.Second {
+			t.Errorf("retryAfterFromErr(%q) dur = %v, want %ds", tc.err, dur, tc.wantSecs)
+		}
+	}
+}