push.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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. if err := push.ValidateEndpoint(body.Endpoint); err != nil {
  61. writeError(w, http.StatusBadRequest, "invalid_endpoint", err.Error())
  62. return
  63. }
  64. created, err := push.UpsertSubscription(s.db, push.Subscription{
  65. Endpoint: body.Endpoint,
  66. Auth: body.Keys.Auth,
  67. P256dh: body.Keys.P256dh,
  68. UserAgent: r.UserAgent(),
  69. CreatedAt: db.NowMS(),
  70. UserID: me.ID,
  71. Language: body.Language,
  72. })
  73. if err != nil {
  74. writeError(w, http.StatusInternalServerError, "push_unavailable", "no se pudo guardar la suscripción")
  75. return
  76. }
  77. status := http.StatusOK
  78. if created {
  79. status = http.StatusCreated
  80. }
  81. writeJSON(w, status, map[string]any{"ok": true})
  82. }
  83. // handlePushUnsubscribe (POST): baja por endpoint, SOLO de suscripciones del
  84. // usuario autenticado (#1334). 204 siempre (idempotente: dar de baja dos
  85. // veces no es error; la app no bloquea la baja local).
  86. func (s *server) handlePushUnsubscribe(w http.ResponseWriter, r *http.Request) {
  87. me := auth.UserFromContext(r.Context())
  88. if me == nil {
  89. writeError(w, http.StatusUnauthorized, "unauthorized")
  90. return
  91. }
  92. var body struct {
  93. Endpoint string `json:"endpoint"`
  94. }
  95. if st := readJSONBody(w, r, &body); st != 0 {
  96. writeBodyError(w, st, "invalid_body", "endpoint es obligatorio")
  97. return
  98. }
  99. if strings.TrimSpace(body.Endpoint) == "" {
  100. writeError(w, http.StatusBadRequest, "invalid_body", "endpoint es obligatorio")
  101. return
  102. }
  103. if _, err := s.db.Exec(
  104. "DELETE FROM push_subscriptions WHERE endpoint = ? AND user_id = ?",
  105. body.Endpoint, me.ID,
  106. ); err != nil {
  107. writeError(w, http.StatusInternalServerError, "push_unavailable", "no se pudo borrar la suscripción")
  108. return
  109. }
  110. w.WriteHeader(http.StatusNoContent)
  111. }