server_firebase.go 9.3 KB

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