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