push.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. // push.go — endpoints Web Push (SPEC-PUSH §1), tras auth de sesión:
  2. //
  3. // GET /api/push/vapid-key → {"key":"<base64url>"} (clave pública VAPID)
  4. // POST /api/push/subscribe {endpoint, keys:{auth,p256dh}, language} → 201/200 (upsert)
  5. // POST /api/push/unsubscribe {endpoint} → 204
  6. package httpapi
  7. import (
  8. "net/http"
  9. "strings"
  10. "github.com/gnacho/netpulse/server-go/internal/auth"
  11. "github.com/gnacho/netpulse/server-go/internal/db"
  12. "github.com/gnacho/netpulse/server-go/internal/push"
  13. )
  14. // Límites defensivos de longitud (los push endpoints reales son < 1 KB).
  15. const (
  16. maxEndpointLen = 2048
  17. maxPushKeyLen = 512
  18. )
  19. // handlePushVapidKey (GET): clave pública VAPID para pushManager.subscribe().
  20. // Asegura el par en kv si faltara (main ya lo genera en el arranque).
  21. func (s *server) handlePushVapidKey(w http.ResponseWriter, _ *http.Request) {
  22. pub, _, err := push.EnsureVAPIDKeys(s.db)
  23. if err != nil {
  24. writeError(w, http.StatusInternalServerError, "push_unavailable", "no se pudo obtener la clave VAPID")
  25. return
  26. }
  27. writeJSON(w, http.StatusOK, map[string]any{"key": pub})
  28. }
  29. type pushSubscribeBody struct {
  30. Endpoint string `json:"endpoint"`
  31. Keys struct {
  32. Auth string `json:"auth"`
  33. P256dh string `json:"p256dh"`
  34. } `json:"keys"`
  35. // Language (#1334): idioma efectivo de la UI en el alta (es|en); el push
  36. // se compone en ese idioma por suscriptor.
  37. Language string `json:"language"`
  38. }
  39. // handlePushSubscribe (POST): upsert por endpoint. 201 si es nueva, 200 si
  40. // actualizó una existente (la app solo exige res.ok).
  41. func (s *server) handlePushSubscribe(w http.ResponseWriter, r *http.Request) {
  42. me := auth.UserFromContext(r.Context())
  43. if me == nil {
  44. writeError(w, http.StatusUnauthorized, "unauthorized")
  45. return
  46. }
  47. var body pushSubscribeBody
  48. if st := readJSONBody(w, r, &body); st != 0 {
  49. writeBodyError(w, st, "invalid_body", "JSON esperado: {endpoint, keys:{auth, p256dh}, language}")
  50. return
  51. }
  52. body.Endpoint = strings.TrimSpace(body.Endpoint)
  53. if body.Endpoint == "" || len(body.Endpoint) > maxEndpointLen ||
  54. body.Keys.Auth == "" || len(body.Keys.Auth) > maxPushKeyLen ||
  55. body.Keys.P256dh == "" || len(body.Keys.P256dh) > maxPushKeyLen ||
  56. (body.Language != "es" && body.Language != "en") {
  57. writeError(w, http.StatusBadRequest, "invalid_body", "endpoint, keys.auth, keys.p256dh y language (es|en) son obligatorios")
  58. return
  59. }
  60. created, err := push.UpsertSubscription(s.db, push.Subscription{
  61. Endpoint: body.Endpoint,
  62. Auth: body.Keys.Auth,
  63. P256dh: body.Keys.P256dh,
  64. UserAgent: r.UserAgent(),
  65. CreatedAt: db.NowMS(),
  66. UserID: me.ID,
  67. Language: body.Language,
  68. })
  69. if err != nil {
  70. writeError(w, http.StatusInternalServerError, "push_unavailable", "no se pudo guardar la suscripción")
  71. return
  72. }
  73. status := http.StatusOK
  74. if created {
  75. status = http.StatusCreated
  76. }
  77. writeJSON(w, status, map[string]any{"ok": true})
  78. }
  79. // handlePushUnsubscribe (POST): baja por endpoint, SOLO de suscripciones del
  80. // usuario autenticado (#1334). 204 siempre (idempotente: dar de baja dos
  81. // veces no es error; la app no bloquea la baja local).
  82. func (s *server) handlePushUnsubscribe(w http.ResponseWriter, r *http.Request) {
  83. me := auth.UserFromContext(r.Context())
  84. if me == nil {
  85. writeError(w, http.StatusUnauthorized, "unauthorized")
  86. return
  87. }
  88. var body struct {
  89. Endpoint string `json:"endpoint"`
  90. }
  91. if st := readJSONBody(w, r, &body); st != 0 {
  92. writeBodyError(w, st, "invalid_body", "endpoint es obligatorio")
  93. return
  94. }
  95. if strings.TrimSpace(body.Endpoint) == "" {
  96. writeError(w, http.StatusBadRequest, "invalid_body", "endpoint es obligatorio")
  97. return
  98. }
  99. if _, err := s.db.Exec(
  100. "DELETE FROM push_subscriptions WHERE endpoint = ? AND user_id = ?",
  101. body.Endpoint, me.ID,
  102. ); err != nil {
  103. writeError(w, http.StatusInternalServerError, "push_unavailable", "no se pudo borrar la suscripción")
  104. return
  105. }
  106. w.WriteHeader(http.StatusNoContent)
  107. }