notifier.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. // notifier.go — push.Notifier: implementa alerts.Notifier (SPEC-PUSH §1).
  2. // Notify NUNCA bloquea al llamador (el motor de alertas lo invoca desde el
  3. // ciclo de sondeo): encola el evento y un worker único lo drena, enviando a
  4. // todas las suscripciones con timeout de 10 s por envío. 404/410 del push
  5. // service → suscripción muerta → se purga de la DB.
  6. package push
  7. import (
  8. "context"
  9. "encoding/json"
  10. "fmt"
  11. "io"
  12. "log/slog"
  13. "net/http"
  14. "net/url"
  15. "strings"
  16. "sync"
  17. "time"
  18. webpush "github.com/SherClockHolmes/webpush-go"
  19. "github.com/gnacho/netpulse/server-go/internal/alertlang"
  20. "github.com/gnacho/netpulse/server-go/internal/alerts"
  21. "github.com/gnacho/netpulse/server-go/internal/db"
  22. )
  23. const (
  24. // queueCap acota la cola: ráfagas de urgentes no pueden crecer sin
  25. // límite; si se llena se descarta (el panel ya muestra la alerta).
  26. queueCap = 64
  27. // sendTimeout por envío individual (SPEC-PUSH §1: 10 s).
  28. sendTimeout = 10 * time.Second
  29. // ttl de la notificación en el push service (1 h: si el móvil está
  30. // apagado más tiempo, la alerta ya es historia).
  31. ttlSeconds = 3600
  32. // fallbackSubject: sub del JWT cuando no hay URL pública https ni subject
  33. // configurado. Nunca "netpulse@localhost", que Apple rechaza con 403
  34. // BadJwtToken (#1974). La página del proyecto es un https: valido.
  35. fallbackSubject = "https://github.com/gnacho/netpulse"
  36. )
  37. // SubjectFor devuelve el sub del JWT VAPID a partir del subject configurado
  38. // (NETPULSE_VAPID_SUBJECT) o, si no hay, de NETPULSE_PUBLIC_URL. Solo se acepta
  39. // una URL https: o un mailto: con dominio real: un mailto:localhost devuelve
  40. // 403 BadJwtToken en Apple (issue #1974).
  41. func SubjectFor(configured, publicURL string) string {
  42. if s := validSubject(configured); s != "" {
  43. return s
  44. }
  45. if s := validSubject(publicURL); s != "" {
  46. return s
  47. }
  48. return fallbackSubject
  49. }
  50. func validSubject(raw string) string {
  51. s := strings.TrimSpace(raw)
  52. if s == "" {
  53. return ""
  54. }
  55. if strings.HasPrefix(strings.ToLower(s), "mailto:") {
  56. addr := strings.TrimSpace(s[len("mailto:"):])
  57. at := strings.LastIndex(addr, "@")
  58. if at <= 0 || at == len(addr)-1 {
  59. return ""
  60. }
  61. domain := strings.ToLower(strings.TrimSpace(addr[at+1:]))
  62. if domain == "" || domain == "localhost" || !strings.Contains(domain, ".") {
  63. return ""
  64. }
  65. return s
  66. }
  67. u, err := url.Parse(s)
  68. if err != nil || u.Scheme != "https" || u.Host == "" {
  69. return ""
  70. }
  71. return s
  72. }
  73. // payload es el JSON cifrado que recibe el Service Worker (contrato con
  74. // app/src/sw.ts: {title, body, category, severity, url, tag, hint}).
  75. // Desde #689 viaja además {type, vars}: el slug estable del tipo de alerta y
  76. // sus variables de interpolación, para que el SW traduzca la notificación al
  77. // idioma del dispositivo. Los literales title/body/hint se mantienen como
  78. // fallback (SW antiguo o tipo sin clave i18n).
  79. type payload struct {
  80. Title string `json:"title"`
  81. Body string `json:"body"`
  82. Type string `json:"type,omitempty"`
  83. Vars map[string]string `json:"vars,omitempty"`
  84. Category string `json:"category"`
  85. Severity string `json:"severity"`
  86. URL string `json:"url"`
  87. Tag string `json:"tag"` // alertId: dedup nativo del navegador
  88. Hint string `json:"hint,omitempty"` // sugerencia accionable (issue #310)
  89. }
  90. // Notifier implementa alerts.Notifier con entrega asíncrona.
  91. type Notifier struct {
  92. db *db.DB
  93. pub string
  94. priv string
  95. subject string
  96. client *http.Client
  97. ch chan alerts.AlertEvent
  98. done chan struct{} // cerrado en Close: Notify posterior es no-op
  99. once sync.Once
  100. wg sync.WaitGroup
  101. }
  102. // NewNotifier crea el Notifier y arranca su worker. pub/priv son el par
  103. // VAPID de EnsureVAPIDKeys.
  104. func NewNotifier(d *db.DB, pub, priv string) *Notifier {
  105. return newNotifier(d, pub, priv, newSafeHTTPClient())
  106. }
  107. // NewNotifierWithClient permite inyectar un cliente HTTP. Se usa en tests que
  108. // necesitan alcanzar un push service TLS local; produccion usa NewNotifier.
  109. func NewNotifierWithClient(d *db.DB, pub, priv string, client *http.Client) *Notifier {
  110. if client == nil {
  111. client = newSafeHTTPClient()
  112. }
  113. return newNotifier(d, pub, priv, client)
  114. }
  115. func newNotifier(d *db.DB, pub, priv string, client *http.Client) *Notifier {
  116. n := &Notifier{
  117. db: d,
  118. pub: pub,
  119. priv: priv,
  120. subject: fallbackSubject,
  121. client: client,
  122. ch: make(chan alerts.AlertEvent, queueCap),
  123. done: make(chan struct{}),
  124. }
  125. n.wg.Add(1)
  126. go n.worker()
  127. return n
  128. }
  129. // SetSubject fija el sub del JWT VAPID (ver SubjectFor). Sin llamada se usa
  130. // fallbackSubject, que es un https: valido para los push services.
  131. func (n *Notifier) SetSubject(subject string) {
  132. if s := validSubject(subject); s != "" {
  133. n.subject = s
  134. }
  135. }
  136. // Notify encola el evento y vuelve inmediatamente (nunca bloquea el poll).
  137. // Si la cola está llena descarta con aviso: el evento ya está en /api/alerts.
  138. func (n *Notifier) Notify(ev alerts.AlertEvent) {
  139. select {
  140. case <-n.done:
  141. return
  142. case n.ch <- ev:
  143. default:
  144. slog.Warn("push: queue full, notification dropped", "alertId", ev.ID, "title", ev.Title)
  145. }
  146. }
  147. // Close para el worker y espera al envío en curso (acotado por sendTimeout).
  148. func (n *Notifier) Close() {
  149. n.once.Do(func() {
  150. close(n.done)
  151. n.wg.Wait()
  152. })
  153. }
  154. func (n *Notifier) worker() {
  155. defer n.wg.Done()
  156. for {
  157. select {
  158. case <-n.done:
  159. return
  160. case ev := <-n.ch:
  161. n.sendAll(ev)
  162. }
  163. }
  164. }
  165. // payloadJSON serializa el cuerpo de la notificación (SPEC-PUSH §1).
  166. func payloadJSON(ev alerts.AlertEvent) ([]byte, error) {
  167. return json.Marshal(payload{
  168. Title: ev.Title,
  169. Body: ev.Description,
  170. Type: ev.Type,
  171. Vars: ev.Vars,
  172. Category: ev.Category,
  173. Severity: ev.Severity,
  174. URL: "/alerts",
  175. Tag: ev.ID,
  176. Hint: ev.Hint,
  177. })
  178. }
  179. // sendAll envía el evento a TODAS las suscripciones y purga las muertas.
  180. // El payload se serializa POR suscripción (#1334: idioma por suscriptor).
  181. func (n *Notifier) sendAll(ev alerts.AlertEvent) {
  182. subs, err := ListSubscriptions(n.db)
  183. if err != nil {
  184. slog.Error("push: could not list subscriptions", "alertId", ev.ID, "error", err)
  185. return
  186. }
  187. for _, s := range subs {
  188. // #1334: la suscripción recuerda el idioma efectivo de la UI en su
  189. // alta; se compone el payload en ESE idioma (catálogo alertlang, el
  190. // mismo de la traducción global). Sin idioma (legacy): el payload ya
  191. // llega traducido al idioma global por alertlang.Notifier.
  192. evs := ev
  193. if s.Language != "" {
  194. evs = alertlang.LocalizeLang(ev, s.Language)
  195. }
  196. body, err := payloadJSON(evs)
  197. if err != nil {
  198. slog.Error("push: payload no serializable", "alertId", ev.ID, "error", err)
  199. continue
  200. }
  201. n.sendOne(evs, body, s)
  202. }
  203. }
  204. // wireSubject adapta el subject al formato de webpush-go: la libreria antepone
  205. // "mailto:" salvo que empiece por "https:", asi que un mailto: explicito se
  206. // pasa sin prefijo para no acabar en "mailto:mailto:...".
  207. func wireSubject(s string) string {
  208. if strings.HasPrefix(strings.ToLower(s), "mailto:") {
  209. return s[len("mailto:"):]
  210. }
  211. return s
  212. }
  213. func pushReason(body []byte) string {
  214. s := strings.TrimSpace(string(body))
  215. s = strings.Join(strings.Fields(s), " ")
  216. if len(s) > 300 {
  217. s = s[:300]
  218. }
  219. return s
  220. }
  221. // push entrega un payload ya cifrado a una suscripción y devuelve el status y
  222. // el cuerpo del push service. Lo comparten el envio de alertas (sendOne) y el
  223. // boton de prueba (#1973), para que la prueba use el camino real.
  224. func (n *Notifier) push(s Subscription, body []byte) (int, []byte, error) {
  225. resp, err := webpush.SendNotificationWithContext(context.Background(), body,
  226. &webpush.Subscription{
  227. Endpoint: s.Endpoint,
  228. Keys: webpush.Keys{Auth: s.Auth, P256dh: s.P256dh},
  229. },
  230. &webpush.Options{
  231. HTTPClient: n.client,
  232. Subscriber: wireSubject(n.subject),
  233. VAPIDPublicKey: n.pub,
  234. VAPIDPrivateKey: n.priv,
  235. TTL: ttlSeconds,
  236. })
  237. if err != nil {
  238. return 0, nil, err
  239. }
  240. defer resp.Body.Close()
  241. rb, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<16))
  242. return resp.StatusCode, rb, nil
  243. }
  244. // TestResult es el resultado de un envio de prueba (#1973).
  245. type TestResult struct {
  246. Status int `json:"status,omitempty"`
  247. Reason string `json:"reason,omitempty"`
  248. Expired bool `json:"expired,omitempty"`
  249. Error string `json:"error,omitempty"`
  250. }
  251. // SendTest manda una notificacion de prueba a UNA suscripcion por el mismo
  252. // camino que las alertas reales y devuelve el resultado en vez de descartarlo.
  253. // Un 404/410 purga la suscripcion, igual que sendOne.
  254. func (n *Notifier) SendTest(s Subscription) TestResult {
  255. if err := ValidateEndpoint(s.Endpoint); err != nil {
  256. return TestResult{Error: err.Error()}
  257. }
  258. body, err := payloadJSON(testEvent(s.Language))
  259. if err != nil {
  260. return TestResult{Error: "payload no serializable"}
  261. }
  262. status, respBody, err := n.push(s, body)
  263. if err != nil {
  264. return TestResult{Error: err.Error()}
  265. }
  266. res := TestResult{Status: status, Reason: pushReason(respBody)}
  267. if status == http.StatusNotFound || status == http.StatusGone {
  268. res.Expired = true
  269. if err := DeleteSubscription(n.db, s.Endpoint); err != nil {
  270. slog.Error("push: could not purge dead subscription", "endpoint", s.Endpoint, "error", err)
  271. }
  272. }
  273. return res
  274. }
  275. // testEvent compone el aviso de prueba en el idioma de la suscripcion.
  276. func testEvent(lang string) alerts.AlertEvent {
  277. title, body := "Test notification", "Push notifications work on this device."
  278. switch lang {
  279. case "es":
  280. title, body = "Notificacion de prueba", "Las notificaciones push funcionan en este dispositivo."
  281. case "ru":
  282. title, body = "Тестовое уведомление", "Push-уведомления работают на этом устройстве."
  283. }
  284. return alerts.AlertEvent{
  285. ID: fmt.Sprintf("push-test-%d", time.Now().UnixNano()),
  286. Category: alerts.CatSystem,
  287. Severity: "info",
  288. Title: title,
  289. Description: body,
  290. }
  291. }
  292. func (n *Notifier) sendOne(ev alerts.AlertEvent, body []byte, s Subscription) {
  293. if err := ValidateEndpoint(s.Endpoint); err != nil {
  294. slog.Warn("push: endpoint rechazado", "endpoint", s.Endpoint, "error", err)
  295. return
  296. }
  297. status, respBody, err := n.push(s, body)
  298. if err != nil {
  299. slog.Warn("push: send failed", "alertId", ev.ID, "endpoint", s.Endpoint, "error", err)
  300. return
  301. }
  302. if status == http.StatusNotFound || status == http.StatusGone {
  303. // Suscripción muerta (expirada o dada de baja): purgar (SPEC-PUSH §1).
  304. if err := DeleteSubscription(n.db, s.Endpoint); err != nil {
  305. slog.Error("push: could not purge dead subscription", "endpoint", s.Endpoint, "error", err)
  306. }
  307. slog.Info("push: subscription purged", "endpoint", s.Endpoint, "status", status)
  308. return
  309. }
  310. if status >= 400 {
  311. // #1974: el cuerpo del push service dice la causa (Apple devuelve
  312. // {"reason":"BadJwtToken"}). Sin el, un 403 pelado no diagnostica nada.
  313. slog.Warn("push: push service returned an error", "alertId", ev.ID, "endpoint", s.Endpoint,
  314. "status", status, "reason", pushReason(respBody))
  315. }
  316. }