Push notifications: register_push_token / unregister_push_token
:::note Status
Android: implemented 2026-10-07. On 2026-11-12 dev moved from the
Firebase project crown-solar-energy-dev to cse-datalogger. The
backend reads the project ID from the service-account secret, so the move
needs no code change, only a new secret value and new app config files
(see One-time setup). Tokens issued by the old project
fail with SENDER_ID_MISMATCH and are deleted on first use; apps
re-register on their next connect. Web (browser) push for End Users: built 2026-11-10, not
deployed yet (cse-http-be ADR 0022, the web console's WP-1 to WP-8). It
needs cse-http-be's half deployed too, and is not yet verified end to end
in a browser or on a phone. iOS and browser tokens over the WebSocket:
enabled in code 2026-11-11, not deployed yet. The Android app,
the iOS app (com..solar.crowninverter) and the web app must be registered
in cse-datalogger. iOS delivery also needs the APNs authentication key
uploaded to that project (see
One-time setup). See
What is not covered.
:::
:::tip Implementing this in an app? This page is the reference: messages, payload, backend setup. The step-by-step guides are Push: mobile app guide (Flutter, Android and iOS) and Push: web app guide (in-app notifications now, browser push later). :::
When a device raises a new alert, the backend sends a push notification to every phone (Android and iOS) and every browser its owner has registered. That happens whether or not the app or console is open, through Firebase Cloud Messaging (FCM). The backend also sends the pushes the HTTP server asks for (work orders, report ready) to the browsers of the person concerned.
It is the same alert the Device alerts feed shows. The push is only ever sent after the alert has been saved, so tapping it always finds the alert in the app.
How it works
- Tokens come from two places:
- the mobile app (Android or iOS) or a browser registers its token over
the WebSocket with
register_push_token;ws-gatewaystores it inpush_tokensagainst theuserId; - the web console (and the app, if it uses it) can register with the
HTTP server instead (
POST /v1/me/push-tokens). The HTTP server projects each person's endpoints and preferences to TCP innotify.user.v1(notify_users,notify_endpoints).
- the mobile app (Android or iOS) or a browser registers its token over
the WebSocket with
- When the alert-processor saves a new alert, it publishes it to the
ALERT_EVENTSstream, as it already did for the live feed. - The push sender, a separate consumer inside the same
persistence-workerprocess, reads that event. It looks up the device's owner (devices.owner_user_id), the owner's preferences, and the owner's tokens from both places (one push per token, even when a phone is in both). - It writes the notification inbox entry first, then sends one FCM message per token.
- If FCM reports a token as dead, the sender deletes it, and for a token
the HTTP server projected publishes
notify.endpoint.invalid.v1so the HTTP server deletes it too.
Who gets push: End Users only (built 2026-11-13, not deployed). Alert
pushes go to the device's owner only, and only if that owner is an End
User. The HTTP server decides who is one: a person is push-eligible only
when every active membership they hold is an End User membership (the End
User role, a customer org, or their personal org). Anyone with an active
Super Admin, Administrator, Business or Installer membership gets
notify.user.v1 with pushEligible: false. TCP stores the
flag (notify_users.push_eligible, migration 0133) and then sends that
person nothing on any platform. That includes the Android, iOS and browser
tokens they registered over the WebSocket, which the HTTP server never
sees. The one exception is the HTTP server's membership notices (see
below). A membership or role change makes the HTTP server publish the
person's notify.user.v1 again, so eligibility follows within the bus
latency. An event without the field (from before this change) counts as
eligible. So does a person the HTTP server never projected: after its
reconciliation run, every member of a staff org has a projection.
TCP itself has no role logic.
The app's on/off switch. The mobile profile setting is the HTTP
server's PATCH /v1/me/preferences with notifications.channels.push,
saved in DynamoDB and sent to TCP as pushEnabled in notify.user.v1.
Off means no push at all, critical included (changed 2026-11-13; before,
critical always went through). The in-app inbox entry is still written.
A slow or failing Firebase never delays saving alerts. The push sender works from the stream, and the stream keeps undelivered events until it catches up.
Membership notices to staff
Built 2026-11-26 (cse-http-be ADR 0031), not deployed. Three push requests from the HTTP server go out even to a
person with pushEligible: false: JOIN_REQUEST_RECEIVED (to the Business
members who decide an Installer's join request), INVITATION_RECEIVED (to
the Installer or End User a Business invited) and ADDED_TO_BUSINESS (to
an End User a plant transfer added into a Business). They arrive as
notify.push.requested.v1 with eligibilityExempt: true and platforms
ANDROID, IOS and WEB. The HTTP server now projects a staff member's
endpoints so these can reach them. The person's own push switch and quiet
hours still apply. They also go to the tokens the person registered over
the WebSocket, not only to the endpoints the HTTP server projected (changed
2026-11-27, not deployed). Alert pushes and every other request keep the End Users
only rule. The Flutter app reloads its Requests tab when it receives a push
with data.type JOIN_REQUEST_RECEIVED.
What is pushed, and what is not
| Situation | Push? |
|---|---|
| A new alert is raised on a device you own | Yes: Android and iOS phones, and web browsers |
An alert whose catalog entry has notify_on_resolve (e.g. Logger Offline → Logger Back Online) clears | Yes, web browsers only; replaces the raise's notification on screen |
| Several alerts raised in the same scan (e.g. a grid failure trips three codes) | One notification: "Critical: 3 new alerts", naming up to three |
Any other alert resolves, or an open alert changes (resolved / updated) | No. It still updates the in-app feed |
The owner is not an End User (HTTP pushEligible: false: Super Admin, Administrator, Business or Installer) | No, on any platform, critical included. The inbox entry is still written. (Only the HTTP server's membership notices are exempt: see above) |
The owner turned push off in the app (HTTP preference pushEnabled: false) | No, critical included. The inbox entry is still written |
| It is inside the owner's personal quiet hours (read in the plant's timezone) | No, unless the alert is critical: critical goes through quiet hours. The inbox entry is still written |
| The alert is more than 15 minutes old by the time it reaches the sender (backlog after an outage) | No, to avoid a burst of stale notifications after recovery. Logger Back Online is measured from 10 minutes after its resolvedAt, because the offline alert is resolved only after the logger has stayed connected for 10 minutes (see Device alerts) |
| 200 or more loggers go offline in the same sweep (almost always a backend failure, not each customer's internet) | No; logged as a platform incident instead. The alerts still appear in the app |
| The device is revoked, has no owner, or the owner registered no token | No (an owner without tokens still gets the inbox entry) |
Every severity is pushed, info included. Critical and warning alerts are
sent with high priority, and info alerts with normal priority (see
Payload).
Messages
Register a token: register_push_token
Send it after sign-in, and again every time Firebase gives the app a new
token (onTokenRefresh). Re-registering the same token is harmless; it just
refreshes it.
// → client
{"type": "register_push_token",
"userId": "17833b2e-a851-4a17-a764-62524d667959",
"token": "<FCM registration token from FirebaseMessaging.getToken()>",
"platform": "android"} // or "ios" or "web"
// ← server
{"type": "push_token_result", "action": "register", "ok": true}
| Field | Rules |
|---|---|
userId | A UUID, the same userId every other message uses (the Cognito user id). Required on a connection without a realtime ticket; on a ticket-authenticated connection it is ignored and the ticket's user is used |
token | Required. The FCM registration token: 16–4096 characters of A–Z a–z 0–9 : _ - . |
platform | Required. "android", "ios" or "web" (case-insensitive). Anything else is refused with platform must be "android", "ios" or "web" |
Rules:
- One token belongs to one user. If a second user signs in on the same phone and registers the same token, it moves to them, so the first user's alerts stop arriving on that phone.
- A user can have at most 10 registered tokens. Registering an 11th drops the one refreshed longest ago.
Remove a token: unregister_push_token
Send it on sign-out, before dropping the session.
// → client
{"type": "unregister_push_token",
"userId": "17833b2e-a851-4a17-a764-62524d667959",
"token": "<the same FCM token>"}
// ← server
{"type": "push_token_result", "action": "unregister", "ok": true}
ok: true also comes back when the token was not registered, or belongs to
someone else; nothing is removed then. That is deliberate: the reply must not
reveal which tokens exist.
Errors
Validation failures and database problems come back on the same envelope:
{"type": "push_token_result", "action": "register", "ok": false, "error": "userId must be a UUID"}
error | Cause |
|---|---|
userId is required / userId must be a UUID | Missing or malformed userId |
token is required / token is not an FCM registration token | Missing or malformed token |
platform is required / platform must be "android", "ios" or "web" | register_push_token without an accepted platform |
device database not configured | ws-gateway is running without its database. This is a server problem, so retry later |
could not register the push token; try again (or unregister) | The database write failed. Retry with backoff |
Payload
What the phone or browser receives: an FCM notification message with a
data payload. Each token gets one message carrying only its own platform's
block (android, apns or webpush).
Notification:
| Part | Value |
|---|---|
| Title | "<Severity>: <alert title>", e.g. Critical: Grid over-voltage. Grouped: "Critical: 3 new alerts" (the highest severity among them). Up to 100 characters |
| Body | "Inverter <serial> — <alert message>" ("Logger <loggerId>" when the inverter serial is unknown). Grouped: "Inverter <serial> — <title>, <title>, <title> and N more". Up to 240 characters |
data (all values are strings, as FCM requires):
| Key | Value |
|---|---|
type | "alert" |
alertId | The (first) alert's id, the same id get_alerts returns |
alertIds | Comma-separated ids of every alert in this notification |
count | How many alerts this notification covers |
deviceKey, plantId | The device (its id, the key to open it with) and its plant. Always the device id, including for an alert raised just before the device-id release and delivered after it |
loggerId | The logger that raised the (first) alert, for display |
code | The (first) alert's catalog code, e.g. aotai.F01 |
severity | critical, warning or info (the highest in the notification) |
tag | alert-<alertId>: the web notification tag (see below) |
link | /alerts?alert=<alertId>: the web console path the click opens |
Android options:
| Option | Value |
|---|---|
priority | HIGH for critical and warning (delivered immediately even when the phone is dozing); NORMAL for info |
ttl | How long FCM keeps trying a phone that is off: 24 h critical, 6 h warning, 1 h info |
notification.tag | The (first) alert id. A later notification with the same tag replaces it instead of stacking |
notification.channel_id | alerts_critical, alerts_warning or alerts_info; the app must create these (see the mobile guide) |
iOS message
One FCM HTTP v1 message per ios token, with the same
notification {title, body} and data as above. FCM turns data into
top-level keys of the APNs payload, so the app reads the same keys as on
Android.
| Option | Value |
|---|---|
apns.headers.apns-priority | 10 for critical and warning (delivered at once); 5 for info (iOS may batch it for battery) |
apns.headers.apns-expiration | Send time + 24 h critical, 6 h warning, 1 h info (Unix seconds). Apple stops trying after it |
apns.headers.apns-collapse-id | The (first) alert id. A later notification with the same id replaces it. Left out if longer than 64 bytes |
apns.payload.aps.sound | default |
Web (browser) message
One FCM HTTP v1 message per WEB token, with the same
notification {title, body} and data as above (never a data-only message), and:
| Option | Value |
|---|---|
webpush.notification.icon | /brand/logo-mark.png |
webpush.notification.tag | alert-<alertId> (the first alert's). The clear of that alert uses the same tag and replaces it |
webpush.fcm_options.link | /alerts?alert=<alertId> (the first alert's). If the backend is deployed with WEB_CONSOLE_ORIGIN, the link is that origin plus the path |
webpush.headers.Urgency | high for critical and warning, normal for info |
webpush.headers.TTL | Seconds: 86400 critical, 21600 warning, 3600 info |
No other console path is used for alerts; the console team asked to be consulted before any other is added.
Alert raised and alert cleared
| Alert raised | Alert cleared | |
|---|---|---|
| Sent to | Android, iOS and web | Web only, and only for catalog codes with notify_on_resolve |
title | <Severity>: <alert title> (grouped: <Severity>: N new alerts) | Resolved: <resolved title>, e.g. Resolved: Logger Back Online (grouped: Resolved: N alerts) |
body | Inverter <serial> — <alert message> | Inverter <serial> (grouped: Inverter <serial> — <title>, …) |
data.type | alert | alert_resolved |
data.tag / web tag | alert-<alertId> | alert-<alertId> (same as the raise) |
link | /alerts?alert=<alertId> | /alerts?alert=<alertId> |
| Preferences | Not eligible or push off: never sent. Quiet hours: suppressed except critical | Same |
| Stale | Not sent if raised more than 15 minutes before it reaches the sender | Not sent if cleared more than 15 minutes before |
The other data keys (alertId, alertIds, count, deviceKey,
plantId, loggerId, code, severity, link) are the same for both.
Pushes the HTTP server requests (notify.push.requested.v1)
The HTTP server asks for one push to one person, for its own inbox items
(work-order kinds → /service?order=<id>, tag wo-<id>; REPORT_READY →
/reports, tag report-<id>) and for its digest fallback. The bus consumer
only queues the request (notify_push_requests, idempotent on
requestId); a separate loop in persistence-worker sends it, so Firebase
never slows the bus. Each request:
- goes to every endpoint the person has: the ones the HTTP server
projected and the tokens the app or browser registered over the
WebSocket (
push_tokens), one push per token, limited toplatformswhen present. The HTTP server's inbox pushes carry["WEB"], so phones never get them; membership notices carry all three platforms, so they reach the phone whichever way it registered (changed 2026-11-27, not deployed: before, WebSocket-registered tokens were skipped and a phone that registered only over the WebSocket never got a membership notice); - uses the request's
title,bodyanddata(non-string values are sent as their JSON text; FCM's reserved keys are dropped), withdata.tagand the notification tag set totag, andlinksent aswebpush.fcm_options.link(a path starting with a single/; anything else is dropped and the push is sent without it); - is not sent to a person with
pushEligible: falseorpushEnabled: false, and honours personal quiet hours. A request witheligibilityExempt: true(the membership notices) skips only thepushEligiblecheck; the flag is queued with it (notify_push_requests.eligibility_exempt, migration 0155) (quiet hours are read in the timezone of a plant the person owns a device in, elseAsia/Karachi); - is not sent if it is more than 15 minutes old when the sender gets to it, and is retried at most 3 times when nothing could be delivered.
Dead tokens (notify.endpoint.invalid.v1)
When FCM answers UNREGISTERED (or 404), SENDER_ID_MISMATCH, or
INVALID_ARGUMENT naming the registration token, the sender deletes the token from both push_tokens
and notify_endpoints. For a token the HTTP server projected it publishes
notify.endpoint.invalid.v1 {userSub, tokenId, reason} (reason
UNREGISTERED or INVALID_ARGUMENT) on cse-tcp-be-<stage>-events, and
the HTTP server deletes it and republishes notify.user.v1 without it. The
token itself is never sent back or logged. Any other INVALID_ARGUMENT (a
problem with the message, not the token) deletes nothing, and neither does
THIRD_PARTY_AUTH_ERROR (no valid APNs key in the Firebase project): that
is logged as push send failed with platform: ios, and the iOS tokens
start working as soon as the key is uploaded.
App integration
- Mobile (Flutter, Android and iOS): Push: mobile app guide: Firebase setup, channels, permission, the registration lifecycle, tap and foreground handling, testing and troubleshooting.
- Web: Push: web app guide: in-app toasts, the bell, the notification inbox, and browser push.
One-time setup
All by a human, once per environment. None of it involves committing a file.
-
Create a Firebase project (or use the existing one) and add the apps. Dev uses
cse-datalogger(since 2026-11-12). It needs all three apps: Android (com.crownsolar.crown_inverter_…), iOS (com..solar.crowninverter) and web.- iOS: in the Apple Developer account create an APNs authentication
key (
.p8), then upload it in Firebase console → Project settings → Cloud Messaging → Apple app configuration, with its Key ID and the Team ID. Without it every iOS send fails withTHIRD_PARTY_AUTH_ERROR. The key is a credential: it goes to Firebase only, never into a repository or Secrets Manager here. - Web: generate the Web Push certificate (VAPID key pair) under
Cloud Messaging → Web Push certificates. The public key goes in
the web app's
getTokencall; the backend needs nothing for it.
- iOS: in the Apple Developer account create an APNs authentication
key (
-
Firebase console → Project settings → Service accounts → Generate new private key. This JSON file is a credential. Keep it out of the repository;
.gitignorealso excludes*service-account*.jsonand*firebase-adminsdk*.jsonas a backstop. -
Store it in Secrets Manager under the exact name the deploy script looks for:
aws secretsmanager create-secret --region us-east-1 \--name cse-tcp-be-dev-fcm-service-account \--secret-string file:///path/outside/the/repo/service-account.jsonThen delete the local copy.
-
Deploy:
cd cdk && npm run deploy.deploy.shfinds the secret by name and passes its ARN as-c fcmSecretArn=…. The persistence-worker task then getsPUSH_ENABLED=true, and the secret is injected asFCM_SERVICE_ACCOUNT_JSON. Without the secret the same deploy setsPUSH_ENABLED=false, and nothing else changes. -
Check the persistence-worker log (
cd cdk && npm run logs:persistence-worker) forpush notifications enabledwithfirebase_project. Every push afterwards logspush sentwith how many tokens it reached.
Kill switch. Push runs only when the secret exists and SSM
/cse-tcp-be/<stage>/notify/push-enabled is true. The stack writes that
parameter (the HTTP server reads it to show Push availability) and
deploy.sh reads it back on every run, so a value set by hand survives
the next deploy:
aws ssm put-parameter --region us-east-1 --overwrite \
--name /cse-tcp-be/dev/notify/push-enabled --value true # or false
cd cdk && npm run deploy
NOTIFY_PUSH_ENABLED=true|false npm run deploy does the same in one step.
The first deploy that finds no parameter creates it as true when the
secret exists (push stays as it was) and false otherwise. Turning it off
stops every push and nothing else: alerts, the inbox and the HTTP
projection keep running. The worker reads the setting at start, so it
takes effect with the deploy, not before.
Optional: WEB_CONSOLE_ORIGIN=https://<console host> npm run deploy makes
web notification links absolute. Firebase documents fcm_options.link as
an HTTPS URL; if it refuses the bare path on dev, set this.
The migration that creates push_tokens (0054_push_tokens) is applied by
the persistence-worker on its next start, like every other migration.
Local runs: set PUSH_ENABLED=true and FCM_SERVICE_ACCOUNT_FILE to the
key file's path, outside the repository (see .env.example).
Turning it off: set the kill switch to false and redeploy (above).
Deleting the secret also works. An invalid or unreadable key turns push off
at startup, with an error logged. Telemetry and alert persistence keep
running either way.
Cost
Firebase Cloud Messaging is free. The only charge is AWS data transfer to the internet for each send (about 1 KB per send, an estimate not yet measured) at $0.09/GB, after the account's first 100 GB per month.
That is $0 at today's volume, and roughly $50 a month at a million users receiving 15 notifications a day. There is no new service, server or queue.
What is not covered
userIdis only verified with a realtime ticket. On a connection authenticated with a ticket, the gateway uses the ticket's user (see Authentication). Without one, which dev'soptionalauth mode still allows,userIdis the client's claim: a client that claims someone else'suserIdcan register its own token and receive that user's alert notifications, the same exposureget_alertshas for the alert list. Production'srequiredmode closes both (see Known gaps).- Alert clears go to browsers only. The mobile app has never received
a clear; sending it one needs the app team to handle
data.typealert_resolvedfirst. - Only the device owner (
devices.owner_user_id) is notified about alerts: not other members of the customer org, installers or staff. The HTTP server'snotify.audience.v1(who may see which plants, and their alert rules) is stored innotify_audiencebut not used yet; the rule-based delivery inPUSH_NOTIFICATIONS_PLAN.mdwould use it. - Only personal preferences are applied:
pushEligible(skipped for the exempt membership notices),pushEnabledand quiet hours. Org settings (notify.org-settings.v1), alert rules, working hours, grouping windows, storm caps and email requests (notify.email.requested.v1) are not implemented. - iOS depends on the APNs key in Firebase. The backend sends to iOS
tokens; whether Apple delivers them depends on the key uploaded in the
Firebase project (One-time setup step 1), which the backend cannot
check. If
push send failed … THIRD_PARTY_AUTH_ERRORappears forplatform: ios, the key is missing or wrong. - Phones without Google Play services (for example Huawei devices sold since 2019) cannot receive FCM at all.
- Best effort. FCM does not guarantee delivery or timing. Battery optimisation on some manufacturers' phones delays or drops normal-priority messages. The in-app alert feed is the source of truth.
- Rare duplicates. If the worker crashes after FCM accepted a send but before the event was acknowledged, the redelivered event can push again. The notification tag makes the second one replace the first rather than stack.