server_webpush.go 6.0 KB

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