server_web_push.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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. }
  31. if !webPushEndpointAllowRegex.MatchString(payload.BrowserSubscription.Endpoint) {
  32. return errHTTPBadRequestWebPushEndpointUnknown
  33. }
  34. if len(payload.Topics) > webPushTopicSubscribeLimit {
  35. return errHTTPBadRequestWebPushTopicCountTooHigh
  36. }
  37. u := v.User()
  38. topics, err := s.topicsFromIDs(payload.Topics...)
  39. if err != nil {
  40. return err
  41. }
  42. if s.userManager != nil {
  43. for _, t := range topics {
  44. if err := s.userManager.Authorize(u, t.ID, user.PermissionRead); err != nil {
  45. logvr(v, r).With(t).Err(err).Debug("Access to topic %s not authorized", t.ID)
  46. return errHTTPForbidden.With(t)
  47. }
  48. }
  49. }
  50. if err := s.webPush.UpdateSubscriptions(payload.Topics, v.MaybeUserID(), payload.BrowserSubscription); err != nil {
  51. return err
  52. }
  53. return s.writeJSON(w, newSuccessResponse())
  54. }
  55. func (s *Server) publishToWebPushEndpoints(v *visitor, m *message) {
  56. subscriptions, err := s.webPush.SubscriptionsForTopic(m.Topic)
  57. if err != nil {
  58. logvm(v, m).Err(err).Warn("Unable to publish web push messages")
  59. return
  60. }
  61. for i, xi := range subscriptions {
  62. go func(i int, sub webPushSubscription) {
  63. ctx := log.Context{"endpoint": sub.BrowserSubscription.Endpoint, "username": sub.UserID, "topic": m.Topic, "message_id": m.ID}
  64. s.sendWebPushNotification(newWebPushPayload(fmt.Sprintf("%s/%s", s.config.BaseURL, m.Topic), *m), &sub, &ctx)
  65. }(i, xi)
  66. }
  67. }
  68. func (s *Server) expireOrNotifyOldSubscriptions() {
  69. subscriptions, err := s.webPush.ExpireAndGetExpiringSubscriptions(s.config.WebPushExpiryWarningDuration, s.config.WebPushExpiryDuration)
  70. if err != nil {
  71. log.Tag(tagWebPush).Err(err).Warn("Unable to publish expiry imminent warning")
  72. return
  73. }
  74. for i, xi := range subscriptions {
  75. go func(i int, sub webPushSubscription) {
  76. ctx := log.Context{"endpoint": sub.BrowserSubscription.Endpoint}
  77. s.sendWebPushNotification(newWebPushSubscriptionExpiringPayload(), &sub, &ctx)
  78. }(i, xi)
  79. }
  80. log.Tag(tagWebPush).Debug("Expired old subscriptions and published %d expiry imminent warnings", len(subscriptions))
  81. }
  82. func (s *Server) sendWebPushNotification(payload any, sub *webPushSubscription, ctx *log.Context) {
  83. jsonPayload, err := json.Marshal(payload)
  84. if err != nil {
  85. log.Tag(tagWebPush).Err(err).Fields(*ctx).Debug("Unable to publish web push message")
  86. return
  87. }
  88. resp, err := webpush.SendNotification(jsonPayload, &sub.BrowserSubscription, &webpush.Options{
  89. Subscriber: s.config.WebPushEmailAddress,
  90. VAPIDPublicKey: s.config.WebPushPublicKey,
  91. VAPIDPrivateKey: s.config.WebPushPrivateKey,
  92. // Deliverability on iOS isn't great with lower urgency values,
  93. // and thus we can't really map lower ntfy priorities to lower urgency values
  94. Urgency: webpush.UrgencyHigh,
  95. })
  96. if err != nil {
  97. log.Tag(tagWebPush).Err(err).Fields(*ctx).Debug("Unable to publish web push message")
  98. if err := s.webPush.RemoveByEndpoint(sub.BrowserSubscription.Endpoint); err != nil {
  99. log.Tag(tagWebPush).Err(err).Fields(*ctx).Warn("Unable to expire subscription")
  100. }
  101. return
  102. }
  103. // May want to handle at least 429 differently, but for now treat all errors the same
  104. if !(200 <= resp.StatusCode && resp.StatusCode <= 299) {
  105. log.Tag(tagWebPush).Fields(*ctx).Field("response", resp).Debug("Unable to publish web push message")
  106. if err := s.webPush.RemoveByEndpoint(sub.BrowserSubscription.Endpoint); err != nil {
  107. log.Tag(tagWebPush).Err(err).Fields(*ctx).Warn("Unable to expire subscription")
  108. }
  109. return
  110. }
  111. }