server_firebase.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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.WithAuthCredentialsFile(option.ServiceAccount, 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 messageDeleteEvent, messageClearEvent:
  134. data = map[string]string{
  135. "id": m.ID,
  136. "time": fmt.Sprintf("%d", m.Time),
  137. "event": m.Event,
  138. "topic": m.Topic,
  139. "sequence_id": m.SequenceID,
  140. }
  141. apnsConfig = createAPNSBackgroundConfig(data)
  142. case messageEvent:
  143. if auther != nil {
  144. // If "anonymous read" for a topic is not allowed, we cannot send the message along
  145. // via Firebase. Instead, we send a "poll_request" message, asking the client to poll.
  146. //
  147. // The data map needs to contain all the fields for it to function properly. If not all
  148. // fields are set, the iOS app fails to decode the message.
  149. //
  150. // See https://github.com/binwiederhier/ntfy/pull/1345
  151. if err := auther.Authorize(nil, m.Topic, user.PermissionRead); err != nil {
  152. m = toPollRequest(m)
  153. }
  154. }
  155. data = map[string]string{
  156. "id": m.ID,
  157. "time": fmt.Sprintf("%d", m.Time),
  158. "event": m.Event,
  159. "topic": m.Topic,
  160. "sequence_id": m.SequenceID,
  161. "priority": fmt.Sprintf("%d", m.Priority),
  162. "tags": strings.Join(m.Tags, ","),
  163. "click": m.Click,
  164. "icon": m.Icon,
  165. "title": m.Title,
  166. "message": m.Message,
  167. "content_type": m.ContentType,
  168. "encoding": m.Encoding,
  169. }
  170. if len(m.Actions) > 0 {
  171. actions, err := json.Marshal(m.Actions)
  172. if err != nil {
  173. return nil, err
  174. }
  175. data["actions"] = string(actions)
  176. }
  177. if m.Attachment != nil {
  178. data["attachment_name"] = m.Attachment.Name
  179. data["attachment_type"] = m.Attachment.Type
  180. data["attachment_size"] = fmt.Sprintf("%d", m.Attachment.Size)
  181. data["attachment_expires"] = fmt.Sprintf("%d", m.Attachment.Expires)
  182. data["attachment_url"] = m.Attachment.URL
  183. }
  184. if m.PollID != "" {
  185. data["poll_id"] = m.PollID
  186. }
  187. apnsConfig = createAPNSAlertConfig(m, data)
  188. }
  189. var androidConfig *messaging.AndroidConfig
  190. if m.Priority >= 4 {
  191. androidConfig = &messaging.AndroidConfig{
  192. Priority: "high",
  193. }
  194. }
  195. return maybeTruncateFCMMessage(&messaging.Message{
  196. Topic: m.Topic,
  197. Data: data,
  198. Android: androidConfig,
  199. APNS: apnsConfig,
  200. }), nil
  201. }
  202. // maybeTruncateFCMMessage performs best-effort truncation of FCM messages.
  203. // The docs say the limit is 4000 characters, but during testing it wasn't quite clear
  204. // what fields matter; so we're just capping the serialized JSON to 4000 bytes.
  205. func maybeTruncateFCMMessage(m *messaging.Message) *messaging.Message {
  206. s, err := json.Marshal(m)
  207. if err != nil {
  208. return m
  209. }
  210. if len(s) > fcmMessageLimit {
  211. over := len(s) - fcmMessageLimit + 16 // = len("truncated":"1",), sigh ...
  212. message, ok := m.Data["message"]
  213. if ok && len(message) > over {
  214. m.Data["truncated"] = "1"
  215. m.Data["message"] = message[:len(message)-over]
  216. }
  217. }
  218. return m
  219. }
  220. // createAPNSAlertConfig creates an APNS config for iOS notifications that show up as an alert (only relevant for iOS).
  221. // We must set the Alert struct ("alert"), and we need to set MutableContent ("mutable-content"), so the Notification Service
  222. // Extension in iOS can modify the message.
  223. func createAPNSAlertConfig(m *message, data map[string]string) *messaging.APNSConfig {
  224. apnsData := make(map[string]any)
  225. for k, v := range data {
  226. apnsData[k] = v
  227. }
  228. return &messaging.APNSConfig{
  229. Payload: &messaging.APNSPayload{
  230. CustomData: apnsData,
  231. Aps: &messaging.Aps{
  232. MutableContent: true,
  233. Alert: &messaging.ApsAlert{
  234. Title: m.Title,
  235. Body: maybeTruncateAPNSBodyMessage(m.Message),
  236. },
  237. },
  238. },
  239. }
  240. }
  241. // createAPNSBackgroundConfig creates an APNS config for a silent background message (only relevant for iOS). Apple only
  242. // allows us to send 2-3 of these notifications per hour, and delivery not guaranteed. We use this only for the ~poll
  243. // topic, which triggers the iOS app to poll all topics for changes.
  244. //
  245. // See https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_background_updates_to_your_app
  246. func createAPNSBackgroundConfig(data map[string]string) *messaging.APNSConfig {
  247. apnsData := make(map[string]any)
  248. for k, v := range data {
  249. apnsData[k] = v
  250. }
  251. return &messaging.APNSConfig{
  252. Headers: map[string]string{
  253. "apns-push-type": "background",
  254. "apns-priority": "5",
  255. },
  256. Payload: &messaging.APNSPayload{
  257. Aps: &messaging.Aps{
  258. ContentAvailable: true,
  259. },
  260. CustomData: apnsData,
  261. },
  262. }
  263. }
  264. // maybeTruncateAPNSBodyMessage truncates the body for APNS.
  265. //
  266. // The "body" of the push notification can contain the entire message, which would count doubly for the overall length
  267. // of the APNS payload. I set a limit of 100 characters before truncating the notification "body" with ellipsis.
  268. // The message would not be changed (unless truncated for being too long). Note: if the payload is too large (>4KB),
  269. // APNS will simply reject / discard the notification, meaning it will never arrive on the iOS device.
  270. func maybeTruncateAPNSBodyMessage(s string) string {
  271. if len(s) >= fcmApnsBodyMessageLimit {
  272. over := len(s) - fcmApnsBodyMessageLimit + 3 // len("...")
  273. return s[:len(s)-over] + "..."
  274. }
  275. return s
  276. }
  277. // toPollRequest converts a message to a poll request message.
  278. //
  279. // This empties all the fields that are not needed for a poll request and just sets the required fields,
  280. // most importantly, the PollID.
  281. func toPollRequest(m *message) *message {
  282. pr := newPollRequestMessage(m.Topic, m.ID)
  283. pr.ID = m.ID
  284. pr.Time = m.Time
  285. pr.Priority = m.Priority // Keep priority
  286. pr.ContentType = m.ContentType
  287. pr.Encoding = m.Encoding
  288. return pr
  289. }