diff --git a/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts b/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts index 353f77ef9..272242c06 100644 --- a/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts +++ b/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts @@ -90,6 +90,7 @@ function makeRoom() { const encryptedPush = (eventId: string) => ({ type: 'm.room.encrypted', + user_id: '@user:example.com', room_id: '!room:example.com', room_name: 'Room', event_id: eventId, @@ -148,9 +149,34 @@ describe('UnifiedPushNotifications', () => { async function listenAndPush(payload: Record, settings = makeSettings()) { await listenForUnifiedPushMessages(() => settings as never); - pushHandler({ message: JSON.stringify(payload) }); + pushHandler({ + message: JSON.stringify({ user_id: '@user:example.com', ...payload }), + }); } + it('ignores pushes without an exact active-account identity', async () => { + await listenForUnifiedPushMessages(() => makeSettings() as never); + + pushHandler({ + message: JSON.stringify({ + type: 'm.room.message', + room_id: '!room:example.com', + content: { body: 'unscoped' }, + }), + }); + pushHandler({ + message: JSON.stringify({ + type: 'm.room.message', + user_id: '@other:example.com', + room_id: '!room:example.com', + content: { body: 'wrong account' }, + }), + }); + + await vi.waitFor(() => expect(notificationsApi.sendNotification).not.toHaveBeenCalled()); + expect(matrixClient.getRoom).not.toHaveBeenCalled(); + }); + it('posts an encrypted baseline before a hanging local decryption completes', async () => { matrixClient.getRoom.mockReturnValue(makeRoom()); let resolveDecryption!: (content: Record) => void; diff --git a/src/app/features/settings/notifications/UnifiedPushNotifications.ts b/src/app/features/settings/notifications/UnifiedPushNotifications.ts index b6506caf4..8c1846f94 100644 --- a/src/app/features/settings/notifications/UnifiedPushNotifications.ts +++ b/src/app/features/settings/notifications/UnifiedPushNotifications.ts @@ -1034,7 +1034,11 @@ async function handleUnifiedPushPayload( const pushData = (raw.extra ?? raw) as UnifiedPushPayload; const eventType = pushData?.type as EventType | undefined; - const userId = pushData?.user_id ?? settings.mx.getUserId() ?? ''; + const userId = isNonEmptyString(pushData?.user_id) ? pushData.user_id.trim() : undefined; + if (!userId || userId !== settings.mx.getUserId()) { + unifiedPushLog.warn('notification', 'Ignoring push without an exact active-account match'); + return; + } if (eventType) { await handleRichPushPayload(pushData, settings, userId, getSettings); diff --git a/src/app/pages/client/client-non-ui/notifications.test.tsx b/src/app/pages/client/client-non-ui/notifications.test.tsx index d5ec92346..7eb648e3a 100644 --- a/src/app/pages/client/client-non-ui/notifications.test.tsx +++ b/src/app/pages/client/client-non-ui/notifications.test.tsx @@ -2,7 +2,9 @@ import { render, waitFor } from '@testing-library/react'; import { Provider, createStore } from 'jotai'; import { MemoryRouter } from 'react-router-dom'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { NativeNotificationClickRouting } from './notifications'; +import { NativeNotificationActionRouting, NativeNotificationClickRouting } from './notifications'; +import { activeSessionIdAtom, pendingNotificationAtom } from '$state/sessions'; +import { nativeNotificationRepliesAtom } from '$state/nativeNotificationReplies'; // Controllable platform gates + a capturable notifications API. The click-routing // effect only calls onNotificationClicked, so the rest of the plugin surface is stubbed @@ -15,10 +17,29 @@ const platform = vi.hoisted(() => ({ const notificationsApi = vi.hoisted(() => ({ onNotificationClicked: vi - .fn<() => Promise<{ unregister: () => void }>>() + .fn< + ( + handler: (event: { data?: Record }) => void + ) => Promise<{ unregister: () => void }> + >() .mockResolvedValue({ unregister: () => {} }), })); +const matrixClient = vi.hoisted(() => ({ + getUserId: vi.fn<() => string>(() => '@user:example.com'), + getRoom: vi.fn<() => { getMyMembership: () => string }>(() => ({ + getMyMembership: () => 'join', + })), + getSyncState: vi.fn<() => string>(() => 'SYNCING'), + sendMessage: vi.fn<() => Promise>().mockResolvedValue(undefined), +})); + +const notificationUtils = vi.hoisted(() => ({ + markAsRead: vi.fn<() => Promise>().mockResolvedValue(undefined), +})); + +const toast = vi.hoisted(() => ({ showToast: vi.fn<(message: string) => void>() })); + const getTauriNotificationsApi = vi.hoisted(() => vi.fn<() => Promise>().mockResolvedValue(notificationsApi) ); @@ -34,15 +55,22 @@ vi.mock('$features/settings/notifications/TauriNotificationsApiClient', () => ({ IOS_NOTIFICATION_SOUND: 'notification.caf', })); +vi.mock('$hooks/useMatrixClient', () => ({ useMatrixClient: () => matrixClient })); +vi.mock('$state/hooks/settings', () => ({ + useSetting: () => [false, vi.fn<(value: unknown) => void>()], +})); +vi.mock('$utils/notifications', () => notificationUtils); +vi.mock('$state/toast', () => toast); + function setPlatform(kind: 'android' | 'ios' | 'desktop' | 'web') { platform.isAndroidTauri.mockReturnValue(kind === 'android'); platform.isIosTauri.mockReturnValue(kind === 'ios'); platform.isDesktopTauri.mockReturnValue(kind === 'desktop'); } -function renderRouting() { +function renderRouting(store = createStore()) { return render( - + @@ -54,6 +82,8 @@ beforeEach(() => { vi.clearAllMocks(); getTauriNotificationsApi.mockResolvedValue(notificationsApi); notificationsApi.onNotificationClicked.mockResolvedValue({ unregister: () => {} }); + matrixClient.sendMessage.mockResolvedValue(undefined); + notificationUtils.markAsRead.mockResolvedValue(undefined); }); afterEach(() => { @@ -99,4 +129,60 @@ describe('NativeNotificationClickRouting', () => { expect(getTauriNotificationsApi).not.toHaveBeenCalled(); expect(notificationsApi.onNotificationClicked).not.toHaveBeenCalled(); }); + + it('ignores unscoped clicks and switches account before routing scoped invites', async () => { + setPlatform('android'); + const store = createStore(); + let clickHandler!: (event: { data?: Record }) => void; + notificationsApi.onNotificationClicked.mockImplementation(async (handler) => { + clickHandler = handler; + return { unregister: () => {} }; + }); + renderRouting(store); + await waitFor(() => expect(clickHandler).toBeTypeOf('function')); + + clickHandler({ data: { type: 'invite', room_id: '!room:example.com' } }); + expect(store.get(activeSessionIdAtom)).not.toBe('@other:example.com'); + expect(store.get(pendingNotificationAtom)).toBeNull(); + + clickHandler({ + data: { + type: 'invite', + user_id: '@other:example.com', + room_id: '!room:example.com', + }, + }); + expect(store.get(activeSessionIdAtom)).toBe('@other:example.com'); + }); +}); + +describe('NativeNotificationActionRouting', () => { + it('does not report a successful reply as failed when marking it read fails', async () => { + setPlatform('web'); + const store = createStore(); + store.set(nativeNotificationRepliesAtom, [ + { + key: 'reply', + userId: '@user:example.com', + roomId: '!room:example.com', + eventId: '$event', + text: 'hello', + createdAt: Date.now(), + }, + ]); + notificationUtils.markAsRead.mockRejectedValueOnce(new Error('receipt failed')); + + render( + + + + + + ); + + await waitFor(() => expect(matrixClient.sendMessage).toHaveBeenCalledOnce()); + await waitFor(() => expect(store.get(nativeNotificationRepliesAtom)).toEqual([])); + expect(notificationUtils.markAsRead).toHaveBeenCalledOnce(); + expect(toast.showToast).not.toHaveBeenCalled(); + }); }); diff --git a/src/app/pages/client/client-non-ui/notifications.tsx b/src/app/pages/client/client-non-ui/notifications.tsx index a5936f509..4a22c4b0d 100644 --- a/src/app/pages/client/client-non-ui/notifications.tsx +++ b/src/app/pages/client/client-non-ui/notifications.tsx @@ -705,6 +705,7 @@ function registerNativeNotificationListener( // payload attached in sendNativeTauriNotification. export function NativeNotificationClickRouting() { const setPending = useSetAtom(pendingNotificationAtom); + const setActiveSessionId = useSetAtom(activeSessionIdAtom); const navigate = useNavigate(); useEffect( @@ -717,6 +718,8 @@ export function NativeNotificationClickRouting() { .catch(() => {}); } if (!data) return; + if (!data.user_id) return; + setActiveSessionId(data.user_id); if (data.type === 'invite') { navigate(getInboxInvitesPath()); return; @@ -730,7 +733,7 @@ export function NativeNotificationClickRouting() { } }) ), - [setPending, navigate] + [setPending, setActiveSessionId, navigate] ); return null; @@ -815,7 +818,7 @@ export function NativeNotificationActionRouting() { .sendMessage(item.roomId, null, { msgtype: MsgType.Text, body: item.text }) // Replying is reading; otherwise the room stays unread and its // notification lingers while later pushes stack onto it. - .then(() => markAsRead(mx, item.roomId, hideReads)) + .then(() => markAsRead(mx, item.roomId, hideReads).catch(() => undefined)) .catch(() => { showToast('Reply was not sent. Open the room to retry.'); })