Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(ios): push notification device registration (#5348)
Peter Chinmand5f0e88975d6
diff --git a/.sqlx/query-78f1cf9da464937604c1a2d5115c014cab9de72bd88605ff47a316baa2c7acc2.json b/.sqlx/query-78f1cf9da464937604c1a2d5115c014cab9de72bd88605ff47a316baa2c7acc2.jsondeleted file mode 100644index 9e6f7f8877..0000000000--- a/.sqlx/query-78f1cf9da464937604c1a2d5115c014cab9de72bd88605ff47a316baa2c7acc2.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT d.device_endpoint\n FROM notification_user_device_registration d\n WHERE d.device_token = $1\n LIMIT 1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "device_endpoint",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false- ]- },- "hash": "78f1cf9da464937604c1a2d5115c014cab9de72bd88605ff47a316baa2c7acc2"-}diff --git a/.sqlx/query-270cd8ae6b47508cb7e4e920bd76cb0f6177d685bddedb06f1892d0014af6f01.json b/.sqlx/query-a89be8ead6a9c4614b738c82ffeb34fcad4e23fe3f2c30a6223d0fc05d2fe22f.jsonsimilarity index 77%rename from .sqlx/query-270cd8ae6b47508cb7e4e920bd76cb0f6177d685bddedb06f1892d0014af6f01.jsonrename to .sqlx/query-a89be8ead6a9c4614b738c82ffeb34fcad4e23fe3f2c30a6223d0fc05d2fe22f.jsonindex ee1916f8f5..a20ceafd0d 100644--- a/.sqlx/query-270cd8ae6b47508cb7e4e920bd76cb0f6177d685bddedb06f1892d0014af6f01.json+++ b/.sqlx/query-a89be8ead6a9c4614b738c82ffeb34fcad4e23fe3f2c30a6223d0fc05d2fe22f.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n DELETE FROM notification_user_device_registration\n WHERE device_token = $1 AND device_type = $2\n RETURNING device_endpoint\n ",+ "query": "\n DELETE FROM notification_user_device_registration\n WHERE device_token = $1 AND device_type = $2 AND device_endpoint != $3\n RETURNING device_endpoint\n ","describe": {"columns": [{@@ -23,12 +23,13 @@]}}- }+ },+ "Text"]},"nullable": [false]},- "hash": "270cd8ae6b47508cb7e4e920bd76cb0f6177d685bddedb06f1892d0014af6f01"+ "hash": "a89be8ead6a9c4614b738c82ffeb34fcad4e23fe3f2c30a6223d0fc05d2fe22f"}diff --git a/.sqlx/query-c30215af0b9eed6ebb9aee2ab60c847dc1766df4e5280c91067a1ce92c9f40d5.json b/.sqlx/query-c30215af0b9eed6ebb9aee2ab60c847dc1766df4e5280c91067a1ce92c9f40d5.jsonnew file mode 100644index 0000000000..e51f8b3627--- /dev/null+++ b/.sqlx/query-c30215af0b9eed6ebb9aee2ab60c847dc1766df4e5280c91067a1ce92c9f40d5.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT d.device_endpoint\n FROM notification_user_device_registration d\n WHERE d.device_token = $1 AND d.device_type = $2\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "device_endpoint",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ {+ "Custom": {+ "name": "notification_device_type_option",+ "kind": {+ "Enum": [+ "ios",+ "android",+ "iosvoip"+ ]+ }+ }+ }+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "c30215af0b9eed6ebb9aee2ab60c847dc1766df4e5280c91067a1ce92c9f40d5"+}diff --git a/.sqlx/query-dc14a4d8f89e55287b4dccb4422e52fa08b7bc0e4836b505315b03c633bc3381.json b/.sqlx/query-dc14a4d8f89e55287b4dccb4422e52fa08b7bc0e4836b505315b03c633bc3381.jsonnew file mode 100644index 0000000000..379b7388e5--- /dev/null+++ b/.sqlx/query-dc14a4d8f89e55287b4dccb4422e52fa08b7bc0e4836b505315b03c633bc3381.json@@ -0,0 +1,35 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM notification_user_device_registration\n WHERE user_id = $1 AND device_token = $2 AND device_type = $3\n RETURNING device_endpoint\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "device_endpoint",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ {+ "Custom": {+ "name": "notification_device_type_option",+ "kind": {+ "Enum": [+ "ios",+ "android",+ "iosvoip"+ ]+ }+ }+ }+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "dc14a4d8f89e55287b4dccb4422e52fa08b7bc0e4836b505315b03c633bc3381"+}diff --git a/apps/web/src/features/channel/Call/use-callkit.ts b/apps/web/src/features/channel/Call/use-callkit.tsindex 50e37c7500..c2eac1e0ba 100644--- a/apps/web/src/features/channel/Call/use-callkit.ts+++ b/apps/web/src/features/channel/Call/use-callkit.ts@@ -1,4 +1,5 @@import { whenSplitManagerReady } from '@app/signal/splitLayout';+import { registerPushRegistrationLifecycle } from '@core/auth/push-registration-lifecycle';import { ENABLE_CALLKIT } from '@core/constant/featureFlags';import { useChannelsContext } from '@core/context/channels';import { isPlatform, isTauri } from '@core/util/platform';@@ -23,6 +24,51 @@ import { useCallKitThemeSync } from './use-callkit-theme-sync';// regenerated to include it yet. Cast until a regeneration picks it up.const DEVICE_TYPE_IOS_VOIP = 'iosvoip' as DeviceType;+async function getCachedVoipToken(): Promise<string | null> {+ const { token } = await invoke<{ token: string | null }>(+ 'plugin:call-kit|get_voip_token'+ );+ return token;+}++async function registerVoipToken(token: string): Promise<void> {+ const res = await notificationServiceClient.registerDevice({+ token,+ deviceType: DEVICE_TYPE_IOS_VOIP,+ });+ if (res.isErr()) {+ // The client returns a Result and never rejects — throw so callers (and+ // the push lifecycle's retry) can see the failure.+ throw new Error(+ `failed to register VoIP token: ${res.error.map((e) => e.code).join(',')}`+ );+ }+}++/** Register the cached PushKit token (if any) under the current session's user. */+async function syncVoipRegistration(): Promise<void> {+ const token = await getCachedVoipToken();+ if (!token) return;+ console.info('[callkit] registering cached VoIP token', {+ tokenLength: token.length,+ });+ await registerVoipToken(token);+}++async function unregisterVoipForLogout(): Promise<void> {+ const token = await getCachedVoipToken();+ if (!token) return;+ const res = await notificationServiceClient.unregisterDevice({+ token,+ deviceType: DEVICE_TYPE_IOS_VOIP,+ });+ if (res.isErr()) {+ throw new Error(+ `failed to unregister VoIP token: ${res.error.map((e) => e.code).join(',')}`+ );+ }+}+type VoipTokenPayload = { token: string };type CallAnsweredPayload = { channelId: string; nativeMedia?: boolean };type CallEndedPayload = { callId: string };@@ -251,6 +297,7 @@ export function useCallKitSetup() {);}+ // Token rotation: PushKit can hand us a new token at any point at runtime.trackListener(addPluginListener<VoipTokenPayload>('call-kit',@@ -259,31 +306,26 @@ export function useCallKitSetup() {console.info('[callkit] received VoIP token update', {tokenLength: token.length,});- await notificationServiceClient- .registerDevice({ token, deviceType: DEVICE_TYPE_IOS_VOIP })- .catch((err) =>- console.error('[callkit] failed to register VoIP token', err)- );+ await registerVoipToken(token).catch((err) =>+ console.error('[callkit] failed to register VoIP token', err)+ );}),'voip-token-updated');- // Drain any VoIP token that arrived from PushKit before the listener above- // was registered (common on first launch).- invoke<{ token: string | null }>('plugin:call-kit|get_voip_token')- .then(({ token }) => {- if (!token) return;- console.info('[callkit] registering cached VoIP token', {- tokenLength: token.length,- });- return notificationServiceClient- .registerDevice({ token, deviceType: DEVICE_TYPE_IOS_VOIP })- .catch((err) =>- console.error('[callkit] failed to register cached VoIP token', err)- );- })- .catch((err) => console.error('[callkit] get_voip_token failed', err));+ // Cold start: drain any token that arrived from PushKit before the+ // listener above was registered.+ syncVoipRegistration().catch((err) =>+ console.error('[callkit] failed to register cached VoIP token', err)+ );++ // Account switch: rebind on login and remove on logout so the previous account's calls stop ringing this device. Registrations are idempotent upserts, so overlap between these three triggers is harmless.+ const removeVoipLifecycle = registerPushRegistrationLifecycle({+ syncRegistration: syncVoipRegistration,+ unregisterForLogout: unregisterVoipForLogout,+ });+ onCleanup(removeVoipLifecycle);const handleCallAnswered = ({ channelId, nativeMedia }: CallAnsweredPayload,diff --git a/apps/web/src/lib/core/auth/logout.ts b/apps/web/src/lib/core/auth/logout.tsindex ee156aed50..c5ef3b572d 100644--- a/apps/web/src/lib/core/auth/logout.ts+++ b/apps/web/src/lib/core/auth/logout.ts@@ -9,8 +9,10 @@ import { emailKeys } from '@queries/email/keys';import { propertiesKeys } from '@queries/properties/keys';import { clearDocumentQueryCache } from '@queries/storage/document-cache';import { authServiceClient } from '@service-auth/client';+import { raceTimeout } from '@solid-primitives/promise';import { createCallback } from '@solid-primitives/rootless';import { useNavigate } from '@solidjs/router';+import { unregisterPushRegistrationsForLogout } from './push-registration-lifecycle';const unauthenticatedUserInfo: UserInfoData = {id: '',@@ -48,6 +50,9 @@ export function useLogout() {const navigate = useNavigate();return createCallback(async () => {+ // Must run before the session is torn down — the unregister call is+ // authenticated. Time-boxed so a hung request can't block logout.+ await raceTimeout(unregisterPushRegistrationsForLogout(), 3000);await clearLocalAuthSession();await authServiceClient.logout();analytics.track('sign_out');diff --git a/apps/web/src/lib/core/auth/push-registration-lifecycle.ts b/apps/web/src/lib/core/auth/push-registration-lifecycle.tsnew file mode 100644index 0000000000..ff1d2424ec--- /dev/null+++ b/apps/web/src/lib/core/auth/push-registration-lifecycle.ts@@ -0,0 +1,72 @@+/**+ * Registry connecting the auth lifecycle to push-notification device+ * registration.+ *+ * The backend keys a device token to a single user, so registrations must be+ * rebound on every login and removed on logout — otherwise the device keeps+ * receiving the previous account's pushes. Platform modules (APNs/FCM alert+ * push, iOS VoIP push) each register a lifecycle here; the login/logout flows+ * invoke all registered lifecycles.+ */++export type PushRegistrationLifecycle = {+ /** (Re-)register this device's push token under the current session's user. */+ syncRegistration: () => Promise<void>;+ /** Unregister this device's push token for the currently logged-in user. */+ unregisterForLogout: () => Promise<void>;+};++const lifecycles = new Set<PushRegistrationLifecycle>();++/** Register a platform push lifecycle. Returns a function that removes it. */+export function registerPushRegistrationLifecycle(+ lifecycle: PushRegistrationLifecycle+): () => void {+ lifecycles.add(lifecycle);+ return () => lifecycles.delete(lifecycle);+}++const SYNC_RETRY_DELAY_MS = 5_000;++/**+ * (Re-)register this device's push tokens under the current session's user.+ * Call whenever a session is established — on login or at app launch with an+ * existing session.+ *+ * A failed sync leaves the previous account's registration in place on the+ * backend, so each lifecycle gets one short delayed retry against transient+ * failures (network blip, backend error).+ */+export async function syncPushRegistrations(): Promise<void> {+ await Promise.all(+ [...lifecycles].map(async (lifecycle) => {+ try {+ await lifecycle.syncRegistration();+ } catch (err) {+ console.error('push registration sync failed; retrying once', err);+ await new Promise((resolve) =>+ setTimeout(resolve, SYNC_RETRY_DELAY_MS)+ );+ try {+ await lifecycle.syncRegistration();+ } catch (retryErr) {+ console.error('push registration sync retry failed', retryErr);+ }+ }+ })+ );+}++/**+ * Best-effort unregister of this device's push registrations. Must run while+ * the session is still valid — the unregister call is authenticated.+ */+export async function unregisterPushRegistrationsForLogout(): Promise<void> {+ await Promise.all(+ [...lifecycles].map((lifecycle) =>+ lifecycle.unregisterForLogout().catch((err) => {+ console.error('failed to unregister push registration on logout', err);+ })+ )+ );+}diff --git a/apps/web/src/lib/queries/auth/user-info.ts b/apps/web/src/lib/queries/auth/user-info.tsindex 30b408669d..4b8cb1f7b7 100644--- a/apps/web/src/lib/queries/auth/user-info.ts+++ b/apps/web/src/lib/queries/auth/user-info.ts@@ -1,3 +1,4 @@+import { syncPushRegistrations } from '@core/auth/push-registration-lifecycle';import { enableUserInfoQuery } from '@core/context/user-info-gate';import { hasLoginCookie } from '@core/util/cookies';import { catchToResult, type ResultType, throwOnErr } from '@core/util/result';@@ -50,7 +51,13 @@ export function invalidateUserInfo() {/** Invalidate all queries after a successful login. */export function invalidateAllAfterLogin() {enableUserInfoQuery();- return queryClient.invalidateQueries();+ const invalidated = queryClient.invalidateQueries();+ // Rebind this device's push registrations once the refetches above have+ // exercised the fresh session — registering earlier can race auth state+ // that is still settling. Fire-and-forget so login isn't blocked on the+ // notification service.+ void invalidated.catch(() => {}).then(() => syncPushRegistrations());+ return invalidated;}/** Ensure user info is in the query cache. Fetches if not present. */diff --git a/apps/web/src/lib/tauri/PushNotification.tsx b/apps/web/src/lib/tauri/PushNotification.tsxindex 929b1cdbef..107b85c1a9 100644--- a/apps/web/src/lib/tauri/PushNotification.tsx+++ b/apps/web/src/lib/tauri/PushNotification.tsx@@ -1,3 +1,8 @@+import {+ registerPushRegistrationLifecycle,+ syncPushRegistrations,+} from '@core/auth/push-registration-lifecycle';+import { hasLoginCookie } from '@core/util/cookies';import { whenSettled } from '@core/util/whenSettled';import {checkPermissions,@@ -14,12 +19,14 @@ import {} from '@notifications';import { notificationServiceClient } from '@service-notification/client';import { makePersisted } from '@solid-primitives/storage';+import { removeAllActive } from '@tauri-apps/plugin-notification';import {createContext,createEffect,createResource,createSignal,type JSX,+ onCleanup,} from 'solid-js';import { createTauriNotificationInterface } from './notification';import { useExpectTauri } from './TauriProvider';@@ -50,9 +57,17 @@ function usePushNotifications(deviceType,token,});- const result = res.isOk() ? ('granted' as const) : ('denied' as const);- setPermission(result);- return result;+ if (res.isErr()) {+ // A failed registration is always a transient condition (network blip,+ // auth still settling, backend error) — the endpoint has no "rejected"+ // semantics. Only success may write the persisted state: flipping it to+ // 'denied' here would disable remote-push dedupe and report push as off+ // in Settings until the next successful sync.+ console.error('failed to register device for push', res.error);+ return 'denied';+ }+ setPermission('granted');+ return 'granted';}async function requestNotificationRegistration() {@@ -76,10 +91,13 @@ function usePushNotifications(const token = registrationResult()?.token;if (token) {- await notificationServiceClient.unregisterDevice({+ const res = await notificationServiceClient.unregisterDevice({deviceType,token,});+ if (res.isErr()) {+ console.error('failed to unregister device for push', res.error);+ }} else {console.warn('Cannot unregister device with no token set');}@@ -87,40 +105,68 @@ function usePushNotifications(setPermission(undefined);}- // On launch, once permission state resolves, ensure persisted state is synced correct, and check if the APNS token has rotated.- // iOS returns the same token if valid, or a new one if it has rotated.+ // (Re-)register this device under whoever is currently logged in. The+ // backend keys a token to a single user, so this must run on every login —+ // not just when the APNs token rotates — or the previous account keeps+ // receiving this device's pushes.+ async function syncDeviceRegistration() {+ const sysPerm = await checkPermissions();+ if (sysPerm.status !== 'granted') return;+ const freshResult = await registerForRemoteNotifications();+ if (!freshResult.token) return;+ const storedToken = registrationResult()?.token;+ if (storedToken && storedToken !== freshResult.token) {+ // Best-effort: unregister the old token+ notificationServiceClient+ .unregisterDevice({ deviceType, token: storedToken })+ .catch(console.error);+ }+ setRegistrationResult(freshResult);+ const result = await registerDeviceWithNotificationService(+ freshResult.token+ );+ if (result !== 'granted') {+ // Surface the failure so the lifecycle's retry (and its logging) see it.+ throw new Error('push device registration did not complete');+ }+ }++ async function unregisterForLogout() {+ // The logged-out account's already-delivered notifications must not+ // linger in the system notification center for the next account to see.+ await Promise.all([+ removeAllActive().catch(console.error),+ unregisterPushNotifications(),+ ]);+ }++ const removeLifecycle = registerPushRegistrationLifecycle({+ syncRegistration: syncDeviceRegistration,+ unregisterForLogout,+ });+ onCleanup(removeLifecycle);++ // On launch, once permission state resolves, ensure persisted state is+ // synced correctly and — when a session exists — re-register the device so+ // the backend registration tracks the current user (covering both an APNs+ // token rotation and an account switch since the last launch).whenSettled(systemPermission,(perm) => {- // We defensively ensure our persisted perm state is synced properly, for backwards compatiblity+ // OS permission was revoked externally (iOS Settings) — clear the+ // persisted registration state so it never claims 'granted' when+ // notifications can't display.if (perm.status !== 'granted') {setPermission(undefined);return;}- const storedToken = registrationResult()?.token;- if (!storedToken) {- setPermission(undefined);+ if (!hasLoginCookie()) {+ // Logged out: nothing to register against; login will sync.return;}- if (permission() !== 'granted') {- setPermission('granted');- }-- registerForRemoteNotifications()- .then((freshResult) => {- if (freshResult.token && freshResult.token !== storedToken) {- // Best-effort unregister the old token- notificationServiceClient.unregisterDevice({- deviceType,- token: storedToken,- });- setRegistrationResult(freshResult);- registerDeviceWithNotificationService(freshResult.token).catch(- console.error- );- }- })- .catch(console.error);+ // Sync via the lifecycle registry so the launch path gets the same+ // one-retry behavior as login (registrations are idempotent).+ syncPushRegistrations().catch(console.error);},console.error);diff --git a/crates/notification/src/domain/ports.rs b/crates/notification/src/domain/ports.rsindex 57fc01f0c3..d14673517e 100644--- a/crates/notification/src/domain/ports.rs+++ b/crates/notification/src/domain/ports.rs@@ -193,6 +193,7 @@ pub trait NotificationRepository: Send + Sync + 'static {fn get_device_endpoint(&self,device_token: &str,+ device_type: &DeviceType,) -> impl Future<Output = Result<Option<String>, Report>> + Send;/// Upsert a device registration: create a new one or update the existing@@ -205,14 +206,28 @@ pub trait NotificationRepository: Send + Sync + 'static {device_type: &DeviceType,) -> impl Future<Output = Result<(), Report>> + Send;- /// Delete the device registration matching the given token and type.+ /// Delete all of the user's device registrations matching the given token+ /// and type.///- /// Returns the endpoint ARN that was removed.- fn delete_device_by_token(+ /// Returns the endpoint ARNs that were removed (empty if none matched).+ fn delete_user_devices_by_token(&self,+ user_id: MacroUserIdStr<'_>,device_token: &str,device_type: &DeviceType,- ) -> impl Future<Output = Result<String, Report>> + Send;+ ) -> impl Future<Output = Result<Vec<String>, Report>> + Send;++ /// Delete registrations that share the given token and type but point at a+ /// different endpoint than `active_endpoint` — stale rows left behind when+ /// SNS minted a new endpoint for the same physical device.+ ///+ /// Returns the endpoint ARNs that were removed.+ fn delete_stale_devices_by_token(+ &self,+ device_token: &str,+ device_type: &DeviceType,+ active_endpoint: &str,+ ) -> impl Future<Output = Result<Vec<String>, Report>> + Send;/// Delete a device registration by its endpoint ARN.fn delete_device_by_endpoint(diff --git a/crates/notification/src/domain/service/device/test.rs b/crates/notification/src/domain/service/device/test.rsindex 762fd5812e..461f35ac98 100644--- a/crates/notification/src/domain/service/device/test.rs+++ b/crates/notification/src/domain/service/device/test.rs@@ -19,7 +19,10 @@ fn test_user_id() -> MacroUserIdStr<'static> {struct MockNotifRepo {existing_endpoint: Mutex<Option<String>>,upserted: Mutex<Vec<(String, String, String, String)>>,- deleted_token_result: Mutex<Result<String, &'static str>>,+ deleted_token_result: Mutex<Result<Vec<String>, &'static str>>,+ deleted_token_calls: Mutex<Vec<(String, String)>>,+ stale_endpoints: Mutex<Vec<String>>,+ stale_delete_calls: Mutex<Vec<(String, String)>>,}impl MockNotifRepo {@@ -27,7 +30,10 @@ impl MockNotifRepo {Self {existing_endpoint: Mutex::new(Some(endpoint.to_string())),upserted: Mutex::new(Vec::new()),- deleted_token_result: Mutex::new(Ok("arn:default".to_string())),+ deleted_token_result: Mutex::new(Ok(vec!["arn:default".to_string()])),+ deleted_token_calls: Mutex::new(Vec::new()),+ stale_endpoints: Mutex::new(Vec::new()),+ stale_delete_calls: Mutex::new(Vec::new()),}}@@ -35,18 +41,30 @@ impl MockNotifRepo {Self {existing_endpoint: Mutex::new(None),upserted: Mutex::new(Vec::new()),- deleted_token_result: Mutex::new(Ok("arn:default".to_string())),+ deleted_token_result: Mutex::new(Ok(vec!["arn:default".to_string()])),+ deleted_token_calls: Mutex::new(Vec::new()),+ stale_endpoints: Mutex::new(Vec::new()),+ stale_delete_calls: Mutex::new(Vec::new()),}}- fn with_delete_result(mut self, result: Result<String, &'static str>) -> Self {+ fn with_delete_result(mut self, result: Result<Vec<String>, &'static str>) -> Self {self.deleted_token_result = Mutex::new(result);self}++ fn with_stale_endpoints(mut self, endpoints: Vec<String>) -> Self {+ self.stale_endpoints = Mutex::new(endpoints);+ self+ }}impl NotificationRepository for MockNotifRepo {- async fn get_device_endpoint(&self, _device_token: &str) -> Result<Option<String>, Report> {+ async fn get_device_endpoint(+ &self,+ _device_token: &str,+ _device_type: &DeviceType,+ ) -> Result<Option<String>, Report> {Ok(self.existing_endpoint.lock().unwrap().clone())}@@ -66,11 +84,16 @@ impl NotificationRepository for MockNotifRepo {Ok(())}- async fn delete_device_by_token(+ async fn delete_user_devices_by_token(&self,- _device_token: &str,+ user_id: macro_user_id::user_id::MacroUserIdStr<'_>,+ device_token: &str,_device_type: &DeviceType,- ) -> Result<String, Report> {+ ) -> Result<Vec<String>, Report> {+ self.deleted_token_calls+ .lock()+ .unwrap()+ .push((user_id.to_string(), device_token.to_string()));self.deleted_token_result.lock().unwrap()@@ -78,6 +101,19 @@ impl NotificationRepository for MockNotifRepo {.map_err(|e| rootcause::report!("{e}"))}+ async fn delete_stale_devices_by_token(+ &self,+ device_token: &str,+ _device_type: &DeviceType,+ active_endpoint: &str,+ ) -> Result<Vec<String>, Report> {+ self.stale_delete_calls+ .lock()+ .unwrap()+ .push((device_token.to_string(), active_endpoint.to_string()));+ Ok(self.stale_endpoints.lock().unwrap().clone())+ }+async fn delete_device_by_endpoint(&self, _: &str) -> Result<(), Report> {unimplemented!()}@@ -480,32 +516,120 @@ async fn register_android_uses_fcm_arn() {.unwrap();}+#[tokio::test]+async fn register_prunes_stale_registrations_for_token() {+ let db = MockNotifRepo::with_existing_endpoint("arn:existing")+ .with_stale_endpoints(vec!["arn:stale-1".to_string(), "arn:stale-2".to_string()]);+ let sns = MockSnsManager::new();+ let service = make_service(db, sns);++ service+ .register_device(test_user_id(), "device-token", &DeviceType::Ios)+ .await+ .unwrap();++ // Pruning must exclude the endpoint that was just upserted.+ let stale_calls = service.repository.stale_delete_calls.lock().unwrap();+ assert_eq!(stale_calls.len(), 1);+ assert_eq!(stale_calls[0].1, "arn:existing");++ let deleted = service.sns_endpoint.deleted.lock().unwrap();+ assert_eq!(*deleted, vec!["arn:stale-1", "arn:stale-2"]);+}++#[tokio::test]+async fn register_succeeds_when_stale_sns_delete_fails() {+ let db = MockNotifRepo::with_existing_endpoint("arn:existing")+ .with_stale_endpoints(vec!["arn:stale".to_string()]);+ let mut sns = MockSnsManager::new();+ sns.should_fail = true;+ let service = make_service(db, sns);++ service+ .register_device(test_user_id(), "device-token", &DeviceType::Ios)+ .await+ .unwrap();++ let upserted = service.repository.upserted.lock().unwrap();+ assert_eq!(upserted.len(), 1);+}+// ─── Unregister Tests ────────────────────────────────────────────────────#[tokio::test]async fn unregister_happy_path() {- let db = MockNotifRepo::empty().with_delete_result(Ok("arn:to-delete".to_string()));+ let db = MockNotifRepo::empty().with_delete_result(Ok(vec!["arn:to-delete".to_string()]));let sns = MockSnsManager::new();let service = make_service(db, sns);service- .unregister_device("device-token", &DeviceType::Ios)+ .unregister_device(test_user_id(), "device-token", &DeviceType::Ios).await.unwrap();let deleted = service.sns_endpoint.deleted.lock().unwrap();assert_eq!(deleted.len(), 1);assert_eq!(deleted[0], "arn:to-delete");++ // The delete must be scoped to the calling user.+ let calls = service.repository.deleted_token_calls.lock().unwrap();+ assert_eq!(calls.len(), 1);+ assert_eq!(calls[0].0, test_user_id().to_string());+}++#[tokio::test]+async fn unregister_no_matching_rows_succeeds() {+ let db = MockNotifRepo::empty().with_delete_result(Ok(Vec::new()));+ let sns = MockSnsManager::new();+ let service = make_service(db, sns);++ service+ .unregister_device(test_user_id(), "device-token", &DeviceType::Ios)+ .await+ .unwrap();++ let deleted = service.sns_endpoint.deleted.lock().unwrap();+ assert!(deleted.is_empty());+}++#[tokio::test]+async fn unregister_deletes_all_matching_endpoints() {+ let db = MockNotifRepo::empty()+ .with_delete_result(Ok(vec!["arn:a".to_string(), "arn:b".to_string()]));+ let sns = MockSnsManager::new();+ let service = make_service(db, sns);++ service+ .unregister_device(test_user_id(), "device-token", &DeviceType::Ios)+ .await+ .unwrap();++ let deleted = service.sns_endpoint.deleted.lock().unwrap();+ assert_eq!(*deleted, vec!["arn:a", "arn:b"]);+}++#[tokio::test]+async fn unregister_succeeds_when_sns_delete_fails() {+ let db = MockNotifRepo::empty()+ .with_delete_result(Ok(vec!["arn:a".to_string(), "arn:b".to_string()]));+ let mut sns = MockSnsManager::new();+ sns.should_fail = true;+ let service = make_service(db, sns);++ service+ .unregister_device(test_user_id(), "device-token", &DeviceType::Ios)+ .await+ .unwrap();}#[tokio::test]async fn unregister_db_error_propagates() {- let db = MockNotifRepo::empty().with_delete_result(Err("device not found"));+ let db = MockNotifRepo::empty().with_delete_result(Err("db error"));let sns = MockSnsManager::new();let service = make_service(db, sns);let result = service- .unregister_device("device-token", &DeviceType::Ios)+ .unregister_device(test_user_id(), "device-token", &DeviceType::Ios).await;assert!(result.is_err());diff --git a/crates/notification/src/domain/service/ingress.rs b/crates/notification/src/domain/service/ingress.rsindex 8c5b45431f..124b76dfc4 100644--- a/crates/notification/src/domain/service/ingress.rs+++ b/crates/notification/src/domain/service/ingress.rs@@ -130,12 +130,16 @@ pub trait NotificationReader: Send + Sync + 'static {device_type: &DeviceType,) -> impl std::future::Future<Output = Result<(), Report>> + Send;- /// Unregister a device from push notifications.+ /// Unregister the user's device from push notifications.///- /// Deletes the device registration from the database (by token + type),- /// then deletes the SNS endpoint.+ /// Deletes the user's device registrations matching the token + type, then+ /// best-effort deletes the associated SNS endpoints (an SNS failure does+ /// not fail the call — the DB rows are already gone). Succeeds when+ /// nothing matched, so logout can call this without checking prior+ /// registration state.fn unregister_device(&self,+ user_id: MacroUserIdStr<'_>,device_token: &str,device_type: &DeviceType,) -> impl std::future::Future<Output = Result<(), Report>> + Send;@@ -747,7 +751,11 @@ where};// Get endpoint if exists, otherwise create new one- let endpoint = match self.repository.get_device_endpoint(device_token).await {+ let endpoint = match self+ .repository+ .get_device_endpoint(device_token, device_type)+ .await+ {Ok(Some(endpoint)) => endpoint,_ => {self.sns_endpoint@@ -787,21 +795,51 @@ where.upsert_device(user_id, device_token, &endpoint, device_type).await?;+ // A device token must map to a single registration. When SNS minted a+ // different endpoint for this token in the past (e.g. under another+ // user), those rows would keep receiving that user's notifications on+ // this device — remove them and their SNS endpoints.+ let stale_endpoints = self+ .repository+ .delete_stale_devices_by_token(device_token, device_type, &endpoint)+ .await?;+ for stale_endpoint in stale_endpoints {+ let _ = self+ .sns_endpoint+ .delete_endpoint(&stale_endpoint)+ .await+ .inspect_err(|e| {+ tracing::warn!(error=?e, endpoint = %stale_endpoint, "failed to delete stale SNS endpoint");+ });+ }+Ok(())}#[tracing::instrument(err, skip(self))]async fn unregister_device(&self,+ user_id: MacroUserIdStr<'_>,device_token: &str,device_type: &DeviceType,) -> Result<(), Report> {- let endpoint = self+ let endpoints = self.repository- .delete_device_by_token(device_token, device_type)+ .delete_user_devices_by_token(user_id, device_token, device_type).await?;- self.sns_endpoint.delete_endpoint(&endpoint).await?;+ // The DB rows are gone, so the unregistration has already succeeded;+ // SNS endpoint deletion is best-effort cleanup and must not fail the+ // call or abort the remaining endpoints.+ for endpoint in endpoints {+ let _ = self+ .sns_endpoint+ .delete_endpoint(&endpoint)+ .await+ .inspect_err(|e| {+ tracing::warn!(error=?e, endpoint = %endpoint, "failed to delete SNS endpoint during unregister");+ });+ }Ok(())}diff --git a/crates/notification/src/domain/service/push_notification_event/test.rs b/crates/notification/src/domain/service/push_notification_event/test.rsindex 1754805da6..24ad79c638 100644--- a/crates/notification/src/domain/service/push_notification_event/test.rs+++ b/crates/notification/src/domain/service/push_notification_event/test.rs@@ -185,7 +185,11 @@ impl NotificationRepository for MockNotifRepo {) -> Result<(), Report> {unimplemented!()}- async fn get_device_endpoint(&self, _: &str) -> Result<Option<String>, Report> {+ async fn get_device_endpoint(+ &self,+ _: &str,+ _: &crate::domain::models::device::DeviceType,+ ) -> Result<Option<String>, Report> {unimplemented!()}async fn upsert_device(@@ -197,11 +201,20 @@ impl NotificationRepository for MockNotifRepo {) -> Result<(), Report> {unimplemented!()}- async fn delete_device_by_token(+ async fn delete_user_devices_by_token(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ _: &str,+ _: &crate::domain::models::device::DeviceType,+ ) -> Result<Vec<String>, Report> {+ unimplemented!()+ }+ async fn delete_stale_devices_by_token(&self,_: &str,_: &crate::domain::models::device::DeviceType,- ) -> Result<String, Report> {+ _: &str,+ ) -> Result<Vec<String>, Report> {unimplemented!()}async fn get_users_with_type_disabled<'a>(diff --git a/crates/notification/src/domain/service/test.rs b/crates/notification/src/domain/service/test.rsindex b4e8a9526b..1df04bc69c 100644--- a/crates/notification/src/domain/service/test.rs+++ b/crates/notification/src/domain/service/test.rs@@ -393,7 +393,11 @@ impl NotificationRepository for MockRepository {Ok(())}- async fn get_device_endpoint(&self, _device_token: &str) -> Result<Option<String>, Report> {+ async fn get_device_endpoint(+ &self,+ _device_token: &str,+ _device_type: &DeviceType,+ ) -> Result<Option<String>, Report> {Ok(None)}@@ -407,12 +411,22 @@ impl NotificationRepository for MockRepository {Ok(())}- async fn delete_device_by_token(+ async fn delete_user_devices_by_token(&self,+ _user_id: MacroUserIdStr<'_>,_device_token: &str,_device_type: &DeviceType,- ) -> Result<String, Report> {- Ok(String::new())+ ) -> Result<Vec<String>, Report> {+ Ok(Vec::new())+ }++ async fn delete_stale_devices_by_token(+ &self,+ _device_token: &str,+ _device_type: &DeviceType,+ _active_endpoint: &str,+ ) -> Result<Vec<String>, Report> {+ Ok(Vec::new())}async fn delete_device_by_endpoint(&self, _endpoint_arn: &str) -> Result<(), Report> {@@ -617,8 +631,14 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {(**self).delete_all_user_notifications(user_id).await}- async fn get_device_endpoint(&self, device_token: &str) -> Result<Option<String>, Report> {- (**self).get_device_endpoint(device_token).await+ async fn get_device_endpoint(+ &self,+ device_token: &str,+ device_type: &DeviceType,+ ) -> Result<Option<String>, Report> {+ (**self)+ .get_device_endpoint(device_token, device_type)+ .await}async fn upsert_device(@@ -633,13 +653,25 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {.await}- async fn delete_device_by_token(+ async fn delete_user_devices_by_token(&self,+ user_id: MacroUserIdStr<'_>,device_token: &str,device_type: &DeviceType,- ) -> Result<String, Report> {+ ) -> Result<Vec<String>, Report> {+ (**self)+ .delete_user_devices_by_token(user_id, device_token, device_type)+ .await+ }++ async fn delete_stale_devices_by_token(+ &self,+ device_token: &str,+ device_type: &DeviceType,+ active_endpoint: &str,+ ) -> Result<Vec<String>, Report> {(**self)- .delete_device_by_token(device_token, device_type)+ .delete_stale_devices_by_token(device_token, device_type, active_endpoint).await}diff --git a/crates/notification/src/domain/service/voip/test.rs b/crates/notification/src/domain/service/voip/test.rsindex 4220f812fc..45d7afdbc7 100644--- a/crates/notification/src/domain/service/voip/test.rs+++ b/crates/notification/src/domain/service/voip/test.rs@@ -62,7 +62,11 @@ impl NotificationRepository for MockRepo {.map_err(|e| rootcause::report!("{e}"))}- async fn get_device_endpoint(&self, _: &str) -> Result<Option<String>, Report> {+ async fn get_device_endpoint(+ &self,+ _: &str,+ _: &crate::domain::models::device::DeviceType,+ ) -> Result<Option<String>, Report> {unimplemented!()}async fn upsert_device(@@ -74,11 +78,20 @@ impl NotificationRepository for MockRepo {) -> Result<(), Report> {unimplemented!()}- async fn delete_device_by_token(+ async fn delete_user_devices_by_token(&self,+ _: MacroUserIdStr<'_>,_: &str,_: &crate::domain::models::device::DeviceType,- ) -> Result<String, Report> {+ ) -> Result<Vec<String>, Report> {+ unimplemented!()+ }+ async fn delete_stale_devices_by_token(+ &self,+ _: &str,+ _: &crate::domain::models::device::DeviceType,+ _: &str,+ ) -> Result<Vec<String>, Report> {unimplemented!()}async fn delete_device_by_endpoint(&self, _: &str) -> Result<(), Report> {diff --git a/crates/notification/src/inbound/http/device.rs b/crates/notification/src/inbound/http/device.rsindex bd546db4ca..bb853f7099 100644--- a/crates/notification/src/inbound/http/device.rs+++ b/crates/notification/src/inbound/http/device.rs@@ -52,23 +52,27 @@ async fn register_device<S: NotificationReader, Auth: MacroAuthorizationService>Ok(Json(()))}-/// Unregister a device from push notifications.-#[tracing::instrument(skip(state, _macro_user, req))]+/// Unregister the calling user's device from push notifications.+#[tracing::instrument(skip(state, user, req))]async fn unregister_device<S: NotificationReader, Auth: MacroAuthorizationService>(State(state): State<NotificationRouterState<S, Auth>>,- _macro_user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,Json(req): Json<DeviceRequest>,) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {state.inner- .unregister_device(&req.token, &req.device_type)+ .unregister_device(+ user.authorization.user.macro_user_id,+ &req.token,+ &req.device_type,+ ).await.map_err(|e| {tracing::error!(error=?e, "failed to unregister device");(- StatusCode::NOT_FOUND,+ StatusCode::INTERNAL_SERVER_ERROR,Json(ErrorResponse {- message: "device not found".into(),+ message: "unable to unregister device".into(),}),)})?;diff --git a/crates/notification/src/inbound/http/test.rs b/crates/notification/src/inbound/http/test.rsindex 6a1f576fc2..18c92f77ff 100644--- a/crates/notification/src/inbound/http/test.rs+++ b/crates/notification/src/inbound/http/test.rs@@ -166,6 +166,7 @@ impl NotificationReader for AuthenticationTestService {fn unregister_device(&self,+ _user_id: MacroUserIdStr<'_>,_device_token: &str,_device_type: &DeviceType,) -> impl Future<Output = Result<(), Report>> + Send {@@ -647,6 +648,7 @@ impl NotificationReader for PresignedTestService {fn unregister_device(&self,+ _user_id: MacroUserIdStr<'_>,_device_token: &str,_device_type: &DeviceType,) -> impl Future<Output = Result<(), Report>> + Send {diff --git a/crates/notification/src/outbound/device_registration.rs b/crates/notification/src/outbound/device_registration.rsindex 2c5256c5ae..2f2b1ab5e4 100644--- a/crates/notification/src/outbound/device_registration.rs+++ b/crates/notification/src/outbound/device_registration.rs@@ -15,10 +15,11 @@ pub trait DeviceRegistrationDbOps: Send + Sync + 'static {endpoint_arn: &str,) -> impl std::future::Future<Output = Result<(), Report>> + Send;- /// Look up an existing device endpoint ARN by its device token.+ /// Look up an existing device endpoint ARN by its device token and type.fn get_device_endpoint(&self,device_token: &str,+ device_type: &DeviceType,) -> impl std::future::Future<Output = Result<Option<String>, Report>> + Send;/// Upsert a device registration.@@ -30,12 +31,23 @@ pub trait DeviceRegistrationDbOps: Send + Sync + 'static {device_type: &DeviceType,) -> impl std::future::Future<Output = Result<(), Report>> + Send;- /// Delete by token and type, returning the endpoint ARN.- fn delete_by_token(+ /// Delete all of the user's registrations matching the token and type,+ /// returning the removed endpoint ARNs.+ fn delete_user_devices_by_token(+ &self,+ user_id: MacroUserIdStr<'_>,+ device_token: &str,+ device_type: &DeviceType,+ ) -> impl std::future::Future<Output = Result<Vec<String>, Report>> + Send;++ /// Delete registrations sharing the token and type but pointing at a+ /// different endpoint, returning the removed endpoint ARNs.+ fn delete_stale_devices_by_token(&self,device_token: &str,device_type: &DeviceType,- ) -> impl std::future::Future<Output = Result<String, Report>> + Send;+ active_endpoint: &str,+ ) -> impl std::future::Future<Output = Result<Vec<String>, Report>> + Send;}impl DeviceRegistrationDbOps for PgPool {@@ -53,15 +65,20 @@ impl DeviceRegistrationDbOps for PgPool {Ok(())}- async fn get_device_endpoint(&self, device_token: &str) -> Result<Option<String>, Report> {+ async fn get_device_endpoint(+ &self,+ device_token: &str,+ device_type: &DeviceType,+ ) -> Result<Option<String>, Report> {let result = sqlx::query!(r#"SELECT d.device_endpointFROM notification_user_device_registration d- WHERE d.device_token = $1+ WHERE d.device_token = $1 AND d.device_type = $2LIMIT 1"#,- device_token+ device_token,+ device_type as _,).map(|row| row.device_endpoint).fetch_optional(self)@@ -97,23 +114,50 @@ impl DeviceRegistrationDbOps for PgPool {Ok(())}- async fn delete_by_token(+ async fn delete_user_devices_by_token(&self,+ user_id: MacroUserIdStr<'_>,device_token: &str,device_type: &DeviceType,- ) -> Result<String, Report> {- let result = sqlx::query!(+ ) -> Result<Vec<String>, Report> {+ let user_id_str = user_id.as_ref();+ let endpoints = sqlx::query!(r#"DELETE FROM notification_user_device_registration- WHERE device_token = $1 AND device_type = $2+ WHERE user_id = $1 AND device_token = $2 AND device_type = $3RETURNING device_endpoint"#,+ user_id_str,device_token,device_type as _,)- .fetch_one(self)+ .map(|row| row.device_endpoint)+ .fetch_all(self)+ .await?;++ Ok(endpoints)+ }++ async fn delete_stale_devices_by_token(+ &self,+ device_token: &str,+ device_type: &DeviceType,+ active_endpoint: &str,+ ) -> Result<Vec<String>, Report> {+ let endpoints = sqlx::query!(+ r#"+ DELETE FROM notification_user_device_registration+ WHERE device_token = $1 AND device_type = $2 AND device_endpoint != $3+ RETURNING device_endpoint+ "#,+ device_token,+ device_type as _,+ active_endpoint,+ )+ .map(|row| row.device_endpoint)+ .fetch_all(self).await?;- Ok(result.device_endpoint)+ Ok(endpoints)}}diff --git a/crates/notification/src/outbound/repository.rs b/crates/notification/src/outbound/repository.rsindex c246421ade..35bd1ac227 100644--- a/crates/notification/src/outbound/repository.rs+++ b/crates/notification/src/outbound/repository.rs@@ -1702,8 +1702,12 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificatiself.db.delete_all_user_notifications(user_id).await}- async fn get_device_endpoint(&self, device_token: &str) -> Result<Option<String>, Report> {- self.db.get_device_endpoint(device_token).await+ async fn get_device_endpoint(+ &self,+ device_token: &str,+ device_type: &DeviceType,+ ) -> Result<Option<String>, Report> {+ self.db.get_device_endpoint(device_token, device_type).await}async fn upsert_device(@@ -1718,12 +1722,26 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati.await}- async fn delete_device_by_token(+ async fn delete_user_devices_by_token(&self,+ user_id: MacroUserIdStr<'_>,device_token: &str,device_type: &DeviceType,- ) -> Result<String, Report> {- self.db.delete_by_token(device_token, device_type).await+ ) -> Result<Vec<String>, Report> {+ self.db+ .delete_user_devices_by_token(user_id, device_token, device_type)+ .await+ }++ async fn delete_stale_devices_by_token(+ &self,+ device_token: &str,+ device_type: &DeviceType,+ active_endpoint: &str,+ ) -> Result<Vec<String>, Report> {+ self.db+ .delete_stale_devices_by_token(device_token, device_type, active_endpoint)+ .await}async fn delete_device_by_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {diff --git a/tooling/notification_sandbox/src/adapters/sandbox_repository.rs b/tooling/notification_sandbox/src/adapters/sandbox_repository.rsindex 41b29cf214..bc4b0b06fe 100644--- a/tooling/notification_sandbox/src/adapters/sandbox_repository.rs+++ b/tooling/notification_sandbox/src/adapters/sandbox_repository.rs@@ -202,8 +202,14 @@ impl NotificationRepository for SandboxNotificationRepository {self.inner.delete_all_user_notifications(user_id).await}- async fn get_device_endpoint(&self, device_token: &str) -> Result<Option<String>, Report> {- self.inner.get_device_endpoint(device_token).await+ async fn get_device_endpoint(+ &self,+ device_token: &str,+ device_type: &DeviceType,+ ) -> Result<Option<String>, Report> {+ self.inner+ .get_device_endpoint(device_token, device_type)+ .await}async fn upsert_device(@@ -218,13 +224,25 @@ impl NotificationRepository for SandboxNotificationRepository {.await}- async fn delete_device_by_token(+ async fn delete_user_devices_by_token(+ &self,+ user_id: MacroUserIdStr<'_>,+ device_token: &str,+ device_type: &DeviceType,+ ) -> Result<Vec<String>, Report> {+ self.inner+ .delete_user_devices_by_token(user_id, device_token, device_type)+ .await+ }++ async fn delete_stale_devices_by_token(&self,device_token: &str,device_type: &DeviceType,- ) -> Result<String, Report> {+ active_endpoint: &str,+ ) -> Result<Vec<String>, Report> {self.inner- .delete_device_by_token(device_token, device_type)+ .delete_stale_devices_by_token(device_token, device_type, active_endpoint).await}