server_webpush.go 5.9 KB

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