server_firebase.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. "content_type": m.ContentType,
  147. "encoding": m.Encoding,
  148. }
  149. if len(m.Actions) > 0 {
  150. actions, err := json.Marshal(m.Actions)
  151. if err != nil {
  152. return nil, err
  153. }
  154. data["actions"] = string(actions)
  155. }
  156. if m.Attachment != nil {
  157. data["attachment_name"] = m.Attachment.Name
  158. data["attachment_type"] = m.Attachment.Type
  159. data["attachment_size"] = fmt.Sprintf("%d", m.Attachment.Size)
  160. data["attachment_expires"] = fmt.Sprintf("%d", m.Attachment.Expires)
  161. data["attachment_url"] = m.Attachment.URL
  162. }
  163. apnsConfig = createAPNSAlertConfig(m, data)
  164. } else {
  165. // If anonymous read for a topic is not allowed, we cannot send the message along
  166. // via Firebase. Instead, we send a "poll_request" message, asking the client to poll.
  167. data = map[string]string{
  168. "id": m.ID,
  169. "time": fmt.Sprintf("%d", m.Time),
  170. "event": pollRequestEvent,
  171. "topic": m.Topic,
  172. }
  173. // TODO Handle APNS?
  174. }
  175. }
  176. var androidConfig *messaging.AndroidConfig
  177. if m.Priority >= 4 {
  178. androidConfig = &messaging.AndroidConfig{
  179. Priority: "high",
  180. }
  181. }
  182. return maybeTruncateFCMMessage(&messaging.Message{
  183. Topic: m.Topic,
  184. Data: data,
  185. Android: androidConfig,
  186. APNS: apnsConfig,
  187. }), nil
  188. }
  189. // maybeTruncateFCMMessage performs best-effort truncation of FCM messages.
  190. // The docs say the limit is 4000 characters, but during testing it wasn't quite clear
  191. // what fields matter; so we're just capping the serialized JSON to 4000 bytes.
  192. func maybeTruncateFCMMessage(m *messaging.Message) *messaging.Message {
  193. s, err := json.Marshal(m)
  194. if err != nil {
  195. return m
  196. }
  197. if len(s) > fcmMessageLimit {
  198. over := len(s) - fcmMessageLimit + 16 // = len("truncated":"1",), sigh ...
  199. message, ok := m.Data["message"]
  200. if ok && len(message) > over {
  201. m.Data["truncated"] = "1"
  202. m.Data["message"] = message[:len(message)-over]
  203. }
  204. }
  205. return m
  206. }
  207. // createAPNSAlertConfig creates an APNS config for iOS notifications that show up as an alert (only relevant for iOS).
  208. // We must set the Alert struct ("alert"), and we need to set MutableContent ("mutable-content"), so the Notification Service
  209. // Extension in iOS can modify the message.
  210. func createAPNSAlertConfig(m *message, data map[string]string) *messaging.APNSConfig {
  211. apnsData := make(map[string]any)
  212. for k, v := range data {
  213. apnsData[k] = v
  214. }
  215. return &messaging.APNSConfig{
  216. Payload: &messaging.APNSPayload{
  217. CustomData: apnsData,
  218. Aps: &messaging.Aps{
  219. MutableContent: true,
  220. Alert: &messaging.ApsAlert{
  221. Title: m.Title,
  222. Body: maybeTruncateAPNSBodyMessage(m.Message),
  223. },
  224. },
  225. },
  226. }
  227. }
  228. // createAPNSBackgroundConfig creates an APNS config for a silent background message (only relevant for iOS). Apple only
  229. // allows us to send 2-3 of these notifications per hour, and delivery not guaranteed. We use this only for the ~poll
  230. // topic, which triggers the iOS app to poll all topics for changes.
  231. //
  232. // See https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_background_updates_to_your_app
  233. func createAPNSBackgroundConfig(data map[string]string) *messaging.APNSConfig {
  234. apnsData := make(map[string]any)
  235. for k, v := range data {
  236. apnsData[k] = v
  237. }
  238. return &messaging.APNSConfig{
  239. Headers: map[string]string{
  240. "apns-push-type": "background",
  241. "apns-priority": "5",
  242. },
  243. Payload: &messaging.APNSPayload{
  244. Aps: &messaging.Aps{
  245. ContentAvailable: true,
  246. },
  247. CustomData: apnsData,
  248. },
  249. }
  250. }
  251. // maybeTruncateAPNSBodyMessage truncates the body for APNS.
  252. //
  253. // The "body" of the push notification can contain the entire message, which would count doubly for the overall length
  254. // of the APNS payload. I set a limit of 100 characters before truncating the notification "body" with ellipsis.
  255. // The message would not be changed (unless truncated for being too long). Note: if the payload is too large (>4KB),
  256. // APNS will simply reject / discard the notification, meaning it will never arrive on the iOS device.
  257. func maybeTruncateAPNSBodyMessage(s string) string {
  258. if len(s) >= fcmApnsBodyMessageLimit {
  259. over := len(s) - fcmApnsBodyMessageLimit + 3 // len("...")
  260. return s[:len(s)-over] + "..."
  261. }
  262. return s
  263. }