server_firebase.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. //go:build !nofirebase
  2. package server
  3. import (
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. firebase "firebase.google.com/go/v4"
  8. "firebase.google.com/go/v4/messaging"
  9. "fmt"
  10. "google.golang.org/api/option"
  11. "heckel.io/ntfy/v2/user"
  12. "heckel.io/ntfy/v2/util"
  13. "strings"
  14. )
  15. const (
  16. // FirebaseAvailable is a constant used to indicate that Firebase support is available.
  17. // It can be disabled with the 'nofirebase' build tag.
  18. FirebaseAvailable = true
  19. fcmMessageLimit = 4000
  20. fcmApnsBodyMessageLimit = 100
  21. )
  22. var (
  23. errFirebaseQuotaExceeded = errors.New("quota exceeded for Firebase messages to topic")
  24. errFirebaseTemporarilyBanned = errors.New("visitor temporarily banned from using Firebase")
  25. )
  26. // firebaseClient is a generic client that formats and sends messages to Firebase.
  27. // The actual Firebase implementation is implemented in firebaseSenderImpl, to make it testable.
  28. type firebaseClient struct {
  29. sender firebaseSender
  30. auther user.Auther
  31. }
  32. func newFirebaseClient(sender firebaseSender, auther user.Auther) *firebaseClient {
  33. return &firebaseClient{
  34. sender: sender,
  35. auther: auther,
  36. }
  37. }
  38. func (c *firebaseClient) Send(v *visitor, m *message) error {
  39. if !v.FirebaseAllowed() {
  40. return errFirebaseTemporarilyBanned
  41. }
  42. fbm, err := toFirebaseMessage(m, c.auther)
  43. if err != nil {
  44. return err
  45. }
  46. ev := logvm(v, m).Tag(tagFirebase)
  47. if ev.IsTrace() {
  48. ev.Field("firebase_message", util.MaybeMarshalJSON(fbm)).Trace("Firebase message")
  49. }
  50. err = c.sender.Send(fbm)
  51. if errors.Is(err, errFirebaseQuotaExceeded) {
  52. logvm(v, m).
  53. Tag(tagFirebase).
  54. Err(err).
  55. Warn("Firebase quota exceeded (likely for topic), temporarily denying Firebase access to visitor")
  56. v.FirebaseTemporarilyDeny()
  57. }
  58. return err
  59. }
  60. // firebaseSender is an interface that represents a client that can send to Firebase Cloud Messaging.
  61. // In tests, this can be implemented with a mock.
  62. type firebaseSender interface {
  63. // Send sends a message to Firebase, or returns an error. It returns errFirebaseQuotaExceeded
  64. // if a rate limit has reached.
  65. Send(m *messaging.Message) error
  66. }
  67. // firebaseSenderImpl is a firebaseSender that actually talks to Firebase
  68. type firebaseSenderImpl struct {
  69. client *messaging.Client
  70. }
  71. func newFirebaseSender(credentialsFile string) (firebaseSender, error) {
  72. fb, err := firebase.NewApp(context.Background(), nil, option.WithCredentialsFile(credentialsFile))
  73. if err != nil {
  74. return nil, err
  75. }
  76. client, err := fb.Messaging(context.Background())
  77. if err != nil {
  78. return nil, err
  79. }
  80. return &firebaseSenderImpl{
  81. client: client,
  82. }, nil
  83. }
  84. func (c *firebaseSenderImpl) Send(m *messaging.Message) error {
  85. _, err := c.client.Send(context.Background(), m)
  86. if err != nil && messaging.IsQuotaExceeded(err) {
  87. return errFirebaseQuotaExceeded
  88. }
  89. return err
  90. }
  91. // toFirebaseMessage converts a message to a Firebase message.
  92. //
  93. // Normal messages ("message"):
  94. // - For Android, we can receive data messages from Firebase and process them as code, so we just send all fields
  95. // in the "data" attribute. In the Android app, we then turn those into a notification and display it.
  96. // - On iOS, we are not allowed to receive data-only messages, so we build messages with an "alert" (with title and
  97. // message), and still send the rest of the data along in the "aps" attribute. We can then locally modify the
  98. // message in the Notification Service Extension.
  99. //
  100. // Keepalive messages ("keepalive"):
  101. // - On Android, we subscribe to the "~control" topic, which is used to restart the foreground service (if it died,
  102. // e.g. after an app update). We send these keepalive messages regularly (see Config.FirebaseKeepaliveInterval).
  103. // - On iOS, we subscribe to the "~poll" topic, which is used to poll all topics regularly. This is because iOS
  104. // does not allow any background or scheduled activity at all.
  105. //
  106. // Poll request messages ("poll_request"):
  107. // - Normal messages are turned into poll request messages if anonymous users are not allowed to read the message.
  108. // On Android, this will trigger the app to poll the topic and thereby displaying new messages.
  109. // - If UpstreamBaseURL is set, messages are forwarded as poll requests to an upstream server and then forwarded
  110. // to Firebase here. This is mainly for iOS to support self-hosted servers.
  111. func toFirebaseMessage(m *message, auther user.Auther) (*messaging.Message, error) {
  112. var data map[string]string // Mostly matches https://ntfy.sh/docs/subscribe/api/#json-message-format
  113. var apnsConfig *messaging.APNSConfig
  114. switch m.Event {
  115. case keepaliveEvent, openEvent:
  116. data = map[string]string{
  117. "id": m.ID,
  118. "time": fmt.Sprintf("%d", m.Time),
  119. "event": m.Event,
  120. "topic": m.Topic,
  121. }
  122. apnsConfig = createAPNSBackgroundConfig(data)
  123. case pollRequestEvent:
  124. data = map[string]string{
  125. "id": m.ID,
  126. "time": fmt.Sprintf("%d", m.Time),
  127. "event": m.Event,
  128. "topic": m.Topic,
  129. "message": newMessageBody,
  130. "poll_id": m.PollID,
  131. }
  132. apnsConfig = createAPNSAlertConfig(m, data)
  133. case messageEvent:
  134. if auther != nil {
  135. // If "anonymous read" for a topic is not allowed, we cannot send the message along
  136. // via Firebase. Instead, we send a "poll_request" message, asking the client to poll.
  137. //
  138. // The data map needs to contain all the fields for it to function properly. If not all
  139. // fields are set, the iOS app fails to decode the message.
  140. //
  141. // See https://github.com/binwiederhier/ntfy/pull/1345
  142. if err := auther.Authorize(nil, m.Topic, user.PermissionRead); err != nil {
  143. m = toPollRequest(m)
  144. }
  145. }
  146. data = map[string]string{
  147. "id": m.ID,
  148. "time": fmt.Sprintf("%d", m.Time),
  149. "event": m.Event,
  150. "topic": m.Topic,
  151. "priority": fmt.Sprintf("%d", m.Priority),
  152. "tags": strings.Join(m.Tags, ","),
  153. "click": m.Click,
  154. "icon": m.Icon,
  155. "title": m.Title,
  156. "message": m.Message,
  157. "content_type": m.ContentType,
  158. "encoding": m.Encoding,
  159. }
  160. if len(m.Actions) > 0 {
  161. actions, err := json.Marshal(m.Actions)
  162. if err != nil {
  163. return nil, err
  164. }
  165. data["actions"] = string(actions)
  166. }
  167. if m.Attachment != nil {
  168. data["attachment_name"] = m.Attachment.Name
  169. data["attachment_type"] = m.Attachment.Type
  170. data["attachment_size"] = fmt.Sprintf("%d", m.Attachment.Size)
  171. data["attachment_expires"] = fmt.Sprintf("%d", m.Attachment.Expires)
  172. data["attachment_url"] = m.Attachment.URL
  173. }
  174. if m.PollID != "" {
  175. data["poll_id"] = m.PollID
  176. }
  177. apnsConfig = createAPNSAlertConfig(m, data)
  178. }
  179. var androidConfig *messaging.AndroidConfig
  180. if m.Priority >= 4 {
  181. androidConfig = &messaging.AndroidConfig{
  182. Priority: "high",
  183. }
  184. }
  185. return maybeTruncateFCMMessage(&messaging.Message{
  186. Topic: m.Topic,
  187. Data: data,
  188. Android: androidConfig,
  189. APNS: apnsConfig,
  190. }), nil
  191. }
  192. // maybeTruncateFCMMessage performs best-effort truncation of FCM messages.
  193. // The docs say the limit is 4000 characters, but during testing it wasn't quite clear
  194. // what fields matter; so we're just capping the serialized JSON to 4000 bytes.
  195. func maybeTruncateFCMMessage(m *messaging.Message) *messaging.Message {
  196. s, err := json.Marshal(m)
  197. if err != nil {
  198. return m
  199. }
  200. if len(s) > fcmMessageLimit {
  201. over := len(s) - fcmMessageLimit + 16 // = len("truncated":"1",), sigh ...
  202. message, ok := m.Data["message"]
  203. if ok && len(message) > over {
  204. m.Data["truncated"] = "1"
  205. m.Data["message"] = message[:len(message)-over]
  206. }
  207. }
  208. return m
  209. }
  210. // createAPNSAlertConfig creates an APNS config for iOS notifications that show up as an alert (only relevant for iOS).
  211. // We must set the Alert struct ("alert"), and we need to set MutableContent ("mutable-content"), so the Notification Service
  212. // Extension in iOS can modify the message.
  213. func createAPNSAlertConfig(m *message, data map[string]string) *messaging.APNSConfig {
  214. apnsData := make(map[string]any)
  215. for k, v := range data {
  216. apnsData[k] = v
  217. }
  218. return &messaging.APNSConfig{
  219. Payload: &messaging.APNSPayload{
  220. CustomData: apnsData,
  221. Aps: &messaging.Aps{
  222. MutableContent: true,
  223. Alert: &messaging.ApsAlert{
  224. Title: m.Title,
  225. Body: maybeTruncateAPNSBodyMessage(m.Message),
  226. },
  227. },
  228. },
  229. }
  230. }
  231. // createAPNSBackgroundConfig creates an APNS config for a silent background message (only relevant for iOS). Apple only
  232. // allows us to send 2-3 of these notifications per hour, and delivery not guaranteed. We use this only for the ~poll
  233. // topic, which triggers the iOS app to poll all topics for changes.
  234. //
  235. // See https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_background_updates_to_your_app
  236. func createAPNSBackgroundConfig(data map[string]string) *messaging.APNSConfig {
  237. apnsData := make(map[string]any)
  238. for k, v := range data {
  239. apnsData[k] = v
  240. }
  241. return &messaging.APNSConfig{
  242. Headers: map[string]string{
  243. "apns-push-type": "background",
  244. "apns-priority": "5",
  245. },
  246. Payload: &messaging.APNSPayload{
  247. Aps: &messaging.Aps{
  248. ContentAvailable: true,
  249. },
  250. CustomData: apnsData,
  251. },
  252. }
  253. }
  254. // maybeTruncateAPNSBodyMessage truncates the body for APNS.
  255. //
  256. // The "body" of the push notification can contain the entire message, which would count doubly for the overall length
  257. // of the APNS payload. I set a limit of 100 characters before truncating the notification "body" with ellipsis.
  258. // The message would not be changed (unless truncated for being too long). Note: if the payload is too large (>4KB),
  259. // APNS will simply reject / discard the notification, meaning it will never arrive on the iOS device.
  260. func maybeTruncateAPNSBodyMessage(s string) string {
  261. if len(s) >= fcmApnsBodyMessageLimit {
  262. over := len(s) - fcmApnsBodyMessageLimit + 3 // len("...")
  263. return s[:len(s)-over] + "..."
  264. }
  265. return s
  266. }
  267. // toPollRequest converts a message to a poll request message.
  268. //
  269. // This empties all the fields that are not needed for a poll request and just sets the required fields,
  270. // most importantly, the PollID.
  271. func toPollRequest(m *message) *message {
  272. pr := newPollRequestMessage(m.Topic, m.ID)
  273. pr.ID = m.ID
  274. pr.Time = m.Time
  275. pr.Priority = m.Priority // Keep priority
  276. pr.ContentType = m.ContentType
  277. pr.Encoding = m.Encoding
  278. return pr
  279. }