Skip to content

Latest commit

 

History

History
270 lines (221 loc) · 20 KB

push-notifications.md

File metadata and controls

270 lines (221 loc) · 20 KB

Push notifications

Pushes go out from backend/shared/src/mobile.ts: sendWebNotifications (Web Push, to the service worker) and sendMobileNotifications (FCM, to both the Android and the iOS app). buildPushMessage builds the FCM message for one token, with the block of the token's platform only (push_subscriptions_mobile.platform): android for an Android token, apns for an iOS one. See "Size caps and failed sends" for why.

Every payload has a collapseKey. For most pushes (search alerts, connection interests, profile access, spaces, referrals) it means "replace": a new push with the same key takes the place of the one showing, on all three platforms (Android collapseKey and notification tag, APNs apns-collapse-id, web tag).

Private messages

A private message is different: it is sent with conversation: true, and its key is the conversation's tag (messageNotificationTag(channelId) in common/src/notifications.ts, channel-<id>). The messages of a conversation then show together, the way messaging apps do, instead of each replacing the last. The merge is done on the device, by each platform's own means:

  • Android: one notification per conversation, to which each new message is appended (NotificationCompat.MessagingStyle). The server sends the message as a data-only FCM message (data.style = 'messaging', plus the tag, sender name, text and endpoint), which FCM does not display. CompassMessagingService receives it and MessageNotifications.show appends it to the notification of that tag, or starts a new one if none is showing. The service extends the push plugin's own service (which the manifest removes), so pushNotificationReceived and token refreshes still reach the JS side. No FCM collapseKey, so the messages queued while the phone was offline all arrive.
  • iOS: each message is its own notification, without apns-collapse-id, and carries the tag as its thread-id, so iOS stacks a conversation's notifications together. Server-side only.
  • Web: the service worker (web/public/service-worker.js) reads the notification already showing for the tag and shows a new one with the last five messages, one per line (each cut short once there is more than one), with renotify so it alerts again. The texts are kept in the notification's data. A click brings forward a tab already on the conversation, or opens one, and only once: Chrome on a Linux desktop has been seen to send one click per update of the notification.

As before, nothing is shown while the app is on screen: the unread badge updates live.

Old Android builds

An Android build without CompassMessagingService shows nothing for a data-only push. So the server has to know, per token, whether the app draws message notifications itself: that is push_subscriptions_mobile.renders_message_notifications. web/lib/service/native-push.ts sends rendersMessageNotifications: true with the token when window.AndroidBridge.rendersMessageNotifications() exists and returns true. It asks the native code rather than assuming it, since a dev build can load a newer web bundle than its native code. The flag is saved on every launch, so a row flips once the app is updated.

Every token without the flag (older Android builds, iOS) keeps getting a notification message for each private message, which on Android replaces the previous one of the conversation, as before.

The Messages channel

On Android, message notifications are posted on their own channel, messages ("Messages"), at IMPORTANCE_HIGH, so a new message shows as a heads-up banner over whatever app is open rather than only as a status-bar icon. The other pushes stay on FCM's default channel. The channel shows in the app's notification settings, where a member can lower it. Android never lets an app raise the importance of a channel that already exists, so changing it later means a new channel id.

The sender's photo and conversation shortcuts

On Android a message notification shows the sender's photo, the way WhatsApp does. The server adds the sender's avatarUrl to the push data as avatar, only for tokens whose app draws message notifications. Avatars.load (in CompassMessagingService) downloads it with a 3-second timeout. It then scales it down to 256 px, crops it square and caches it in the app's cache directory by URL, so a conversation costs one download. When the photo can't be had in time, the message shows without it.

The photo becomes the icon of the sender's Person. Each conversation also gets a long-lived dynamic shortcut (id = the conversation's tag), linked to the notification with setShortcutInfo. From Android 11 the shortcut is what makes it a conversation notification: the photo large with the Compass icon as a badge in its corner, in the Conversations section above other notifications, and the option to make it a priority conversation. The photo is laid out as an adaptive icon, so the phone gives it its own icon shape. Below Android 11 the photo is the large icon instead.

Android posts a notification linked to a shortcut only after checking the shortcut, which takes a moment. So MessageNotifications.show waits (up to 2 seconds, on the service's background thread) until the notification is listed as active: otherwise a second message arriving right behind the first, as the messages queued while the phone was offline do, would not find it and would replace it.

The shortcuts also show on a long press of the app icon and in the share sheet, so sign-out removes them and the cached photos (clearConversations in web/lib/service/message-notifications.ts, through AndroidBridge). A shortcut opens the same intent as a tap on the notification, so it lands on the conversation.

iOS and the web don't show the photo: iOS would need a Notification Service Extension and the Communication Notifications capability, and the web notification keeps the app icon.

Replying from the notification

On Android, a message notification has up to two actions:

  • Reply, on every message whose push carried a reply token: the member types in the notification and the message is sent without opening the app.
  • View profile, on the first message of a 1:1 conversation: opens the app on the sender's profile.

There is no "Mark as read". iOS and the web have neither action (see "iOS later" below).

The reply token

The native code has no sign-in: the member's Firebase session lives in the WebView. So the server puts a token in the push instead, and the reply is sent with it.

  • Made per device in buildPushMessage (backend/shared/src/mobile.ts), only for a token whose app draws message notifications (renders_message_notifications), and only when the payload names a replyChannelId. notifyOtherUserInChannelIfInactive sets it on every message of a 1:1 conversation except a kind decline, which closes the conversation.
  • backend/shared/src/push-reply-token.ts: v1.<payload>.<signature>, base64url. The payload binds the receiver's user id, the channel id, the device's push_subscriptions_mobile.id and an expiry (REPLY_TOKEN_TTL_MS, 7 days); the signature is an HMAC-SHA256 with PUSH_REPLY_TOKEN_SECRET, compared in constant time. A new token comes with each message, so a conversation that keeps going keeps a fresh one.
  • PUSH_REPLY_TOKEN_SECRET is a Secret Manager secret, listed in common/src/secrets.ts as optional: a deployment without it starts, sends every push as before without a token, and refuses every reply. The notification then has no Reply action. A value shorter than 32 characters counts as missing. Generate one with openssl rand -base64 48, in each project (prod compass-130ba, dev compass-57c3c); a local API reads it from .env or .env.local. Changing it invalidates every token sent before.
  • The device's subscription row is deleted at sign-out (delete-subscription), and with it every token of that device. A token for another device, member or conversation does not verify or does not match.

The push data (strings, as all FCM data) gains replyToken and, on the first message of a 1:1 conversation, profilePath (/<username>, the profile page). The text in data.body is cut for these devices to 2000 UTF-8 bytes at a word, with an ellipsis (truncateNotificationText), so the data fits FCM's 4 KB with the token and the photo's URL. iOS tokens, Android builds without renders_message_notifications and web push get neither key (push-message.unit.test.ts asserts it).

The endpoint

reply-from-notification (backend/api/src/reply-from-notification.ts), POST {token, text}, not authed, rate limited by IP like every unauthenticated endpoint. It verifies the token, checks that the device's subscription row still exists for that member, turns the text into the document the app's composer makes on a phone (one paragraph per line, an empty paragraph for an empty line), and sends it through sendPrivateUserMessage (create-private-user-message.ts), the same code as create-private-user-message: the length limit, account found, assertCanWrite, suspicious ids, blocks, the first-message rules, the closed-conversation lock and channel membership. The conversation is marked seen for the replier in the same transaction as the message (insertPrivateMessage with markSeen), as set-channel-seen-time would.

Refusals are HTTP errors with a message, which the app tells apart from a network failure:

Status When
401 The token is malformed, tampered with, signed with another secret or expired, or the device signed out (context says which)
400 The text is empty or too long
403 A ban, a suspicious account, a block, a closed conversation, or no longer a member
429 The rate limit

On the phone

MessageNotifications adds the actions; NotificationReplyReceiver (not exported) receives a reply and NotificationReplies posts it.

  • Reply is a RemoteInput action with a mutable PendingIntent (required on Android 12+ for the text to be added), one request code per conversation, shown only when the notification has a token. setAllowGeneratedReplies(false) (androidx.core 1.15.0 defaults it to true) and setAllowSystemGeneratedContextualActions(false) on the notification: no suggested-reply chips.
  • View profile opens the app the way a tap does (openIntent, so pushNotificationActionPerformed navigates to its endpoint), with the profile path as the endpoint and its own request code.
  • The notification is posted again for each message, so the endpoint, the FCM message id, the latest token and the profile path are kept in its extras (MessageNotifications.State). A later message keeps the profile path of the first one, and its own token replaces the kept one.
  • The receiver uses goAsync and sends on a background thread, with a 7-second deadline for the whole request (DNS included), within the receiver's ~10 s.
  • The API host is the one the web bundle uses: when the app loads a dev server (server.url in the synced Capacitor config, from NEXT_PUBLIC_LOCAL_ANDROID or NEXT_PUBLIC_WEBVIEW_DEV_PHONE), the same host at port 8088 over http, as LOCAL_BACKEND_DOMAIN; otherwise https://api.compassmeet.com, since the bundled export is always built for prod (build_web_view.sh). Never from the push.
  • Sent: the notification is posted again silently (setOnlyAlertOnce) with the reply appended as the member's own message ("You"), which also stops the spinner Android shows on a reply. Its actions stay.
  • Not sent: the notification is posted again, silently, with the text kept as the member's message, prefixed "Not sent: " when the API refused it, or "May not have been sent: " when no answer came in time or the phone is offline (the reply may then have arrived). A tap opens the conversation, where it can be written again. If the notification was dismissed while the reply was on its way, a sent reply posts nothing and one not sent brings the notification back, so the text is never dropped. The texts are in android/app/src/main/res/values/strings.xml, English only like the channel name.
  • Sign-out (clearConversations) now also removes the conversations' notifications and cancels their Reply intents, on top of the shortcuts and photos.

Old builds

An Android build from before this ignores replyToken and profilePath: its notification is the one it drew before, without actions. The server cannot tell such a build from a new one (both send rendersMessageNotifications), so it gets the token anyway; that costs some 150 bytes of the push. iOS gets nothing new.

iOS later

The server side is ready for iOS: the iOS app would read the token from the push's data (where the tag already is), and post to the same endpoint from a notification action (UNTextInputNotificationAction in a category). What it needs first is the token in iOS pushes: buildPushMessage adds it only for tokens with renders_message_notifications, so iOS needs its own capability flag saved with the token (as rendersMessageNotifications is today) and the aps.category naming the actions. Neither exists yet.

Size caps and failed sends

FCM refuses a message over 4096 bytes with messaging/invalid-argument, "Message is too large. The maximum is 4K (4096 bytes).", and a push service refuses a Web Push payload over about the same. Until December 2026 every FCM message carried both platform blocks with the whole text, uncut in the apns alert, and a failed send with invalid-argument deleted the device's subscription. So a message of more than about 2300 bytes to an Android app that draws its notifications (with the photo URL and the reply token beside it), or about 4.8 KB to any other device, failed; the device's row was deleted, and the next messages had no device to go to until the app was opened again. That is what a 10 KB message did on 2026-12-04.

What FCM measures, from validate-only sends (send(message, true)) to a real Android token: UTF-8 bytes, with no compression; the data together with each platform's block, each block checked on its own; and the apns block is checked even when the token is an Android one. It is not the JSON as sent: a block passed with some 4.85 KB of text alone, and a message with both blocks at that size passed too.

So, in backend/shared/src/mobile.ts:

  • One block per token. getMobileSubscriptionsFromDB reads platform, and buildPushMessage sends an Android token the android block only and an iOS token the apns block only. A token whose app draws message notifications is an Android one even when the platform is not passed (only the Android app saves that flag); otherwise, with the platform unknown, both blocks go as before.

  • Every text capped, cut at a word with an ellipsis (truncateNotificationText), on every push type:

    What Cap (UTF-8 bytes)
    The title (the sender's name for a message) 120 (MAX_TITLE_BYTES)
    The text the system draws: iOS alert, FCM-drawn Android, web push 1000 (MAX_ALERT_BODY_BYTES)
    The text the Android app draws (data.body) 2000 (MAX_RENDERED_BODY_BYTES)
    The photo URL (avatarUrl) and imageUrl; the profile path 512; 128, left out when longer

    A name is at most 30 UTF-16 units (90 bytes) since cleanDisplayName; the cap catches older names. A link is sent whole or not at all. Web push goes through boundWebPushPayload in sendWebNotifications, which applies the same caps to the JSON the callers pass and returns it unchanged when it fits. The service worker keeps the last five texts of a conversation in the notification's data, so the cap also bounds what it stores. A text within the caps is sent exactly as before.

  • With every optional field at its longest, a 10 KB text and a 250-character token, the whole JSON stays under 4096 bytes for each target (about 3.4 KB at most for the app that draws its notifications, 3.9 KB with the platform unknown): stricter than what FCM measures. push-message.unit.test.ts asserts it.

When a subscription is deleted (isTokenGoneError): only when FCM says the token itself is gone or invalid. registration-token-not-registered (the app uninstalled, the token replaced, or a token FCM never issued), the legacy invalid-registration-token, and invalid-argument whose message is "The registration token is not a valid FCM registration token" (a malformed token, a raw APNs token among them). FCM gives invalid-argument both to a bad token and to a bad message, and firebase-admin keeps only the message text, so the text is what tells them apart; should FCM reword it, such rows are kept. Every other failure keeps the row and is logged (log.warn('Firebase push failed', …)): a message too large, third-party-auth-error (the APNs key), mismatched-credential (another Firebase project's token, or the server's own credentials), FCM unavailable. An orphan row costs one failed send per push; a row deleted wrongly costs the member every notification until the app saves its token again. Web Push subscriptions are deleted only on HTTP 404 or 410, as before.

Clearing on read

Since a conversation's notifications are merged or stacked, the messages already read would otherwise stay in them and come back with the next message. When a conversation is marked seen (setAsSeen in web/pages/messages/[channelId].tsx), dismissMessageNotifications (web/lib/service/message-notifications.ts) removes its notifications: on Android by notification tag, on iOS by the tag in the push's data (the only part iOS exposes), on the web through the service worker's getNotifications({tag}).

Testing

  • Server message (including who gets the sender's photo, the reply token and the profile path, the block of each platform, the caps, the 4096-byte budget of each target, and the web push payload): backend/shared/tests/unit/push-message.unit.test.ts.
  • When a subscription is deleted, with firebase-admin mocked, and a 10 KB message followed by a short one to an Android phone: backend/shared/tests/unit/push-subscription-removal.unit.test.ts.
  • Reply token (valid, expired, tampered, another device, no secret): backend/shared/tests/unit/push-reply-token.unit.test.ts.
  • Reply endpoint (success, each refusal) and the text's document: backend/api/tests/unit/reply-from-notification.unit.test.ts; what the push of a message carries and the seen time written with a reply: backend/api/tests/unit/message-push-actions.unit.test.ts.
  • Service worker merge: web/tests/unit/service-worker-push.test.ts.
  • Android notification (merging, channel, photo, conversation shortcut, the actions, a reply appended or kept as not sent, sign-out): android/app/src/androidTest/.../MessageNotificationsTest.java, on an emulator or device, from android/: ./gradlew :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.compassconnections.app.MessageNotificationsTest.
  • A real reply end to end: a debug build on a phone signed in to a local API (docs/app-updates.md, "A real Android build against a local API"), PUSH_REPLY_TOKEN_SECRET in .env, the app in the background, a message sent to that member from another account in a browser. Reply from the notification; the message appears in the browser and the conversation is no longer unread on the phone. To see the failure, reply with the phone in airplane mode ("May not have been sent"), or after closing the conversation from the browser ("Not sent").