server_web_push.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. package server
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "regexp"
  7. "github.com/SherClockHolmes/webpush-go"
  8. "heckel.io/ntfy/log"
  9. "heckel.io/ntfy/user"
  10. )
  11. // test: https://regexr.com/7eqvl
  12. // example urls:
  13. //
  14. // https://android.googleapis.com/XYZ
  15. // https://fcm.googleapis.com/XYZ
  16. // https://updates.push.services.mozilla.com/XYZ
  17. // https://updates-autopush.stage.mozaws.net/XYZ
  18. // https://updates-autopush.dev.mozaws.net/XYZ
  19. // https://AAA.notify.windows.com/XYZ
  20. // https://AAA.push.apple.com/XYZ
  21. const (
  22. webPushEndpointAllowRegexStr = `^https:\/\/(android\.googleapis\.com|fcm\.googleapis\.com|updates\.push\.services\.mozilla\.com|updates-autopush\.stage\.mozaws\.net|updates-autopush\.dev\.mozaws\.net|.*\.notify\.windows\.com|.*\.push\.apple\.com)\/.*$`
  23. webPushTopicSubscribeLimit = 50
  24. )
  25. var webPushEndpointAllowRegex = regexp.MustCompile(webPushEndpointAllowRegexStr)
  26. func (s *Server) handleWebPushUpdate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  27. payload, err := readJSONWithLimit[webPushSubscriptionPayload](r.Body, jsonBodyBytesLimit, false)
  28. if err != nil || payload.BrowserSubscription.Endpoint == "" || payload.BrowserSubscription.Keys.P256dh == "" || payload.BrowserSubscription.Keys.Auth == "" {
  29. return errHTTPBadRequestWebPushSubscriptionInvalid
  30. } else if !webPushEndpointAllowRegex.MatchString(payload.BrowserSubscription.Endpoint) {
  31. return errHTTPBadRequestWebPushEndpointUnknown
  32. } else if len(payload.Topics) > webPushTopicSubscribeLimit {
  33. return errHTTPBadRequestWebPushTopicCountTooHigh
  34. }
  35. topics, err := s.topicsFromIDs(payload.Topics...)
  36. if err != nil {
  37. return err
  38. }
  39. if s.userManager != nil {
  40. u := v.User()
  41. for _, t := range topics {
  42. if err := s.userManager.Authorize(u, t.ID, user.PermissionRead); err != nil {
  43. logvr(v, r).With(t).Err(err).Debug("Access to topic %s not authorized", t.ID)
  44. return errHTTPForbidden.With(t)
  45. }
  46. }
  47. }
  48. if err := s.webPush.UpdateSubscriptions(payload.Topics, v.MaybeUserID(), payload.BrowserSubscription); err != nil {
  49. return err
  50. }
  51. return s.writeJSON(w, newSuccessResponse())
  52. }
  53. func (s *Server) publishToWebPushEndpoints(v *visitor, m *message) {
  54. subscriptions, err := s.webPush.SubscriptionsForTopic(m.Topic)
  55. if err != nil {
  56. logvm(v, m).Err(err).Warn("Unable to publish web push messages")
  57. return
  58. }
  59. payload, err := json.Marshal(newWebPushPayload(fmt.Sprintf("%s/%s", s.config.BaseURL, m.Topic), m))
  60. if err != nil {
  61. log.Tag(tagWebPush).Err(err).Warn("Unable to marshal expiring payload")
  62. return
  63. }
  64. for _, subscription := range subscriptions {
  65. ctx := log.Context{"endpoint": subscription.BrowserSubscription.Endpoint, "username": subscription.UserID, "topic": m.Topic, "message_id": m.ID}
  66. if err := s.sendWebPushNotification(payload, subscription, &ctx); err != nil {
  67. log.Tag(tagWebPush).Err(err).Fields(ctx).Warn("Unable to publish web push message")
  68. }
  69. }
  70. }
  71. // TODO this should return error
  72. // TODO rate limiting
  73. func (s *Server) expireOrNotifyOldSubscriptions() {
  74. subscriptions, err := s.webPush.ExpireAndGetExpiringSubscriptions(s.config.WebPushExpiryWarningDuration, s.config.WebPushExpiryDuration)
  75. if err != nil {
  76. log.Tag(tagWebPush).Err(err).Warn("Unable to publish expiry imminent warning")
  77. return
  78. } else if len(subscriptions) == 0 {
  79. return
  80. }
  81. payload, err := json.Marshal(newWebPushSubscriptionExpiringPayload())
  82. if err != nil {
  83. log.Tag(tagWebPush).Err(err).Warn("Unable to marshal expiring payload")
  84. return
  85. }
  86. go func() {
  87. for _, subscription := range subscriptions {
  88. ctx := log.Context{"endpoint": subscription.BrowserSubscription.Endpoint}
  89. if err := s.sendWebPushNotification(payload, &subscription, &ctx); err != nil {
  90. log.Tag(tagWebPush).Err(err).Fields(ctx).Warn("Unable to publish expiry imminent warning")
  91. }
  92. }
  93. }()
  94. log.Tag(tagWebPush).Debug("Expiring old subscriptions and published %d expiry imminent warnings", len(subscriptions))
  95. }
  96. func (s *Server) sendWebPushNotification(message []byte, sub *webPushSubscription, ctx *log.Context) error {
  97. resp, err := webpush.SendNotification(message, &sub.BrowserSubscription, &webpush.Options{
  98. Subscriber: s.config.WebPushEmailAddress,
  99. VAPIDPublicKey: s.config.WebPushPublicKey,
  100. VAPIDPrivateKey: s.config.WebPushPrivateKey,
  101. Urgency: webpush.UrgencyHigh, // iOS requires this to ensure delivery
  102. })
  103. if err != nil {
  104. log.Tag(tagWebPush).Err(err).Fields(*ctx).Debug("Unable to publish web push message, removing endpoint")
  105. if err := s.webPush.RemoveByEndpoint(sub.BrowserSubscription.Endpoint); err != nil {
  106. return err
  107. }
  108. return err
  109. }
  110. if (resp.StatusCode < 200 || resp.StatusCode > 299) && resp.StatusCode != 429 {
  111. log.Tag(tagWebPush).Fields(*ctx).Field("response_code", resp.StatusCode).Debug("Unable to publish web push message, unexpected response")
  112. if err := s.webPush.RemoveByEndpoint(sub.BrowserSubscription.Endpoint); err != nil {
  113. return err
  114. }
  115. return errHTTPInternalErrorWebPushUnableToPublish.Fields(*ctx)
  116. }
  117. return nil
  118. }