push.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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}} → 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/db"
  11. "github.com/gnacho/netpulse/server-go/internal/push"
  12. )
  13. // Límites defensivos de longitud (los push endpoints reales son < 1 KB).
  14. const (
  15. maxEndpointLen = 2048
  16. maxPushKeyLen = 512
  17. )
  18. // handlePushVapidKey (GET): clave pública VAPID para pushManager.subscribe().
  19. // Asegura el par en kv si faltara (main ya lo genera en el arranque).
  20. func (s *server) handlePushVapidKey(w http.ResponseWriter, _ *http.Request) {
  21. pub, _, err := push.EnsureVAPIDKeys(s.db)
  22. if err != nil {
  23. writeError(w, http.StatusInternalServerError, "push_unavailable", "no se pudo obtener la clave VAPID")
  24. return
  25. }
  26. writeJSON(w, http.StatusOK, map[string]any{"key": pub})
  27. }
  28. type pushSubscribeBody struct {
  29. Endpoint string `json:"endpoint"`
  30. Keys struct {
  31. Auth string `json:"auth"`
  32. P256dh string `json:"p256dh"`
  33. } `json:"keys"`
  34. }
  35. // handlePushSubscribe (POST): upsert por endpoint. 201 si es nueva, 200 si
  36. // actualizó una existente (la app solo exige res.ok).
  37. func (s *server) handlePushSubscribe(w http.ResponseWriter, r *http.Request) {
  38. var body pushSubscribeBody
  39. if st := readJSONBody(w, r, &body); st != 0 {
  40. writeBodyError(w, st, "invalid_body", "JSON esperado: {endpoint, keys:{auth, p256dh}}")
  41. return
  42. }
  43. body.Endpoint = strings.TrimSpace(body.Endpoint)
  44. if body.Endpoint == "" || len(body.Endpoint) > maxEndpointLen ||
  45. body.Keys.Auth == "" || len(body.Keys.Auth) > maxPushKeyLen ||
  46. body.Keys.P256dh == "" || len(body.Keys.P256dh) > maxPushKeyLen {
  47. writeError(w, http.StatusBadRequest, "invalid_body", "endpoint, keys.auth y keys.p256dh son obligatorios")
  48. return
  49. }
  50. created, err := push.UpsertSubscription(s.db, push.Subscription{
  51. Endpoint: body.Endpoint,
  52. Auth: body.Keys.Auth,
  53. P256dh: body.Keys.P256dh,
  54. UserAgent: r.UserAgent(),
  55. CreatedAt: db.NowMS(),
  56. })
  57. if err != nil {
  58. writeError(w, http.StatusInternalServerError, "push_unavailable", "no se pudo guardar la suscripción")
  59. return
  60. }
  61. status := http.StatusOK
  62. if created {
  63. status = http.StatusCreated
  64. }
  65. writeJSON(w, status, map[string]any{"ok": true})
  66. }
  67. // handlePushUnsubscribe (POST): baja por endpoint. 204 siempre (idempotente:
  68. // dar de baja dos veces no es error; la app no bloquea la baja local).
  69. func (s *server) handlePushUnsubscribe(w http.ResponseWriter, r *http.Request) {
  70. var body struct {
  71. Endpoint string `json:"endpoint"`
  72. }
  73. if st := readJSONBody(w, r, &body); st != 0 {
  74. writeBodyError(w, st, "invalid_body", "endpoint es obligatorio")
  75. return
  76. }
  77. if strings.TrimSpace(body.Endpoint) == "" {
  78. writeError(w, http.StatusBadRequest, "invalid_body", "endpoint es obligatorio")
  79. return
  80. }
  81. if err := push.DeleteSubscription(s.db, body.Endpoint); err != nil {
  82. writeError(w, http.StatusInternalServerError, "push_unavailable", "no se pudo borrar la suscripción")
  83. return
  84. }
  85. w.WriteHeader(http.StatusNoContent)
  86. }