server_webpush.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. package server
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "regexp"
  7. "strings"
  8. "github.com/SherClockHolmes/webpush-go"
  9. "heckel.io/ntfy/v2/log"
  10. "heckel.io/ntfy/v2/user"
  11. )
  12. const (
  13. webPushTopicSubscribeLimit = 50
  14. )
  15. var (
  16. webPushAllowedEndpointsPatterns = []string{
  17. "https://*.google.com/",
  18. "https://*.googleapis.com/",
  19. "https://*.mozilla.com/",
  20. "https://*.mozaws.net/",
  21. "https://*.windows.com/",
  22. "https://*.microsoft.com/",
  23. "https://*.apple.com/",
  24. }
  25. webPushAllowedEndpointsRegex *regexp.Regexp
  26. )
  27. func init() {
  28. for i, pattern := range webPushAllowedEndpointsPatterns {
  29. webPushAllowedEndpointsPatterns[i] = strings.ReplaceAll(strings.ReplaceAll(pattern, ".", "\\."), "*", ".+")
  30. }
  31. allPatterns := fmt.Sprintf("^(%s)", strings.Join(webPushAllowedEndpointsPatterns, "|"))
  32. webPushAllowedEndpointsRegex = regexp.MustCompile(allPatterns)
  33. }
  34. func (s *Server) handleWebPushUpdate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  35. req, err := readJSONWithLimit[apiWebPushUpdateSubscriptionRequest](r.Body, jsonBodyBytesLimit, false)
  36. if err != nil || req.Endpoint == "" || req.P256dh == "" || req.Auth == "" {
  37. return errHTTPBadRequestWebPushSubscriptionInvalid
  38. } else if !webPushAllowedEndpointsRegex.MatchString(req.Endpoint) {
  39. return errHTTPBadRequestWebPushEndpointUnknown
  40. } else if len(req.Topics) > webPushTopicSubscribeLimit {
  41. return errHTTPBadRequestWebPushTopicCountTooHigh
  42. }
  43. topics, err := s.topicsFromIDs(req.Topics...)
  44. if err != nil {
  45. return err
  46. }
  47. if s.userManager != nil {
  48. u := v.User()
  49. for _, t := range topics {
  50. if err := s.userManager.Authorize(u, t.ID, user.PermissionRead); err != nil {
  51. logvr(v, r).With(t).Err(err).Debug("Access to topic %s not authorized", t.ID)
  52. return errHTTPForbidden.With(t)
  53. }
  54. }
  55. }
  56. if err := s.webPush.UpsertSubscription(req.Endpoint, req.Auth, req.P256dh, v.MaybeUserID(), v.IP(), req.Topics); err != nil {
  57. return err
  58. }
  59. return s.writeJSON(w, newSuccessResponse())
  60. }
  61. func (s *Server) handleWebPushDelete(w http.ResponseWriter, r *http.Request, _ *visitor) error {
  62. req, err := readJSONWithLimit[apiWebPushUpdateSubscriptionRequest](r.Body, jsonBodyBytesLimit, false)
  63. if err != nil || req.Endpoint == "" {
  64. return errHTTPBadRequestWebPushSubscriptionInvalid
  65. }
  66. if err := s.webPush.RemoveSubscriptionsByEndpoint(req.Endpoint); err != nil {
  67. return err
  68. }
  69. return s.writeJSON(w, newSuccessResponse())
  70. }
  71. func (s *Server) publishToWebPushEndpoints(v *visitor, m *message) {
  72. subscriptions, err := s.webPush.SubscriptionsForTopic(m.Topic)
  73. if err != nil {
  74. logvm(v, m).Err(err).With(v, m).Warn("Unable to publish web push messages")
  75. return
  76. }
  77. log.Tag(tagWebPush).With(v, m).Debug("Publishing web push message to %d subscribers", len(subscriptions))
  78. payload, err := json.Marshal(newWebPushPayload(fmt.Sprintf("%s/%s", s.config.BaseURL, m.Topic), m))
  79. if err != nil {
  80. log.Tag(tagWebPush).Err(err).With(v, m).Warn("Unable to marshal expiring payload")
  81. return
  82. }
  83. for _, subscription := range subscriptions {
  84. if err := s.sendWebPushNotification(subscription, payload, v, m); err != nil {
  85. log.Tag(tagWebPush).Err(err).With(v, m, subscription).Warn("Unable to publish web push message")
  86. }
  87. }
  88. }
  89. func (s *Server) pruneAndNotifyWebPushSubscriptions() {
  90. if s.config.WebPushPublicKey == "" {
  91. return
  92. }
  93. go func() {
  94. if err := s.pruneAndNotifyWebPushSubscriptionsInternal(); err != nil {
  95. log.Tag(tagWebPush).Err(err).Warn("Unable to prune or notify web push subscriptions")
  96. }
  97. }()
  98. }
  99. func (s *Server) pruneAndNotifyWebPushSubscriptionsInternal() error {
  100. // Expire old subscriptions
  101. if err := s.webPush.RemoveExpiredSubscriptions(s.config.WebPushExpiryDuration); err != nil {
  102. return err
  103. }
  104. // Notify subscriptions that will expire soon
  105. subscriptions, err := s.webPush.SubscriptionsExpiring(s.config.WebPushExpiryWarningDuration)
  106. if err != nil {
  107. return err
  108. } else if len(subscriptions) == 0 {
  109. return nil
  110. }
  111. payload, err := json.Marshal(newWebPushSubscriptionExpiringPayload())
  112. if err != nil {
  113. return err
  114. }
  115. warningSent := make([]*webPushSubscription, 0)
  116. for _, subscription := range subscriptions {
  117. if err := s.sendWebPushNotification(subscription, payload); err != nil {
  118. log.Tag(tagWebPush).Err(err).With(subscription).Warn("Unable to publish expiry imminent warning")
  119. continue
  120. }
  121. warningSent = append(warningSent, subscription)
  122. }
  123. if err := s.webPush.MarkExpiryWarningSent(warningSent); err != nil {
  124. return err
  125. }
  126. log.Tag(tagWebPush).Debug("Expired old subscriptions and published %d expiry imminent warnings", len(subscriptions))
  127. return nil
  128. }
  129. func (s *Server) sendWebPushNotification(sub *webPushSubscription, message []byte, contexters ...log.Contexter) error {
  130. log.Tag(tagWebPush).With(sub).With(contexters...).Debug("Sending web push message")
  131. payload := &webpush.Subscription{
  132. Endpoint: sub.Endpoint,
  133. Keys: webpush.Keys{
  134. Auth: sub.Auth,
  135. P256dh: sub.P256dh,
  136. },
  137. }
  138. resp, err := webpush.SendNotification(message, payload, &webpush.Options{
  139. Subscriber: s.config.WebPushEmailAddress,
  140. VAPIDPublicKey: s.config.WebPushPublicKey,
  141. VAPIDPrivateKey: s.config.WebPushPrivateKey,
  142. Urgency: webpush.UrgencyHigh, // iOS requires this to ensure delivery
  143. TTL: int(s.config.CacheDuration.Seconds()),
  144. })
  145. if err != nil {
  146. log.Tag(tagWebPush).With(sub).With(contexters...).Err(err).Debug("Unable to publish web push message, removing endpoint")
  147. if err := s.webPush.RemoveSubscriptionsByEndpoint(sub.Endpoint); err != nil {
  148. return err
  149. }
  150. return err
  151. }
  152. if (resp.StatusCode < 200 || resp.StatusCode > 299) && resp.StatusCode != 429 {
  153. log.Tag(tagWebPush).With(sub).With(contexters...).Field("response_code", resp.StatusCode).Debug("Unable to publish web push message, unexpected response")
  154. if err := s.webPush.RemoveSubscriptionsByEndpoint(sub.Endpoint); err != nil {
  155. return err
  156. }
  157. return errHTTPInternalErrorWebPushUnableToPublish.With(sub).With(contexters...)
  158. }
  159. return nil
  160. }