server_firebase.go 9.3 KB

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