:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(workflows): keep every device of a person reachable for push notifications (#103496)
Daniel Marchukb8523b171c61
diff --git a/docs/internal/push-subscription-registration.md b/docs/internal/push-subscription-registration.mdindex 7d1ca584b4ce..72915fb178e3 100644--- a/docs/internal/push-subscription-registration.md+++ b/docs/internal/push-subscription-registration.md@@ -7,7 +7,7 @@ configured does not generate a request per device per app open.A mobile SDK with push capture enabled posts its device token to `/api/push_subscriptions/` when theapp starts. The server resolves the `app_id` to a Firebase or APNs integration on the team and stores-the token as a `$device_push_subscription_<app_id>` person property.+the token as a person property.`distinct_id`, `device_token` and `app_id` are required. SDKs also send a `platform` field, which theserver ignores: nothing is stored or routed by it, and the provider is selected by `app_id`. A device@@ -17,6 +17,23 @@ reject a registration over a field it does not use.Push is opt-in per project, and the SDK cannot see whether a project opted in. So an app that shipswith push capture on registers against every project it reports to, configured or not.+## Where a token is stored++Each device holds its own person property, `$device_push_subscription_<app_id>:<digest>`, where the+digest is the first 16 hex characters of the SHA-256 of the token. The digest comes from the token+rather than from a device id supplied by the SDK, so a build already in the field lands on the right+key without shipping a new one.++`$device_push_subscription_<app_id>`, keyed on the app alone, is the earlier shape and holds a single+device for the whole app. `POST` no longer writes it, and the send path still reads it, so a device+stored that way stays reachable until it registers again and moves to a per-device key.++`DELETE` unsets the key for the token in the request, and the app-wide key with it. A device cannot+tell whether that key holds its own token, and a logout that left it would keep a signed-out device+receiving notifications.++One send addresses at most 20 devices for one person and one app, taken in key order.+## What the server does with an unconfigured `app_id``POST` answers `200` with `{"stored": false, "push_enabled": false}` and does not store the token.diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts b/nodejs/src/cdp/services/messaging/push-notification.service.test.tsindex d5de0346e875..cfad579a7aa1 100644--- a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts+++ b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts@@ -4,6 +4,7 @@ import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '~/cdp/_import { createExampleInvocation, createHogFunction } from '~/cdp/_tests/fixtures'import { CyclotronJobInvocationHogFunction } from '~/cdp/types'import { EncryptedFields } from '~/cdp/utils/encryption-utils'+import { deviceSubscriptionKey } from '~/cdp/utils/push-subscription-utils'import { parseJSON } from '~/common/utils/json-parse'import { IntegrationManagerService } from '../managers/integration-manager.service'@@ -911,6 +912,185 @@ describe('PushNotificationService', () => {})})+ describe('multiple devices on one app', () => {+ const twoDevices = () =>+ createSendPushNotificationInvocation({+ [deviceSubscriptionKey('test-project', 'token-phone')]: encryptedFields.encrypt('token-phone'),+ [deviceSubscriptionKey('test-project', 'token-tablet')]: encryptedFields.encrypt('token-tablet'),+ })++ const ok = () => ({+ fetchError: null,+ fetchResponse: { status: 200, text: () => Promise.resolve('{}'), dump: () => Promise.resolve() },+ fetchDuration: 10,+ })++ const unregistered = () => ({+ fetchError: null,+ fetchResponse: {+ status: 404,+ text: () =>+ Promise.resolve(+ JSON.stringify({ error: { status: 'NOT_FOUND', details: [{ errorCode: 'UNREGISTERED' }] } })+ ),+ dump: () => Promise.resolve(),+ },+ fetchDuration: 10,+ })++ const serverError = () => ({+ fetchError: null,+ fetchResponse: { status: 500, text: () => Promise.resolve('{}'), dump: () => Promise.resolve() },+ fetchDuration: 10,+ })++ it('sends to every device, not just one', async () => {+ // The bug: a second device on the same app was unreachable because it overwrote the first.+ mockTrackedFetch.mockResolvedValue(ok())++ const result = await service.executeSendPushNotification(twoDevices())++ expect(result.error).toBeUndefined()+ const sentTokens = mockTrackedFetch.mock.calls.map(+ (call: any) => parseJSON(call[0].fetchParams.body).message.token+ )+ expect(sentTokens.sort()).toEqual(['token-phone', 'token-tablet'])+ })++ it('prunes only the dead device and still delivers to the other', async () => {+ mockTrackedFetch.mockResolvedValueOnce(unregistered()).mockResolvedValueOnce(ok())++ const result = await service.executeSendPushNotification(twoDevices())++ expect(result.error).toBeUndefined()+ const unsets = result.capturedPostHogEvents.flatMap((e: any) => e.properties.$unset ?? [])+ expect(unsets).toHaveLength(1)+ expect(unsets[0]).toMatch(/^\$device_push_subscription_test-project:/)+ })++ it('does not contact a pruned device again when the step is retried', async () => {+ // The dead key has to leave the invocation's own snapshot as well as the person. The retry+ // reads that snapshot back, so a key left behind means another send to the dead token and a+ // second $unset for it.+ mockTrackedFetch.mockImplementation((opts: any) =>+ Promise.resolve(+ parseJSON(opts.fetchParams.body).message.token === 'token-phone' ? unregistered() : serverError()+ )+ )++ const first = await service.executeSendPushNotification(twoDevices())+ expect(first.finished).toBe(false)++ mockTrackedFetch.mockClear()+ mockTrackedFetch.mockImplementation(() => Promise.resolve(ok()))++ const retry = await service.executeSendPushNotification(first.invocation)++ const retriedTokens = mockTrackedFetch.mock.calls.map(+ (call: any) => parseJSON(call[0].fetchParams.body).message.token+ )+ expect(retriedTokens).toEqual(['token-tablet'])+ expect(retry.capturedPostHogEvents).toEqual([])+ })++ it('does not retry the step when one device failed but another was delivered to', async () => {+ // Retrying would push a second time to the device that already received it. Losing the+ // failed device's notification is the better of the two outcomes.+ mockTrackedFetch.mockResolvedValueOnce(ok()).mockResolvedValueOnce(serverError())++ const result = await service.executeSendPushNotification(twoDevices())++ // Finished, not rescheduled: a reschedule is what would resend to the delivered device.+ expect(result.error).toBeUndefined()+ expect(result.finished).toBe(true)+ expect(result.invocation.queueScheduledAt).toBeUndefined()+ })++ it('reschedules the step when no device was delivered to', async () => {+ // Nothing arrived anywhere, so a retry cannot duplicate a delivery.+ mockTrackedFetch.mockResolvedValue(serverError())++ const result = await service.executeSendPushNotification(twoDevices())++ expect(result.finished).toBe(false)+ expect(result.invocation.queueScheduledAt).toBeDefined()+ })++ const badPayload = () => ({+ fetchError: null,+ fetchResponse: { status: 400, text: () => Promise.resolve('{}'), dump: () => Promise.resolve() },+ fetchDuration: 10,+ })++ it.each([+ [+ 'transient first',+ () => mockTrackedFetch.mockResolvedValueOnce(serverError()).mockResolvedValueOnce(badPayload()),+ ],+ [+ 'terminal first',+ () => mockTrackedFetch.mockResolvedValueOnce(badPayload()).mockResolvedValueOnce(serverError()),+ ],+ ])('reschedules when one device failed transiently and another terminally, %s', async (_name, arrange) => {+ // Whether the step is worth re-running depends on any device being retriable, not on which+ // device happened to fail last. Keeping only the last error made this order-dependent, so+ // a terminal failure arriving second dropped the retry the transient one had earned.+ arrange()++ const result = await service.executeSendPushNotification(twoDevices())++ expect(result.finished).toBe(false)+ expect(result.invocation.queueScheduledAt).toBeDefined()+ })++ const throttled = () => ({+ fetchError: null,+ fetchResponse: {+ status: 429,+ headers: { 'retry-after': '30' },+ text: () => Promise.resolve('{}'),+ dump: () => Promise.resolve(),+ },+ fetchDuration: 10,+ })++ it.each([+ [+ 'throttled device second',+ () => mockTrackedFetch.mockResolvedValueOnce(serverError()).mockResolvedValueOnce(throttled()),+ ],+ [+ 'throttled device first',+ () => mockTrackedFetch.mockResolvedValueOnce(throttled()).mockResolvedValueOnce(serverError()),+ ],+ ])('reschedules using the longest Retry-After across devices, %s', async (_name, arrange) => {+ // Only one error per channel reaches the reschedule, so the loop has to hand up the device+ // asking for the longest wait. Handing up the 500 instead drops the 30s window to a sub-2s+ // backoff, and the retries then burn inside the window the provider asked us to sit out.+ arrange()++ const result = await service.executeSendPushNotification(twoDevices())++ expect(result.finished).toBe(false)+ const delayMs = result.invocation.queueScheduledAt!.toMillis() - Date.now()+ expect(delayMs).toBeGreaterThan(20_000)+ expect(delayMs).toBeLessThanOrEqual(30_000)+ })++ it('explains a device that failed while another device was delivered to', async () => {+ // The channel reports success, so this device never reaches the outer catch that logs a+ // channel failure. Without a line of its own it is permanently broken and invisible, since+ // the only other record is the debug-level provider response.+ mockTrackedFetch.mockResolvedValueOnce(ok()).mockResolvedValueOnce(badPayload())++ const result = await service.executeSendPushNotification(twoDevices())++ expect(result.finished).toBe(true)+ const visibleLogs = result.logs.filter((log) => log.level !== 'debug').map((log) => log.message)+ expect(visibleLogs).toContainEqual(expect.stringContaining('rejected the notification contents'))+ })+ })+describe('multiple channels', () => {const apnsIntegration = {id: 2,diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.ts b/nodejs/src/cdp/services/messaging/push-notification.service.tsindex e71bf631411e..b6ff3016bb04 100644--- a/nodejs/src/cdp/services/messaging/push-notification.service.ts+++ b/nodejs/src/cdp/services/messaging/push-notification.service.ts@@ -16,7 +16,7 @@ import type { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult, Iimport { createAddLogFunction } from '../../utils'import { EncryptedFields } from '../../utils/encryption-utils'import { createInvocationResult } from '../../utils/invocation-utils'-import { getDevicePushSubscriptionToken } from '../../utils/push-subscription-utils'+import { DeviceSubscription, getDevicePushSubscriptions } from '../../utils/push-subscription-utils'import { IntegrationManagerService } from '../managers/integration-manager.service'import { MessageAssetsService } from './message-assets.service'import {@@ -143,6 +143,32 @@ function pushCorrelationData(invocation: CyclotronJobInvocationHogFunction): Recreturn { [PUSH_CORRELATION_KEY]: JSON.stringify(correlation) }}+// The retriable failure that stands for a person's devices: the one asking for the longest wait. Only+// one error per channel reaches the reschedule, so the delay every other device asked for is gone by+// then — keeping the earliest would retry inside a window a later device's provider asked us to sit+// out. A failure carrying no Retry-After counts as zero, which is what the backoff already assumes.+function longestRetriableFailure(current: PushSendError | undefined, candidate: Error): PushSendError | undefined {+ if (!(candidate instanceof PushSendError) || !candidate.retriable) {+ return current+ }+ if (!current) {+ return candidate+ }+ return (candidate.retryAfterMs ?? 0) > (current.retryAfterMs ?? 0) ? candidate : current+}++// The devices that failed inside a channel that still delivered to another one. That channel reports+// success, so these never reach the outer catch that logs and counts a whole-channel failure, and a+// device failing for good — a token registered against the wrong app, a rejected payload — would be+// left with only a debug-level line. Counting here cannot double-count: a channel that delivered is+// never rescheduled, so no later attempt sees these devices again.+function reportPartialDeviceFailures(failures: PushSendError[], addLog: ReturnType<typeof createAddLogFunction>): void {+ for (const failure of failures) {+ pushNotificationFailedCounter.labels({ platform: failure.platform, reason: failure.reason }).inc()+ addLog(failure.level, failure.message)+ }+}+function pushSendError(platform: PushPlatform, err: NormalizedPushError, retryAfterMs?: number): PushSendError {// Append the raw provider code so the failure surfaced to the hog template stays debuggable, while// the human-readable sentence leads.@@ -379,7 +405,6 @@ export class PushNotificationService {invocation: CyclotronJobInvocationHogFunction): Promise<boolean> {const addLog = createAddLogFunction(result.logs)- const payload = params.payloadconst projectId = integration.config.project_idconst accessToken = integration.sensitive_config.access_token@@ -388,9 +413,9 @@ export class PushNotificationService {}const personProperties = invocation.state.globals.person?.properties- const token = getDevicePushSubscriptionToken(personProperties, projectId, this.encryptedFields)+ const subscriptions = getDevicePushSubscriptions(personProperties, projectId, this.encryptedFields)- if (!token) {+ if (subscriptions.length === 0) {addLog('warn', `No active FCM device token found for distinct_id: ${params.distinctId}`)pushNotificationSkippedCounter.labels({ platform: 'fcm', reason: 'no_token' }).inc()return false@@ -399,15 +424,60 @@ export class PushNotificationService {const url = `https://fcm.googleapis.com/v1/projects/${projectId}/messages:send`const templateId = result.invocation.hogFunction.template_id ?? 'unknown'- const fcmMessage = this.buildFcmMessage(token, payload)+ let delivered = 0+ // A terminal failure on one device must not mask a retriable one on another: whether the step+ // is worth re-running depends on any device being retriable, not on which failed last.+ let retriableFailure: PushSendError | undefined+ const failures: PushSendError[] = []++ for (const subscription of subscriptions) {+ const outcome = await this.sendOneFcm(result, params, subscription, url, accessToken, templateId, addLog)+ if (outcome.sent) {+ delivered+++ } else if (outcome.unregistered) {+ this.pruneDeviceToken(result, invocation, params.distinctId, subscription.propertyKeys, 'fcm')+ addLog('warn', `FCM: ${outcome.message}`)+ } else if (outcome.error) {+ failures.push(outcome.error)+ retriableFailure = longestRetriableFailure(retriableFailure, outcome.error)+ }+ }++ if (delivered > 0) {+ addLog('info', `Push notification accepted by FCM for ${delivered} of ${subscriptions.length} device(s).`)+ reportPartialDeviceFailures(failures, addLog)+ // A throw here would re-run the step and push again to every device already delivered to.+ // A device that failed retryably loses this one notification instead, which is the better+ // of the two: a missed push on one device rather than a duplicate on the others.+ return true+ }++ const failure = retriableFailure ?? failures.at(-1)+ if (failure) {+ throw failure+ }++ return false+ }+ /** One FCM send. Reports the outcome rather than throwing, so the caller can weigh it against the+ * other devices of the same person before deciding to retry the step. */+ private async sendOneFcm(+ result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,+ params: CyclotronInvocationQueueParametersSendPushNotificationType,+ subscription: DeviceSubscription,+ url: string,+ accessToken: string,+ templateId: string,+ addLog: ReturnType<typeof createAddLogFunction>+ ): Promise<{ sent: boolean; unregistered?: boolean; message?: string; error?: PushSendError }> {const fetchParams: FetchOptions = {method: 'POST',headers: {Authorization: `Bearer ${accessToken}`,'Content-Type': 'application/json',},- body: JSON.stringify(fcmMessage),+ body: JSON.stringify(this.buildFcmMessage(subscription.token, params.payload)),}if (params.timeoutMs !== undefined) {@@ -449,16 +519,13 @@ export class PushNotificationService {// clutter the workflow log — the user-facing explanation is the normalized message below.addLog('debug', `FCM response ${status ?? '(none)'}: ${stringifyBody(body)}`)if (err.unregistered) {- this.pruneDeviceToken(result, invocation, params.distinctId, projectId, 'fcm')- addLog('warn', `FCM: ${err.message}`)- return false+ return { sent: false, unregistered: true, message: err.message }}- throw pushSendError('fcm', err, parseRetryAfterMs(fetchResponse))+ return { sent: false, error: pushSendError('fcm', err, parseRetryAfterMs(fetchResponse)) }}pushNotificationSentCounter.labels({ platform: 'fcm' }).inc()- addLog('info', 'Push notification accepted by FCM.')- return true+ return { sent: true }}/** Returns true if a notification was handed off to APNS, false if skipped (no device token). */@@ -469,7 +536,6 @@ export class PushNotificationService {invocation: CyclotronJobInvocationHogFunction): Promise<boolean> {const addLog = createAddLogFunction(result.logs)- const payload = params.payloadconst signingKey = integration.sensitive_config.signing_keyconst keyId = integration.config.key_id@@ -480,24 +546,73 @@ export class PushNotificationService {}const personProperties = invocation.state.globals.person?.properties- const token = getDevicePushSubscriptionToken(personProperties, bundleId, this.encryptedFields)+ const subscriptions = getDevicePushSubscriptions(personProperties, bundleId, this.encryptedFields)- if (!token) {+ if (subscriptions.length === 0) {addLog('warn', `No active APNS device token found for distinct_id: ${params.distinctId}`)pushNotificationSkippedCounter.labels({ platform: 'apns', reason: 'no_token' }).inc()return false}const jwt = await this.generateApnsJwt(appleTeamId, keyId, signingKey)-- const apnsPayload = this.buildApnsPayload(payload)const apnsHost =integration.config.environment === 'sandbox' ? 'api.sandbox.push.apple.com' : 'api.push.apple.com'- const url = `https://${apnsHost}/3/device/${token}`+ const templateId = result.invocation.hogFunction.template_id ?? 'unknown'++ let delivered = 0+ // A terminal failure on one device must not mask a retriable one on another: whether the step+ // is worth re-running depends on any device being retriable, not on which failed last.+ let retriableFailure: PushSendError | undefined+ const failures: PushSendError[] = []++ for (const subscription of subscriptions) {+ const outcome = await this.sendOneApns(+ result,+ params,+ subscription,+ { apnsHost, bundleId, jwt, templateId },+ addLog+ )+ if (outcome.sent) {+ delivered+++ } else if (outcome.unregistered) {+ this.pruneDeviceToken(result, invocation, params.distinctId, subscription.propertyKeys, 'apns')+ addLog('warn', `APNs: ${outcome.message}`)+ } else if (outcome.error) {+ failures.push(outcome.error)+ retriableFailure = longestRetriableFailure(retriableFailure, outcome.error)+ }+ }++ if (delivered > 0) {+ addLog('info', `Push notification accepted by APNs for ${delivered} of ${subscriptions.length} device(s).`)+ reportPartialDeviceFailures(failures, addLog)+ // See executeFcm: retrying after a partial success would push again to the devices already+ // delivered to.+ return true+ }++ const failure = retriableFailure ?? failures.at(-1)+ if (failure) {+ throw failure+ }+ return false+ }++ /** One APNs send. Reports the outcome rather than throwing, so the caller can weigh it against the+ * other devices of the same person before deciding to retry the step. */+ private async sendOneApns(+ result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,+ params: CyclotronInvocationQueueParametersSendPushNotificationType,+ subscription: DeviceSubscription,+ apns: { apnsHost: string; bundleId: string; jwt: string; templateId: string },+ addLog: ReturnType<typeof createAddLogFunction>+ ): Promise<{ sent: boolean; unregistered?: boolean; message?: string; error?: PushSendError }> {+ const payload = params.payloadconst headers: Record<string, string> = {- Authorization: `bearer ${jwt}`,- 'apns-topic': bundleId,+ Authorization: `bearer ${apns.jwt}`,+ 'apns-topic': apns.bundleId,'apns-push-type': 'alert',}if (payload.collapseKey) {@@ -513,7 +628,7 @@ export class PushNotificationService {const fetchParams: FetchOptions = {method: 'POST',headers,- body: JSON.stringify(apnsPayload),+ body: JSON.stringify(this.buildApnsPayload(payload)),// APNs requires HTTP/2allowH2: true,http2IdleTimeoutMs: APNS_IDLE_TIMEOUT_MS,@@ -523,12 +638,10 @@ export class PushNotificationService {fetchParams.timeoutMs = Math.min(params.timeoutMs, this.fetchUtils.maxFetchTimeoutMs)}- const templateId = result.invocation.hogFunction.template_id ?? 'unknown'-const { fetchError, fetchResponse, fetchDuration } = await this.fetchUtils.trackedFetch({- url,+ url: `https://${apns.apnsHost}/3/device/${subscription.token}`,fetchParams,- templateId,+ templateId: apns.templateId,teamId: result.invocation.teamId,})@@ -560,16 +673,13 @@ export class PushNotificationService {// Apple signals a dead token with 410 / reason "Unregistered". Prune it and skip rather than// retrying a token that will never work; other reasons are surfaced as failures.if (err.unregistered) {- this.pruneDeviceToken(result, invocation, params.distinctId, bundleId, 'apns')- addLog('warn', `APNs: ${err.message}`)- return false+ return { sent: false, unregistered: true, message: err.message }}- throw pushSendError('apns', err, parseRetryAfterMs(fetchResponse))+ return { sent: false, error: pushSendError('apns', err, parseRetryAfterMs(fetchResponse)) }}pushNotificationSentCounter.labels({ platform: 'apns' }).inc()- addLog('info', 'Push notification accepted by APNs.')- return true+ return { sent: true }}private async generateApnsJwt(teamId: string, keyId: string, signingKey: string): Promise<string> {@@ -691,16 +801,30 @@ export class PushNotificationService {result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,invocation: CyclotronJobInvocationHogFunction,distinctId: string,- appIdentifier: string,+ propertyKeys: string[],platform: 'fcm' | 'apns'): void {+ // Only the keys holding this device's token. Unsetting the app's whole subscription here would+ // take every other device of the person with it.result.capturedPostHogEvents.push({team_id: invocation.teamId,event: '$set',distinct_id: distinctId,timestamp: new Date().toISOString(),- properties: { $unset: [`$device_push_subscription_${appIdentifier}`] },+ properties: { $unset: propertyKeys },})+ // Drop the keys from this invocation's own snapshot too. A reschedule carries `state` forward+ // unchanged, so a retry would read the same dead token, send to it again and queue the $unset+ // again. `person` is replaced rather than edited in place because the object can be shared with+ // the sibling invocations built from the same event.+ const globals = result.invocation.state.globals+ if (globals.person?.properties) {+ const properties = { ...globals.person.properties }+ for (const propertyKey of propertyKeys) {+ delete properties[propertyKey]+ }+ globals.person = { ...globals.person, properties }+ }pushNotificationTokenPrunedCounter.labels({ platform }).inc()// A dead token is a non-delivery, not a failure to fix. Record it in the reason-labeled skip// series too (not just the token-removal counter) so the skip metric accounts for it.diff --git a/nodejs/src/cdp/utils/push-subscription-utils.test.ts b/nodejs/src/cdp/utils/push-subscription-utils.test.tsindex a1ef5321b870..12695b7db958 100644--- a/nodejs/src/cdp/utils/push-subscription-utils.test.ts+++ b/nodejs/src/cdp/utils/push-subscription-utils.test.ts@@ -1,5 +1,10 @@import { EncryptedFields } from './encryption-utils'-import { getDevicePushSubscriptionToken } from './push-subscription-utils'+import {+ MAX_DEVICE_TOKENS_PER_APP,+ deviceSubscriptionKey,+ getDevicePushSubscriptionToken,+ getDevicePushSubscriptions,+} from './push-subscription-utils'describe('getDevicePushSubscriptionToken', () => {const encryptedFields = new EncryptedFields('01234567890123456789012345678901')@@ -45,3 +50,103 @@ describe('getDevicePushSubscriptionToken', () => {expect(getDevicePushSubscriptionToken(properties, 'my-project', encryptedFields)).toBeNull()})})++describe('getDevicePushSubscriptions', () => {+ const encryptedFields = new EncryptedFields('01234567890123456789012345678901')+ const store = (appId: string, ...tokens: string[]): Record<string, string> =>+ Object.fromEntries(tokens.map((t) => [deviceSubscriptionKey(appId, t), encryptedFields.encrypt(t)]))++ it('returns every device registered for the app', () => {+ // The bug this fixes: a second device on the same app used to replace the first.+ const properties = store('my-project', 'token-phone', 'token-tablet')++ const tokens = getDevicePushSubscriptions(properties, 'my-project', encryptedFields).map((s) => s.token)++ expect(tokens.sort()).toEqual(['token-phone', 'token-tablet'])+ })++ it('still reads a device stored under the pre-per-device key', () => {+ // Devices registered before this change keep that key until they register again.+ const properties = {+ '$device_push_subscription_my-project': encryptedFields.encrypt('legacy-token'),+ ...store('my-project', 'new-token'),+ }++ const tokens = getDevicePushSubscriptions(properties, 'my-project', encryptedFields).map((s) => s.token)++ expect(tokens.sort()).toEqual(['legacy-token', 'new-token'])+ })++ it('sends once to a device holding the same token under both key shapes', () => {+ const token = 'same-token'+ const properties = {+ '$device_push_subscription_my-project': encryptedFields.encrypt(token),+ ...store('my-project', token),+ }++ expect(getDevicePushSubscriptions(properties, 'my-project', encryptedFields)).toHaveLength(1)+ })++ it('reports the key each token came from so one dead device can be pruned alone', () => {+ const properties = store('my-project', 'token-phone')++ const [subscription] = getDevicePushSubscriptions(properties, 'my-project', encryptedFields)++ expect(subscription.propertyKeys).toEqual([deviceSubscriptionKey('my-project', 'token-phone')])+ })++ it('carries every key holding one token, so pruning removes them together', () => {+ // A device stored under both shapes: removing only one leaves the other to fail on the next+ // send and be pruned then, so the person keeps a dead token for an extra notification.+ const token = 'token-phone'+ const properties = {+ '$device_push_subscription_my-project': encryptedFields.encrypt(token),+ [deviceSubscriptionKey('my-project', token)]: encryptedFields.encrypt(token),+ }++ const subscriptions = getDevicePushSubscriptions(properties, 'my-project', encryptedFields)++ expect(subscriptions).toHaveLength(1)+ expect(subscriptions[0].propertyKeys).toEqual([+ '$device_push_subscription_my-project',+ deviceSubscriptionKey('my-project', token),+ ])+ })++ it('ignores another app, including one whose name extends this one', () => {+ const properties = {+ ...store('my-project', 'mine'),+ ...store('my-project-staging', 'theirs'),+ }++ const tokens = getDevicePushSubscriptions(properties, 'my-project', encryptedFields).map((s) => s.token)++ expect(tokens).toEqual(['mine'])+ })++ it('skips a value that fails to decrypt but keeps the rest', () => {+ const properties = {+ ...store('my-project', 'good-token'),+ '$device_push_subscription_my-project:forged': 'not-encrypted-value',+ }++ const tokens = getDevicePushSubscriptions(properties, 'my-project', encryptedFields).map((s) => s.token)++ expect(tokens).toEqual(['good-token'])+ })++ it('caps how many devices one person and app can fan out to', () => {+ const tokens = Array.from({ length: MAX_DEVICE_TOKENS_PER_APP + 5 }, (_, i) => `token-${i}`)++ expect(getDevicePushSubscriptions(store('my-project', ...tokens), 'my-project', encryptedFields)).toHaveLength(+ MAX_DEVICE_TOKENS_PER_APP+ )+ })++ it('derives the same key the registration endpoint writes', () => {+ // Both sides hash the raw token; if they drift, a registration lands on a key sends never read.+ expect(deviceSubscriptionKey('my-project', 'device-token-abc123')).toBe(+ '$device_push_subscription_my-project:7d8d408df65cffa5'+ )+ })+})diff --git a/nodejs/src/cdp/utils/push-subscription-utils.ts b/nodejs/src/cdp/utils/push-subscription-utils.tsindex 40d0fda53eb2..1d398ef964ef 100644--- a/nodejs/src/cdp/utils/push-subscription-utils.ts+++ b/nodejs/src/cdp/utils/push-subscription-utils.ts@@ -1,27 +1,100 @@+import { createHash } from 'crypto'+import { EncryptedFields } from './encryption-utils'+export const DEVICE_SUBSCRIPTION_PREFIX = '$device_push_subscription_'++/** Upper bound on devices addressed for one person and app in a single send. */+export const MAX_DEVICE_TOKENS_PER_APP = 20++export interface DeviceSubscription {+ /** Every person property holding this token, so a dead token is pruned from all of them at once.+ * A device can appear under both supported key shapes, and removing one would leave the other to+ * fail on the next send. */+ propertyKeys: string[]+ token: string+}++/** Person property key holding one device's push token. Mirrors `device_subscription_key` in+ * `push_subscriptions.py`; the two must agree or a registration lands on a key sends never read. */+export function deviceSubscriptionKey(appIdentifier: string, token: string): string {+ return `${DEVICE_SUBSCRIPTION_PREFIX}${appIdentifier}:${createHash('sha256')+ .update(token)+ .digest('hex')+ .slice(0, 16)}`+}+/**- * Extract the device token from the $device_push_subscription_<appIdentifier> person property.+ * Every device token registered for this person and app.*- * The property value is the encrypted device token.- * Returns the decrypted token, or null if the property is missing or fails to decrypt.+ * Two key shapes carry a token. `<prefix><app>:<digest>` holds one device each. `<prefix><app>` holds+ * a single device for the whole app, and a device is reachable there until it next registers. Both+ * are read, so a person is addressed on every device whichever shape it is stored under.*/-export function getDevicePushSubscriptionToken(+export function getDevicePushSubscriptions(personProperties: Record<string, any> | undefined,appIdentifier: string,encryptedFields: EncryptedFields-): string | null {- const value = personProperties?.[`$device_push_subscription_${appIdentifier}`]- if (!value || typeof value !== 'string') {- return null+): DeviceSubscription[] {+ if (!personProperties) {+ return []}- // Require successful decryption. The subscription endpoint always stores this token encrypted, so a- // value that fails to decrypt was forged directly onto the person property via a plain `$set` capture- // event (a raw token). Ignore it rather than delivering to an unverified device.- try {- return encryptedFields.decrypt(value) ?? null- } catch {- return null+ const legacyKey = `${DEVICE_SUBSCRIPTION_PREFIX}${appIdentifier}`+ const devicePrefix = `${legacyKey}:`+ const subscriptions: DeviceSubscription[] = []+ const seen = new Map<string, DeviceSubscription>()++ // Sorted so a person over the cap keeps the same devices from one send to the next, rather than+ // a set that shifts with property insertion order.+ for (const propertyKey of Object.keys(personProperties).sort()) {+ if (propertyKey !== legacyKey && !propertyKey.startsWith(devicePrefix)) {+ continue+ }+ const value = personProperties[propertyKey]+ if (!value || typeof value !== 'string') {+ continue+ }++ // Require successful decryption. The subscription endpoint always stores this token encrypted, so a+ // value that fails to decrypt was forged directly onto the person property via a plain `$set` capture+ // event (a raw token). Ignore it rather than delivering to an unverified device.+ let token: string | null = null+ try {+ token = encryptedFields.decrypt(value) ?? null+ } catch {+ continue+ }+ if (!token) {+ continue+ }+ // One device can hold the same token under both shapes, so send once and carry both keys.+ const existing = seen.get(token)+ if (existing) {+ existing.propertyKeys.push(propertyKey)+ continue+ }+ const subscription = { propertyKeys: [propertyKey], token }+ seen.set(token, subscription)+ subscriptions.push(subscription)+ if (subscriptions.length >= MAX_DEVICE_TOKENS_PER_APP) {+ break+ }}++ return subscriptions+}++/**+ * One device token for this person and app, or null.+ *+ * Kept for the `push_subscription` hog function input, whose value is a single token a template+ * reads. A person with several devices resolves to the first by key order.+ */+export function getDevicePushSubscriptionToken(+ personProperties: Record<string, any> | undefined,+ appIdentifier: string,+ encryptedFields: EncryptedFields+): string | null {+ return getDevicePushSubscriptions(personProperties, appIdentifier, encryptedFields)[0]?.token ?? null}diff --git a/products/messaging/backend/api/push_subscriptions.py b/products/messaging/backend/api/push_subscriptions.pyindex 8d837957bd04..07de31c24f86 100644--- a/products/messaging/backend/api/push_subscriptions.py+++ b/products/messaging/backend/api/push_subscriptions.py@@ -105,6 +105,8 @@ MAX_BODY_BYTES = 16 * 1024# cached on the instance, so a module-level singleton avoids re-deriving on every request._encrypted_fields = EncryptedFieldMixin()+DEVICE_SUBSCRIPTION_PREFIX = "$device_push_subscription_"+# Verification-mode precedence. An app_id can match more than one integration — config identifiers# (project_id / bundle_id) aren't covered by a uniqueness constraint — so mode resolution must fail@@ -207,6 +209,23 @@ def _parse_user_agent_sdk(request: Request) -> _SdkIdentity:return _SdkIdentity(name=name[:64], version=version.split()[0][:32])+def device_subscription_key(app_id: str, device_token: str) -> str:+ """Person property key holding one device's push token.++ Naming the device in the key is what lets a person hold several devices on one app; a key on the+ app alone holds one token, and a second device on the same platform replaces the first.++ The device part is a digest of the token rather than a client-supplied id, so an SDK already in+ the field lands on the right key without shipping a new build. A device that keeps its token+ re-registers onto the same key. A device whose token rotates lands on a new key, and the provider+ reports the old one unregistered on the next send, which prunes it.++ A colon separates the two parts. Neither a Firebase project id nor an APNs bundle id can contain+ one, so the app part of an existing key can never be read as an app plus a device.+ """+ return f"{DEVICE_SUBSCRIPTION_PREFIX}{app_id}:{hashlib.sha256(device_token.encode()).hexdigest()[:16]}"++def _api_key_fingerprint(api_key: str) -> str:# A stable, non-reversible fingerprint of the submitted token, so many invalid-token rejections# can be grouped to one source without logging the raw credential. Keyed with the server secret@@ -447,17 +466,21 @@ def push_subscriptions(request: Request):app_id=app_id,)- property_key = f"$device_push_subscription_{app_id}"+ property_key = device_subscription_key(app_id, device_token)+ # The app-wide key holds a single device for the whole app. A device is reachable there until it+ # next registers, and the send path reads it, so one stored that way stays addressable.+ legacy_property_key = f"{DEVICE_SUBSCRIPTION_PREFIX}{app_id}"- # $unset of an absent property is a no-op, so DELETE (logout) is idempotent. device_token is- # required for a symmetric contract but isn't matched against the stored value: logout clears- # this app_id's subscription regardless of which token the client last held.+ # $unset of an absent property is a no-op, so DELETE (logout) is idempotent.properties: dict[str, dict[str, str] | list[str]]if request.method == "POST":properties = {"$set": {property_key: _encrypted_fields.encrypt(device_token)}}failure_message = "Failed to store push subscription."else:- properties = {"$unset": [property_key]}+ # The legacy key goes with it. One device cannot tell whether that key holds its own token or+ # another device's, so logout clears it as it always did rather than leaving a token behind+ # that nothing can attribute.+ properties = {"$unset": [property_key, legacy_property_key]}failure_message = "Failed to remove push subscription."try:diff --git a/products/messaging/backend/api/test/test_push_subscriptions.py b/products/messaging/backend/api/test/test_push_subscriptions.pyindex 9294e968b464..4fdc69948c5b 100644--- a/products/messaging/backend/api/test/test_push_subscriptions.py+++ b/products/messaging/backend/api/test/test_push_subscriptions.py@@ -26,6 +26,7 @@ from products.messaging.backend.api.push_subscriptions import (_api_key_fingerprint,_parse_user_agent_sdk,_SdkIdentity,+ device_subscription_key,)@@ -114,7 +115,61 @@ class TestPushSubscriptionsAPI(BaseTest):assert call_kwargs["distinct_id"] == "user-1"assert call_kwargs["event_name"] == "$set"assert call_kwargs["process_person_profile"] is True- assert "$device_push_subscription_my-firebase-project" in call_kwargs["properties"]["$set"]+ assert any(+ key.startswith("$device_push_subscription_my-firebase-project:")+ for key in call_kwargs["properties"]["$set"]+ )++ @patch("products.messaging.backend.api.push_subscriptions.capture_internal")+ def test_two_devices_on_one_app_are_stored_under_separate_keys(self, mock_capture: MagicMock):+ # A second device on the same app used to overwrite the first, leaving it unreachable.+ mock_capture.return_value = MagicMock(status_code=200)++ keys = []+ for device_token in ("fcm-token-phone", "fcm-token-tablet"):+ mock_capture.reset_mock()+ response = self._post(+ {+ "distinct_id": "user-1",+ "device_token": device_token,+ "app_id": "my-firebase-project",+ }+ )+ assert response.status_code == status.HTTP_200_OK+ keys.append(next(iter(mock_capture.call_args.kwargs["properties"]["$set"])))++ assert keys[0] != keys[1]+ assert keys == [+ device_subscription_key("my-firebase-project", "fcm-token-phone"),+ device_subscription_key("my-firebase-project", "fcm-token-tablet"),+ ]++ @patch("products.messaging.backend.api.push_subscriptions.capture_internal")+ def test_the_same_device_registering_twice_reuses_its_key(self, mock_capture: MagicMock):+ # Re-registration must not accumulate a key per call.+ mock_capture.return_value = MagicMock(status_code=200)++ keys = []+ for _ in range(2):+ mock_capture.reset_mock()+ self._post(+ {+ "distinct_id": "user-1",+ "device_token": "fcm-token-phone",+ "app_id": "my-firebase-project",+ }+ )+ keys.append(next(iter(mock_capture.call_args.kwargs["properties"]["$set"])))++ assert keys[0] == keys[1]++ def test_device_key_matches_the_digest_the_send_path_derives(self):+ # The nodejs read path rebuilds this key from the same digest. If the two drift, a+ # registration lands on a key sends never look at. Pinned on both sides to this literal.+ assert (+ device_subscription_key("my-project", "device-token-abc123")+ == "$device_push_subscription_my-project:7d8d408df65cffa5"+ )@patch("products.messaging.backend.api.push_subscriptions.capture_internal")def test_register_ios_token(self, mock_capture: MagicMock):@@ -135,7 +190,9 @@ class TestPushSubscriptionsAPI(BaseTest):mock_capture.assert_called_once()call_kwargs = mock_capture.call_args.kwargs- assert "$device_push_subscription_com.example.app" in call_kwargs["properties"]["$set"]+ assert any(+ key.startswith("$device_push_subscription_com.example.app:") for key in call_kwargs["properties"]["$set"]+ )@patch("products.messaging.backend.api.push_subscriptions.capture_internal")def test_ios_device_registers_a_firebase_token(self, mock_capture: MagicMock):@@ -154,7 +211,10 @@ class TestPushSubscriptionsAPI(BaseTest):assert response.status_code == status.HTTP_200_OKcall_kwargs = mock_capture.call_args.kwargs- assert "$device_push_subscription_my-firebase-project" in call_kwargs["properties"]["$set"]+ assert any(+ key.startswith("$device_push_subscription_my-firebase-project:")+ for key in call_kwargs["properties"]["$set"]+ )@patch("products.messaging.backend.api.push_subscriptions.capture_internal")def test_token_is_encrypted(self, mock_capture: MagicMock):@@ -172,7 +232,7 @@ class TestPushSubscriptionsAPI(BaseTest):assert response.status_code == status.HTTP_200_OKcall_kwargs = mock_capture.call_args.kwargs- encrypted_value = call_kwargs["properties"]["$set"]["$device_push_subscription_my-firebase-project"]+ encrypted_value = next(iter(call_kwargs["properties"]["$set"].values()))# The encrypted value should not be the raw tokenassert encrypted_value != "fcm-device-token-abc"# It should be a non-empty string (Fernet token)@@ -203,7 +263,10 @@ class TestPushSubscriptionsAPI(BaseTest):assert call_kwargs["event_name"] == "$set"assert call_kwargs["process_person_profile"] is True# Unregister clears the property instead of storing a token.- assert call_kwargs["properties"] == {"$unset": ["$device_push_subscription_my-firebase-project"]}+ assert call_kwargs["properties"]["$unset"] == [+ device_subscription_key("my-firebase-project", "fcm-device-token-abc"),+ "$device_push_subscription_my-firebase-project",+ ]@patch("products.messaging.backend.api.push_subscriptions.capture_internal")def test_unregister_ios_token(self, mock_capture: MagicMock):@@ -220,7 +283,7 @@ class TestPushSubscriptionsAPI(BaseTest):assert response.status_code == status.HTTP_200_OKcall_kwargs = mock_capture.call_args.kwargs- assert call_kwargs["properties"]["$unset"] == ["$device_push_subscription_com.example.app"]+ assert call_kwargs["properties"]["$unset"][-1] == "$device_push_subscription_com.example.app"@patch("products.messaging.backend.api.push_subscriptions.capture_internal")def test_unregister_without_integration_still_unsets(self, mock_capture: MagicMock):@@ -237,7 +300,7 @@ class TestPushSubscriptionsAPI(BaseTest):assert response.status_code == status.HTTP_200_OKcall_kwargs = mock_capture.call_args.kwargs- assert call_kwargs["properties"]["$unset"] == ["$device_push_subscription_nonexistent-project"]+ assert call_kwargs["properties"]["$unset"][-1] == "$device_push_subscription_nonexistent-project"def test_missing_api_key_returns_401(self):response = self.client.post(@@ -308,7 +371,10 @@ class TestPushSubscriptionsAPI(BaseTest):assert response.status_code == status.HTTP_200_OKassert "platform" not in response.json()assert capture.call_count == 1- assert "$device_push_subscription_my-firebase-project" in capture.call_args.kwargs["properties"]["$set"]+ assert any(+ key.startswith("$device_push_subscription_my-firebase-project:")+ for key in capture.call_args.kwargs["properties"]["$set"]+ )def test_platform_sent_by_older_sdks_is_ignored(self):with patch("products.messaging.backend.api.push_subscriptions.capture_internal") as capture: