Skip to content

feat: optional device push notifications (FCM + web push) - #185

Merged
iamxvbaba merged 3 commits into
iamxvbaba:mainfrom
roon9e:pr/push-fcm-apns
Nov 23, 2026
Merged

iamxvbaba merged 3 commits into
iamxvbaba:mainfrom
roon9e:pr/push-fcm-apns

Conversation

@roon9e

@roon9e roon9e commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Optional device push notifications (FCM + web push)

Implements the scoped design the owner asked for in #98. Off by default: a
deployment that does not opt in behaves exactly as before (account.registerDevice
stays a no-op returning true, no token is stored, no push is sent).

Today account.registerDevice is accepted and discarded, and a backgrounded
client receives nothing until it reconnects. This adds optional server-side push
delivery for Android FCM and web push, and honours per-chat mute.

How it works

  1. Registration — account.registerDevice/unregisterDevice now persist the
    device token (and the client secret) when a token store is wired. A token is
    globally unique per (token_type, token) and reassigned to the newest account;
    an empty token returns TOKEN_EMPTY.
  2. Offline trigger — the durable outbox dispatcher already reports how many
    live sessions an update reached. When that count is zero, an
    OfflinePushBridge builds a loc_key notification from the viewer's updates,
    coalesces per user, and sends from a small worker pool (never blocking the
    outbox). Online delivery is completely unchanged.
  3. Mute — the bridge reads the peer's mute_until (per-peer scope plus the
    users/chats/broadcasts category default). A muted peer yields a throttled
    MESSAGE_MUTED badge refresh instead of a visible notification; a device whose
    token is no_muted is skipped for that refresh.
  4. Invalidation — an UNREGISTERED/404/410 rejection deletes the token.

Encryption

FCM (token_type 2) — the notification JSON is sealed with the client
secret using the MTProto-v2 scheme the official clients use, and sent as the
p field of a data-only FCM message:

blob       = SHA1(secret)[-8:] || msg_key(16) || AES-IGE(padded_plaintext)
msg_key    = SHA256(secret[96:128] || padded_plaintext)[8:24]
aes key/iv = MessageKeyData(secret, msg_key, incoming=true)  // x=8
padded     = int32LE(len(json)) || json || random padding to 16 bytes
p          = base64url(blob)

This was matched against the reference implementations (DrKLO Android
PushListenerController + MessageKeyData, and Telegram Web K's
pushSingleManager), and the cipher is round-tripped by an independent client
decryptor in tests.

Web push (token_type 10) — the subscription is a JSON token
(endpoint + p256dh/auth). The notification JSON is encrypted with
RFC 8291 (aes128gcm, RFC 8188) and delivered with an RFC 8292
VAPID ES256 Authorization header. Validated against the RFC 8291 §5 test vector
and an end-to-end test that verifies the VAPID JWT and decrypts the body.

Configuration (all optional)

Setting Default Meaning
TELESRV_PUSH_ENABLED false Master switch.
TELESRV_PUSH_FCM_SERVICE_ACCOUNT_FILE — Firebase service-account JSON (file-backed secret).
TELESRV_PUSH_FCM_PROJECT_ID / _TOKEN_URL / _SCOPE — Overrides.
TELESRV_PUSH_WEBPUSH_VAPID_PUBLIC_KEY / _PRIVATE_KEY — Web push VAPID keypair (base64url).
TELESRV_PUSH_WEBPUSH_SUBJECT / _TTL — / 86400 VAPID sub, TTL.
TELESRV_PUSH_DEBOUNCE / _SEND_TIMEOUT 30s / 5s Coalescing window / HTTP timeout.

No new dependency: the OAuth2 service-account JWT and VAPID use only the standard
library (crypto/ecdh, crypto/ecdsa, crypto/aes, HKDF via crypto/hmac).

Client requirement (unavoidable)

  • Android must be rebuilt against the operator's own Firebase project
    (google-services.json swap) so FCM delivers to the server's service account.
  • Web must be built with a VAPID public key whose private half the server
    holds (VITE_PUSH_SERVER_KEY). The push service rejects a mismatched key.

Testing

  • internal/push: FCM sender against an httptest server (token caching,
    unregistered invalidation), the MTProto cipher round-trip, the RFC 8291 test
    vector, and an end-to-end VAPID+decrypt check.
  • internal/rpc: registration/storage, outbox "notify only when sent == 0",
    mute → MESSAGE_MUTED, and no_muted skipping.
  • internal/store: memory + postgres (*_integration_test.go, DSN-gated).

Not included

  • APNs (needs its own Apple key and an iOS rebuild; designed but deferred).
  • Push for forum topic scopes beyond the peer default.

Feedback welcome, especially on the payload/loc_key choices and whether push
should stay in-tree (as here) or be an optional sidecar.

Storage layer for optional device push notifications (issue iamxvbaba#98), off by
default:

- domain.PushToken and store.PushTokenStore with memory + postgres backends
- device_push_tokens migration, sqlc queries and generated code
- account.registerDevice/unregisterDevice persist tokens when a store is
  wired and stay no-ops otherwise; keyed by (token_type, token), reassigned
  across accounts, empty token -> TOKEN_EMPTY
- TELESRV_PUSH_ENABLED master switch gates token storage
- rpc.Deps.PushTokens and main.go wiring; store/rpc tests

Enabling push only records tokens at this point; no sender yet.
Sender layer for issue iamxvbaba#98, gated by TELESRV_PUSH_ENABLED:

- internal/push: MTProto-v2 push cipher (byte-compatible with the official
  clients), FCM HTTP v1 sender with service-account OAuth2, RFC 8291 web push
  with RFC 8292 VAPID, and a Service that dispatches by token type
- offline trigger: the outbox dispatcher hands an update that reached no live
  session to OfflinePushBridge, which builds a loc_key payload from the
  viewer's updates, coalesces per user, and sends from a worker pool
- mute awareness: a muted peer yields a throttled MESSAGE_MUTED badge refresh,
  and a device whose token is no_muted is skipped for it
- invalidation: an UNREGISTERED/410 rejection deletes the token
- config: TELESRV_PUSH_FCM_* and TELESRV_PUSH_WEBPUSH_VAPID_* plus debounce and
  send timeout, wired in cmd/telesrv; .env.example and configuration docs updated
- tests: FCM httptest, the RFC 8291 test vector, an end-to-end VAPID+decrypt
  check, and the rpc trigger/mute cases
- docs/push-notifications.md: scoped design (storage, cipher, senders, offline
  trigger, mute/badge, APNs deferred) kept in sync with the implementation
- docs/telegram-differences.md: the push row now describes the opt-in FCM/web
  push behaviour
@iamxvbaba
iamxvbaba merged commit d883d5e into iamxvbaba:main Nov 23, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants