diff --git a/.changeset/fix-call-sticky-memberships.md b/.changeset/fix-call-sticky-memberships.md new file mode 100644 index 000000000..c9c72c53f --- /dev/null +++ b/.changeset/fix-call-sticky-memberships.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix calls disconnecting on servers that use sticky memberships: the call now has permission to publish them, and sticky memberships also reach clients that sync with sliding sync. diff --git a/src/app/crypto/engineCrypto/EngineCrypto.ts b/src/app/crypto/engineCrypto/EngineCrypto.ts index ae0e9201f..a6f772824 100644 --- a/src/app/crypto/engineCrypto/EngineCrypto.ts +++ b/src/app/crypto/engineCrypto/EngineCrypto.ts @@ -374,8 +374,6 @@ export class EngineCrypto #deviceCreationTimeMs: number | null | undefined; - #hasBackupDecryptionKey: boolean | undefined; - readonly #eventsPendingKey = new Map>(); readonly #backupDownloader: PerSessionBackupDownloader; @@ -1243,11 +1241,13 @@ export class EngineCrypto return this.#deviceCreationTimeMs; } - async #hasSessionBackupKey(): Promise { - if (this.#hasBackupDecryptionKey === undefined) { - this.#hasBackupDecryptionKey = (await this.getSessionBackupPrivateKey()) !== null; - } - return this.#hasBackupDecryptionKey; + async #hasSessionBackupKey(backupInfo: KeyBackupInfo): Promise { + const keys = (await this.#call('getBackupKeys')) as EngineBackupKeys | null; + return ( + !!keys?.decryptionKeyBase64 && + keys.backupVersion === backupInfo.version && + EngineCrypto.#keyMatchesBackup(keys.decryptionKeyBase64, backupInfo) + ); } async #throwIfHistorical(event: MatrixEvent, details: Record): Promise { @@ -1263,7 +1263,7 @@ export class EngineCrypto ); } - const usable = await this.#hasSessionBackupKey(); + const usable = await this.#hasSessionBackupKey(backupInfo); throw new DecryptionError( usable ? DecryptionFailureCode.HISTORICAL_MESSAGE_WORKING_BACKUP @@ -2082,7 +2082,6 @@ export class EngineCrypto async storeSessionBackupPrivateKey(key: Uint8Array, version: string): Promise { await this.#call('saveBackupDecryptionKey', { decryptionKey: encodeBase64(key), version }); - this.#hasBackupDecryptionKey = true; this.emit(CryptoEvent.KeyBackupDecryptionKeyCached, version); } @@ -2272,7 +2271,6 @@ export class EngineCrypto async #disableKeyBackup(): Promise { await this.#call('disableBackup'); - this.#hasBackupDecryptionKey = undefined; this.emit(CryptoEvent.KeyBackupStatus, false); } diff --git a/src/app/crypto/engineCrypto/decryptionErrors.test.ts b/src/app/crypto/engineCrypto/decryptionErrors.test.ts index 7f3df00cb..ab5b996c2 100644 --- a/src/app/crypto/engineCrypto/decryptionErrors.test.ts +++ b/src/app/crypto/engineCrypto/decryptionErrors.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; +import * as RustSdkCryptoJs from '@matrix-org/matrix-sdk-crypto-wasm'; import { DecryptionFailureCode } from 'matrix-js-sdk/lib/crypto-api'; import { KnownMembership } from '$types/matrix-sdk'; import type { MatrixClient, MatrixEvent } from '$types/matrix-sdk'; @@ -11,25 +12,30 @@ vi.mock('../olmMachine/engineInvoke', () => ({ const mockInvoke = vi.mocked(engineInvoke); -const BACKUP_INFO = { +let backupDecryptionKeyBase64: string; +let publicKey: string; + +const backupInfo = () => ({ version: '7', algorithm: 'm.megolm_backup.v1.curve25519-aes-sha2', - auth_data: { public_key: 'cHVibGlj' }, -}; + auth_data: { public_key: publicKey }, +}); type EngineState = { code: number; maybeWithheld?: string | null; deviceCreationTimeMs?: number; decryptionKeyBase64?: string | null; + backupVersion?: string | null; }; -const client = (backupInfo: unknown = BACKUP_INFO) => +const client = (serverBackupInfo: unknown = backupInfo()) => ({ http: { authedRequest: vi.fn<(...args: never[]) => Promise>(async () => { - if (backupInfo === null) throw Object.assign(new Error('nope'), { errcode: 'M_NOT_FOUND' }); - return backupInfo; + if (serverBackupInfo === null) + throw Object.assign(new Error('nope'), { errcode: 'M_NOT_FOUND' }); + return serverBackupInfo; }), }, }) as unknown as MatrixClient; @@ -39,13 +45,14 @@ const engine = ({ maybeWithheld = null, deviceCreationTimeMs = 0, decryptionKeyBase64 = null, + backupVersion = '7', }: EngineState) => { mockInvoke.mockImplementation(async (_identity, method) => { if (method === 'decryptRoomEvent') { return { className: 'DecryptionError', code, description: 'engine says no', maybeWithheld }; } if (method === 'deviceCreationTimeMs') return deviceCreationTimeMs; - if (method === 'getBackupKeys') return { backupVersion: '7', decryptionKeyBase64 }; + if (method === 'getBackupKeys') return { backupVersion, decryptionKeyBase64 }; if (method === 'backupVersion') return null; return null; }); @@ -74,6 +81,14 @@ const codeOf = async (promise: Promise) => { }; describe('decryption failures', () => { + beforeEach(async () => { + await RustSdkCryptoJs.initAsync(); + const key = RustSdkCryptoJs.BackupDecryptionKey.createRandomKey(); + backupDecryptionKeyBase64 = key.toBase64(); + publicKey = key.megolmV1PublicKey.publicKeyBase64; + key.free(); + }); + beforeEach(() => mockInvoke.mockReset()); it('reports a missing room key rather than a bare unknown error', async () => { @@ -133,8 +148,52 @@ describe('decryption failures', () => { ); }); + it('does not promise history recovery for a key without a backup version', async () => { + engine({ + code: 0, + deviceCreationTimeMs: 5000, + decryptionKeyBase64: 'AAAA', + backupVersion: null, + }); + + expect(await codeOf(decrypt(eventAt(100)))).toBe( + DecryptionFailureCode.HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED + ); + }); + + it('does not promise history recovery for a key from another backup version', async () => { + engine({ + code: 0, + deviceCreationTimeMs: 5000, + decryptionKeyBase64: 'AAAA', + backupVersion: '6', + }); + + expect(await codeOf(decrypt(eventAt(100)))).toBe( + DecryptionFailureCode.HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED + ); + }); + + it('does not promise history recovery for a key that cannot open the backup', async () => { + const other = RustSdkCryptoJs.BackupDecryptionKey.createRandomKey(); + const mx = client({ + ...backupInfo(), + auth_data: { public_key: other.megolmV1PublicKey.publicKeyBase64 }, + }); + other.free(); + engine({ code: 0, deviceCreationTimeMs: 5000, decryptionKeyBase64: backupDecryptionKeyBase64 }); + + expect(await codeOf(decrypt(eventAt(100), mx))).toBe( + DecryptionFailureCode.HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED + ); + }); + it('reports history a working backup should eventually supply', async () => { - engine({ code: 0, deviceCreationTimeMs: 5000, decryptionKeyBase64: 'AAAA' }); + engine({ + code: 0, + deviceCreationTimeMs: 5000, + decryptionKeyBase64: backupDecryptionKeyBase64, + }); expect(await codeOf(decrypt(eventAt(100)))).toBe( DecryptionFailureCode.HISTORICAL_MESSAGE_WORKING_BACKUP diff --git a/src/app/features/settings/notifications/NotificationTransportRuntimeFeature.test.tsx b/src/app/features/settings/notifications/NotificationTransportRuntimeFeature.test.tsx index 26829c876..f4d825dae 100644 --- a/src/app/features/settings/notifications/NotificationTransportRuntimeFeature.test.tsx +++ b/src/app/features/settings/notifications/NotificationTransportRuntimeFeature.test.tsx @@ -4,7 +4,10 @@ import { NotificationTransportRuntimeFeature } from './NotificationTransportRunt const mocks = vi.hoisted(() => ({ enable: vi.fn<(...args: unknown[]) => Promise<{ endpoint: string }>>(), - config: { pushTransport: { unifiedPushEmbeddedServerUrl: 'https://push.example' } }, + config: { pushTransport: { unifiedPushEmbeddedServerUrl: 'https://push.example' } } as { + pushTransport?: { unifiedPushEmbeddedServerUrl?: string }; + pushNotificationDetails?: { unifiedPushEmbeddedServerUrl?: string }; + }, overrides: {} as { unifiedPushEmbeddedServerUrl?: string }, mx: {}, setSetting: vi.fn<() => void>(), @@ -41,6 +44,7 @@ vi.mock('./NativePushNotifications', () => ({ beforeEach(() => { mocks.enable.mockReset().mockResolvedValue({ endpoint: 'https://push.example/topic' }); mocks.overrides = {}; + mocks.config = { pushTransport: { unifiedPushEmbeddedServerUrl: 'https://push.example' } }; }); it('keeps the configured built-in server during startup registration', async () => { @@ -63,3 +67,16 @@ it('uses the saved built-in server override during startup registration', async ) ); }); + +it('falls back to the built-in server from the push notification details', async () => { + mocks.config = { + pushNotificationDetails: { unifiedPushEmbeddedServerUrl: 'https://custom.example' }, + }; + render(); + await waitFor(() => + expect(mocks.enable).toHaveBeenCalledWith( + mocks.mx, + expect.objectContaining({ unifiedPushEmbeddedServerUrl: 'https://custom.example' }) + ) + ); +}); diff --git a/src/app/features/settings/notifications/NotificationTransportRuntimeFeature.tsx b/src/app/features/settings/notifications/NotificationTransportRuntimeFeature.tsx index 26c2990ad..6ad7d03c5 100644 --- a/src/app/features/settings/notifications/NotificationTransportRuntimeFeature.tsx +++ b/src/app/features/settings/notifications/NotificationTransportRuntimeFeature.tsx @@ -109,8 +109,8 @@ export function NotificationTransportRuntimeFeature() { const upConfigRef = useRef<{ unifiedPushAppID?: string; - unifiedPushEmbeddedServerUrl?: string; unifiedPushGatewayUrl?: string; + unifiedPushEmbeddedServerUrl?: string; vapidPublicKey?: string; webPushAppID?: string; pushNotifyUrl?: string; @@ -128,7 +128,8 @@ export function NotificationTransportRuntimeFeature() { clientConfig.pushNotificationDetails?.unifiedPushGatewayUrl, unifiedPushEmbeddedServerUrl: pushTransportOverride?.unifiedPushEmbeddedServerUrl ?? - clientConfig.pushTransport?.unifiedPushEmbeddedServerUrl, + clientConfig.pushTransport?.unifiedPushEmbeddedServerUrl ?? + clientConfig.pushNotificationDetails?.unifiedPushEmbeddedServerUrl, vapidPublicKey: clientConfig.pushNotificationDetails?.vapidPublicKey, webPushAppID: clientConfig.pushNotificationDetails?.webPushAppID, pushNotifyUrl: clientConfig.pushNotificationDetails?.pushNotifyUrl, diff --git a/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts b/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts index bf2e391cc..c760af6c6 100644 --- a/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts +++ b/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts @@ -1007,7 +1007,7 @@ describe('UnifiedPushNotifications', () => { await vi.waitFor(() => expect(acknowledgeWebPushPusher).toHaveBeenCalledOnce()); }); - it('clears the UnifiedPush registration timeout after successful registration', async () => { + it('clears the gateway discovery timeout after successful registration', async () => { vi.useFakeTimers(); try { @@ -1021,6 +1021,42 @@ describe('UnifiedPushNotifications', () => { } }); + it('waits for the plugin registration deadline instead of racing it', async () => { + vi.useFakeTimers(); + try { + let resolveRegistration!: (result: { + status: 'registered'; + permissionState: 'granted'; + endpoint: string; + distributor: string; + }) => void; + unifiedPushTransport.registerUnifiedPushTransport.mockReturnValue( + new Promise((resolve) => { + resolveRegistration = resolve; + }) + ); + + let result: unknown; + const registration = tryEnableUnifiedPush(matrixClient as never).then((value) => { + result = value; + }); + + await vi.advanceTimersByTimeAsync(30_000); + expect(result).toBeUndefined(); + + resolveRegistration({ + status: 'registered', + permissionState: 'granted', + endpoint: 'https://up.example/device', + distributor: 'org.unifiedpush.distributor.ntfy', + }); + await registration; + expect(result).toMatchObject({ status: 'registered' }); + } finally { + vi.useRealTimers(); + } + }); + it('falls back to the default UnifiedPush app id when no override is provided', async () => { await tryEnableUnifiedPush(matrixClient as never); diff --git a/src/app/features/settings/notifications/UnifiedPushNotifications.ts b/src/app/features/settings/notifications/UnifiedPushNotifications.ts index aac65e057..7a10699dd 100644 --- a/src/app/features/settings/notifications/UnifiedPushNotifications.ts +++ b/src/app/features/settings/notifications/UnifiedPushNotifications.ts @@ -17,7 +17,7 @@ import { getStateEvent } from '$utils/room/hierarchy'; import { createDebugLogger } from '$utils/debugLogger'; import type { DecryptedPushEvent } from '$app/crypto/pushDecrypt'; import { decryptPushEventNatively } from '$app/crypto/pushDecrypt'; -import { pushAccount, type PushAccount } from './pushAccount'; +import { pushAccount } from './pushAccount'; import { registerUnifiedPushTransport, type UnifiedPushRegistrationResult, @@ -69,8 +69,6 @@ type UnifiedPushPayload = { [key: string]: unknown; }; -const UP_REGISTER_TIMEOUT_MS = 30_000; - // Android freezes a channel's importance at creation, so raising `messages` from // Default to High needs a new id. Mirrored in the plugin's UnifiedPushNotifier. const MESSAGES_CHANNEL_ID = 'messages.v2'; @@ -136,30 +134,6 @@ export type EnableUnifiedPushResult = } | Exclude; -async function registerUnifiedPushWithTimeout( - vapid?: string, - embeddedServerUrl?: string, - account?: PushAccount -): Promise { - let timeoutId: ReturnType | undefined; - const timeout = new Promise((_, reject) => { - timeoutId = setTimeout(() => { - reject(new Error('UnifiedPush registration timed out')); - }, UP_REGISTER_TIMEOUT_MS); - }); - - try { - return await Promise.race([ - registerUnifiedPushTransport(vapid, embeddedServerUrl, account), - timeout, - ]); - } finally { - if (timeoutId !== undefined) { - clearTimeout(timeoutId); - } - } -} - /** * A provider that speaks the Matrix push protocol answers `/_matrix/push/v1/notify` * with `unifiedpush.gateway == "matrix"`. Preferring it keeps delivery on the provider @@ -208,7 +182,7 @@ export async function tryEnableUnifiedPush( // MSC4174: subscribe with the homeserver VAPID key when it pushes directly. const webPushSupport = await getWebPushServerSupport(mx); const vapid = webPushSupport.supported ? webPushSupport.vapidPublicKey : config?.vapidPublicKey; - const registration = await registerUnifiedPushWithTimeout( + const registration = await registerUnifiedPushTransport( vapid, trimConfigValue(config?.unifiedPushEmbeddedServerUrl) ?? DEFAULT_EMBEDDED_GATEWAY, pushAccount(mx) diff --git a/src/app/hooks/useClientConfig.ts b/src/app/hooks/useClientConfig.ts index ee8a4f619..ec1cdbede 100644 --- a/src/app/hooks/useClientConfig.ts +++ b/src/app/hooks/useClientConfig.ts @@ -29,6 +29,7 @@ export type ClientConfig = { iosPushAppID?: string; unifiedPushAppID?: string; unifiedPushGatewayUrl?: string; + unifiedPushEmbeddedServerUrl?: string; }; pushTransport?: PushTransportConfig; diff --git a/src/app/plugins/call/CallWidgetDriver.sticky.test.ts b/src/app/plugins/call/CallWidgetDriver.sticky.test.ts new file mode 100644 index 000000000..62f8ec5f8 --- /dev/null +++ b/src/app/plugins/call/CallWidgetDriver.sticky.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; +import { CallWidgetDriver } from './CallWidgetDriver'; + +const roomId = '!room:example.org'; +const userId = '@alice:example.org'; +const deviceId = 'ALICEDEVICE'; + +const membership = { member: { id: `${userId}:${deviceId}` }, msc4354_sticky_key: 'key' }; + +const makeClient = (overrides: Partial> = {}) => + ({ + getDeviceId: () => deviceId, + getSafeUserId: () => userId, + getRoom: () => null, + ...overrides, + }) as unknown as MatrixClient; + +describe('CallWidgetDriver sticky events', () => { + it('sends a sticky event with its duration', async () => { + const sendSticky = vi + .fn<() => Promise<{ event_id: string }>>() + .mockResolvedValue({ event_id: '$sticky' }); + const driver = new CallWidgetDriver( + makeClient({ _unstable_sendStickyEvent: sendSticky }), + roomId + ); + + await expect( + driver.sendStickyEvent(3_600_000, 'org.matrix.msc4143.rtc.member', membership) + ).resolves.toEqual({ roomId, eventId: '$sticky' }); + expect(sendSticky).toHaveBeenCalledWith( + roomId, + 3_600_000, + null, + 'org.matrix.msc4143.rtc.member', + membership + ); + }); + + it('sends a delayed sticky event', async () => { + const sendDelayedSticky = vi + .fn<() => Promise<{ delay_id: string }>>() + .mockResolvedValue({ delay_id: 'delay-1' }); + const driver = new CallWidgetDriver( + makeClient({ _unstable_sendStickyDelayedEvent: sendDelayedSticky }), + roomId + ); + + await expect( + driver.sendDelayedStickyEvent(8_000, 3_600_000, 'org.matrix.msc4143.rtc.member', membership) + ).resolves.toEqual({ roomId, delayId: 'delay-1' }); + expect(sendDelayedSticky).toHaveBeenCalledWith( + roomId, + 3_600_000, + { delay: 8_000 }, + null, + 'org.matrix.msc4143.rtc.member', + membership + ); + }); + + it('reads the sticky events of a room', async () => { + const event = { getEffectiveEvent: () => ({ event_id: '$one' }) } as unknown as MatrixEvent; + const room = { _unstable_getStickyEvents: () => [event] } as unknown as Room; + const driver = new CallWidgetDriver(makeClient({ getRoom: () => room }), roomId); + + await expect(driver.readStickyEvents(roomId)).resolves.toEqual([{ event_id: '$one' }]); + }); + + it('returns nothing for an unknown room', async () => { + const driver = new CallWidgetDriver(makeClient(), roomId); + + await expect(driver.readStickyEvents(roomId)).resolves.toEqual([]); + }); +}); diff --git a/src/app/plugins/call/CallWidgetDriver.ts b/src/app/plugins/call/CallWidgetDriver.ts index bf9faac08..ac357d6ec 100644 --- a/src/app/plugins/call/CallWidgetDriver.ts +++ b/src/app/plugins/call/CallWidgetDriver.ts @@ -175,6 +175,59 @@ export class CallWidgetDriver extends WidgetDriver { }; } + public async sendStickyEvent( + stickyDurationMs: number, + eventType: string, + content: IContent, + targetRoomId: string | null = null + ): Promise { + const client = this.mx; + const roomId = targetRoomId || this.inRoomId; + + if (!client || !roomId) throw new Error('Not in a room or not attached to a client'); + + const r = await client._unstable_sendStickyEvent( + roomId, + stickyDurationMs, + null, + eventType as keyof TimelineEvents, + content as TimelineEvents[keyof TimelineEvents] + ); + + return { roomId, eventId: r.event_id }; + } + + public async sendDelayedStickyEvent( + delay: number, + stickyDurationMs: number, + eventType: string, + content: IContent, + targetRoomId: string | null = null + ): Promise { + const client = this.mx; + const roomId = targetRoomId || this.inRoomId; + + if (!client || !roomId) throw new Error('Not in a room or not attached to a client'); + + const r = await client._unstable_sendStickyDelayedEvent( + roomId, + stickyDurationMs, + { delay }, + null, + eventType as keyof TimelineEvents, + content as TimelineEvents[keyof TimelineEvents] + ); + + return { roomId, delayId: r.delay_id }; + } + + public async readStickyEvents(roomId: string): Promise { + const room = this.mx.getRoom(roomId); + if (room === null) return []; + + return [...room._unstable_getStickyEvents()].map((e) => e.getEffectiveEvent() as IRoomEvent); + } + public async updateDelayedEvent( delayId: string, action: UpdateDelayedEventAction diff --git a/src/app/plugins/call/utils.test.ts b/src/app/plugins/call/utils.test.ts index 116466b71..496cbacec 100644 --- a/src/app/plugins/call/utils.test.ts +++ b/src/app/plugins/call/utils.test.ts @@ -14,6 +14,13 @@ describe('getCallCapabilities', () => { expect(capabilities.has(MatrixCapabilities.MSC4157UpdateDelayedEvent)).toBe(true); }); + it('includes sticky-event capabilities', () => { + const capabilities = getCallCapabilities(roomId, userId, deviceId); + + expect(capabilities.has(MatrixCapabilities.MSC4407SendStickyEvent)).toBe(true); + expect(capabilities.has(MatrixCapabilities.MSC4407ReceiveStickyEvent)).toBe(true); + }); + it('includes upload and download media capabilities', () => { const capabilities = getCallCapabilities(roomId, userId, deviceId); diff --git a/src/app/plugins/call/utils.ts b/src/app/plugins/call/utils.ts index b61f87aa9..cccb725b4 100644 --- a/src/app/plugins/call/utils.ts +++ b/src/app/plugins/call/utils.ts @@ -20,6 +20,8 @@ export function getCallCapabilities( capabilities.add(MatrixCapabilities.MSC4039DownloadFile); capabilities.add(MatrixCapabilities.MSC4157SendDelayedEvent); capabilities.add(MatrixCapabilities.MSC4157UpdateDelayedEvent); + capabilities.add(MatrixCapabilities.MSC4407SendStickyEvent); + capabilities.add(MatrixCapabilities.MSC4407ReceiveStickyEvent); capabilities.add('moe.sable.thumbnails'); capabilities.add('moe.sable.media_proxy'); capabilities.add(`org.matrix.msc2762.timeline:${roomId}`); diff --git a/src/app/utils/debugLogger.test.ts b/src/app/utils/debugLogger.test.ts index e366a2cda..8b870aa3d 100644 --- a/src/app/utils/debugLogger.test.ts +++ b/src/app/utils/debugLogger.test.ts @@ -147,6 +147,46 @@ describe('debug logger diagnostic capture', () => { expect(logger.getLogs()[0]?.data).toBeUndefined(); }); + it('keeps Error-valued initialization diagnostics in Sentry context', () => { + logger.log('error', 'sync', 'initMatrix', 'Failed to initialize client', { + phase: 'rust_crypto', + error: new Error('crypto initialization failed'), + }); + + expect(Sentry.captureMessage).toHaveBeenCalledWith( + '[sync:initMatrix] Failed to initialize client', + expect.objectContaining({ + contexts: { + debugLog: { + data: { + phase: 'rust_crypto', + error: 'crypto initialization failed', + }, + timestamp: expect.any(String), + }, + }, + }) + ); + }); + + it('keeps native failure reasons in Sentry context', () => { + logger.log('error', 'notification', 'nativePush', 'Failed to register push endpoint', { + reason: 'permission denied', + }); + + expect(Sentry.captureMessage).toHaveBeenCalledWith( + '[notification:nativePush] Failed to register push endpoint', + expect.objectContaining({ + contexts: { + debugLog: { + data: { reason: 'permission denied' }, + timestamp: expect.any(String), + }, + }, + }) + ); + }); + it.each([ [ 'circular values', diff --git a/src/app/utils/notificationSound.test.ts b/src/app/utils/notificationSound.test.ts index 441ff9420..4c81fe34e 100644 --- a/src/app/utils/notificationSound.test.ts +++ b/src/app/utils/notificationSound.test.ts @@ -1,9 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { playNotificationSound } from './notificationSound'; +import type { playNotificationSound as PlayNotificationSound } from './notificationSound'; + +let playNotificationSound: typeof PlayNotificationSound; type MockSource = { buffer: AudioBuffer | null; connect: ReturnType; + disconnect: ReturnType; start: ReturnType; addEventListener: ReturnType; ended: (() => void) | undefined; @@ -12,6 +15,8 @@ type MockSource = { const nativeAudioContext = globalThis.AudioContext; const nativeFetch = globalThis.fetch; let sources: MockSource[]; +let audioContexts: MockAudioContext[]; +let failToStartAudioDevice = false; class MockAudioContext { public state: AudioContextState = 'running'; @@ -19,11 +24,18 @@ class MockAudioContext { public decodeAudioData = vi.fn<() => Promise>().mockResolvedValue({} as AudioBuffer); public resume = vi.fn<() => Promise>().mockResolvedValue(undefined); + public close = vi.fn<() => Promise>().mockResolvedValue(undefined); public createBufferSource = vi.fn<() => AudioBufferSourceNode>(() => { const source: MockSource = { buffer: null, connect: vi.fn<() => void>(), - start: vi.fn<() => void>(), + disconnect: vi.fn<() => void>(), + start: vi.fn<() => void>(() => { + if (failToStartAudioDevice) { + failToStartAudioDevice = false; + throw new DOMException('Failed to start the audio device', 'InvalidStateError'); + } + }), addEventListener: vi.fn<(type: string, listener: () => void) => void>((type, listener) => { if (type === 'ended') source.ended = listener; }), @@ -32,10 +44,18 @@ class MockAudioContext { sources.push(source); return source as unknown as AudioBufferSourceNode; }); + + public constructor() { + audioContexts.push(this); + } } -beforeEach(() => { +beforeEach(async () => { + vi.resetModules(); + ({ playNotificationSound } = await import('./notificationSound')); sources = []; + audioContexts = []; + failToStartAudioDevice = false; globalThis.AudioContext = MockAudioContext as unknown as typeof AudioContext; globalThis.fetch = vi.fn<() => Promise>().mockResolvedValue({ arrayBuffer: () => Promise.resolve(new ArrayBuffer(0)), @@ -62,4 +82,20 @@ describe('playNotificationSound', () => { expect(sources).toHaveLength(2); sources[1]!.ended?.(); }); + + it('recovers after the audio device rejects a buffer source', async () => { + failToStartAudioDevice = true; + + await expect(playNotificationSound('/sound/notification.ogg')).rejects.toMatchObject({ + name: 'InvalidStateError', + message: 'Failed to start the audio device', + }); + + await playNotificationSound('/sound/notification.ogg'); + + expect(audioContexts).toHaveLength(2); + expect(sources).toHaveLength(2); + expect(audioContexts[0]!.close).toHaveBeenCalledOnce(); + expect(sources[0]!.disconnect).toHaveBeenCalledOnce(); + }); }); diff --git a/src/app/utils/notificationSound.ts b/src/app/utils/notificationSound.ts index 6f702e6c9..87a97d78a 100644 --- a/src/app/utils/notificationSound.ts +++ b/src/app/utils/notificationSound.ts @@ -22,24 +22,46 @@ const decode = (ctx: AudioContext, url: string): Promise => { return buffer; }; +const resetAudioState = ( + failedContext: AudioContext, + failedSource?: AudioBufferSourceNode +): void => { + if (context === failedContext) { + context = undefined; + playingSource = undefined; + buffers.clear(); + } + failedSource?.disconnect(); + if (failedContext.state !== 'closed') { + void failedContext.close().catch(() => {}); + } +}; + export const playNotificationSound = async (url: string): Promise => { - context ??= new AudioContext(); - const buffer = await decode(context, url); - // A context constructed outside a user gesture starts suspended, and Safari - // moves it to 'interrupted' after a phone call or a route change. - if (context.state !== 'running') await context.resume(); - if (playingSource) return; - - const source = context.createBufferSource(); - source.buffer = buffer; - source.connect(context.destination); - playingSource = source; - source.addEventListener( - 'ended', - () => { - if (playingSource === source) playingSource = undefined; - }, - { once: true } - ); - source.start(); + const audioContext = (context ??= new AudioContext()); + const buffer = await decode(audioContext, url); + let source: AudioBufferSourceNode | undefined; + try { + if (context !== audioContext) return; + if (audioContext.state !== 'running') { + await audioContext.resume(); + if (context !== audioContext) return; + } + if (playingSource) return; + source = audioContext.createBufferSource(); + source.buffer = buffer; + source.connect(audioContext.destination); + playingSource = source; + source.addEventListener( + 'ended', + () => { + if (playingSource === source) playingSource = undefined; + }, + { once: true } + ); + source.start(); + } catch (error) { + resetAudioState(audioContext, source); + throw error; + } }; diff --git a/src/app/utils/sentryScrubbers.test.ts b/src/app/utils/sentryScrubbers.test.ts index b676b9480..692bc20d2 100644 --- a/src/app/utils/sentryScrubbers.test.ts +++ b/src/app/utils/sentryScrubbers.test.ts @@ -347,6 +347,36 @@ describe('sanitizeSentryPayload', () => { }); describe('sanitizeDiagnosticsLogs', () => { + it('keeps safe failure fields while scrubbing sensitive and arbitrary data', () => { + const sanitized = sanitizeDiagnosticsLogs( + JSON.stringify({ + logs: [ + { + data: { + phase: 'rust_crypto', + error: 'GET https://matrix.example/sync?access_token=secret for @alice:example.org', + reason: 'room !private:example.org failed', + private: 'remove me', + token: 'remove me too', + }, + }, + ], + }) + ); + + expect(sanitized).not.toBeNull(); + const parsed = JSON.parse(sanitized as string) as { + logs: { data: Record }[]; + }; + expect(parsed.logs[0]?.data).toEqual({ + phase: 'rust_crypto', + error: 'GET [REDACTED_URL] for [REDACTED_MATRIX_ID]', + reason: 'room [REDACTED_MATRIX_ID] failed', + }); + expect(JSON.stringify(parsed)).not.toContain('secret'); + expect(JSON.stringify(parsed)).not.toContain('private'); + }); + it('keeps safe metadata and removes sensitive or arbitrary values', () => { const sanitized = sanitizeDiagnosticsLogs( JSON.stringify({ diff --git a/src/app/utils/sentryScrubbers.ts b/src/app/utils/sentryScrubbers.ts index 241bca4c8..e3afd6f53 100644 --- a/src/app/utils/sentryScrubbers.ts +++ b/src/app/utils/sentryScrubbers.ts @@ -189,6 +189,7 @@ const DIAGNOSTICS_REDACTED_URL = '[REDACTED_URL]'; const DIAGNOSTICS_SENSITIVE_KEY_PATTERN = /(?:authorization|cookie|token|secret|password|passwd|credential|api[-_]?key)/i; +const DIAGNOSTICS_SAFE_DATA_KEYS = new Set(['phase', 'error', 'reason']); const DIAGNOSTICS_URL_PATTERN = /\b[a-z][a-z0-9+.-]{1,15}:\/\/[^\s<>"']+/gi; const DIAGNOSTICS_AUTH_PATTERN = /\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+/gi; const DIAGNOSTICS_SENSITIVE_VALUE_PATTERN = @@ -223,6 +224,18 @@ const sanitizeDiagnosticsHeaders = (value: DiagnosticsJsonValue): DiagnosticsJso return sanitizeDiagnosticsJsonValue(value) ?? null; }; +const sanitizeDiagnosticsData = (value: DiagnosticsJsonValue): DiagnosticsJsonValue | undefined => { + if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined; + + const sanitized: DiagnosticsJsonObject = {}; + for (const [key, child] of Object.entries(value)) { + if (!DIAGNOSTICS_SAFE_DATA_KEYS.has(key)) continue; + const safeChild = sanitizeDiagnosticsJsonValue(child); + if (safeChild !== undefined) sanitized[key] = safeChild; + } + return Object.keys(sanitized).length > 0 ? sanitized : undefined; +}; + const sanitizeDiagnosticsJsonValue = ( value: DiagnosticsJsonValue ): DiagnosticsJsonValue | undefined => { @@ -233,7 +246,11 @@ const sanitizeDiagnosticsJsonValue = ( const sanitized: DiagnosticsJsonObject = {}; for (const [key, child] of Object.entries(value)) { - if (key.toLowerCase() === 'data') continue; + if (key.toLowerCase() === 'data') { + const safeData = sanitizeDiagnosticsData(child); + if (safeData !== undefined) sanitized[key] = safeData; + continue; + } if (key.toLowerCase() === 'headers') { sanitized[key] = sanitizeDiagnosticsHeaders(child); continue; diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index c1923ff83..ef5ebfa98 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -32,6 +32,7 @@ import { createDebugLogger } from '$utils/debugLogger'; import { CustomStateEvent } from '$types/matrix/room'; import * as Sentry from '@sentry/react'; import { SlidingSyncSidebarCache } from './slidingSyncSidebarCache'; +import { forwardTimelineStickyEvents, StickyEventsExtension } from './stickyEvents'; import { markPreprocessingSlidingSyncTimelineReset } from './slidingSyncTimelineReset'; const log = createLogger('slidingSync'); @@ -612,6 +613,8 @@ export class SlidingSyncManager { private hydratingSidebarCache = false; + private detachStickyEvents: (() => void) | undefined; + private readonly onCacheRoomData: (roomId: string, data: MSC3575RoomData) => void; private readonly onCacheAccountData: (event: MatrixEvent) => void; @@ -773,6 +776,8 @@ export class SlidingSyncManager { buildSpaceImagePackSubscription() ); + this.slidingSync.registerExtension(new StickyEventsExtension(mx)); + this.onLifecycle = (state, resp, err) => { debugLog.info('sync', `Sliding sync lifecycle: ${state}`, { state, @@ -994,6 +999,7 @@ export class SlidingSyncManager { this.slidingSync.on(SlidingSyncEvent.RoomData, this.onCacheRoomData); this.mx.on(RoomMemberEvent.Membership, this.onMembershipLeave); this.mx.on(ClientEvent.AccountData, this.onCacheAccountData); + this.detachStickyEvents = forwardTimelineStickyEvents(this.mx); this.armPollWatchdog(); @@ -1167,6 +1173,8 @@ export class SlidingSyncManager { this.cacheHydrationResolve = undefined; this.mx.removeListener(RoomMemberEvent.Membership, this.onMembershipLeave); this.mx.removeListener(ClientEvent.AccountData, this.onCacheAccountData); + this.detachStickyEvents?.(); + this.detachStickyEvents = undefined; this.sidebarCache.dispose(); debugLog.info('sync', 'Sliding sync disposed successfully', { diff --git a/src/client/stickyEvents.test.ts b/src/client/stickyEvents.test.ts new file mode 100644 index 000000000..3a6a9a098 --- /dev/null +++ b/src/client/stickyEvents.test.ts @@ -0,0 +1,142 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { MatrixClient, Room } from '$types/matrix-sdk'; +import { MatrixEvent, RoomEvent } from '$types/matrix-sdk'; +import { forwardTimelineStickyEvents, StickyEventsExtension } from './stickyEvents'; + +const roomId = '!room:example.com'; +const userId = '@user:example.com'; + +const eventJson = (eventId: string, sticky = true) => ({ + type: 'm.rtc.member', + event_id: eventId, + sender: userId, + origin_server_ts: Date.now(), + content: { msc4354_sticky_key: `${userId}:DEVICE` }, + ...(sticky ? { msc4354_sticky: { duration_ms: 60_000 } } : {}), +}); + +const makeRoom = (existing: MatrixEvent[] = []) => { + const added: MatrixEvent[][] = []; + const room = { + roomId, + _unstable_getStickyEvents: () => existing, + _unstable_addStickyEvents: (events: MatrixEvent[]) => added.push(events), + } as unknown as Room; + return { room, added }; +}; + +const makeClient = (room: Room | undefined, supported = true) => + ({ + getRoom: () => room, + getEventMapper: () => (event: Record) => new MatrixEvent(event), + doesServerSupportUnstableFeature: vi.fn<() => Promise>().mockResolvedValue(supported), + }) as unknown as MatrixClient; + +describe('StickyEventsExtension', () => { + it('stays disabled when the server does not support MSC4354', async () => { + const extension = new StickyEventsExtension(makeClient(undefined, false)); + expect(await extension.onRequest(true)).toEqual({ enabled: false }); + }); + + it('enables itself and threads the since token', async () => { + const extension = new StickyEventsExtension(makeClient(makeRoom().room)); + + expect(await extension.onRequest(true)).toEqual({ enabled: true, limit: 100 }); + + await extension.onResponse({ next_batch: '42' }); + expect(await extension.onRequest(false)).toEqual({ enabled: true, limit: 100, since: '42' }); + + expect(await extension.onRequest(true)).toEqual({ enabled: true, limit: 100 }); + }); + + it('feeds sticky events into the room store', async () => { + const { room, added } = makeRoom(); + const extension = new StickyEventsExtension(makeClient(room)); + + await extension.onResponse({ + rooms: { [roomId]: { events: [eventJson('$one'), eventJson('$two')] } }, + }); + + expect(added).toHaveLength(1); + expect(added[0]?.map((event) => event.getId())).toEqual(['$one', '$two']); + expect(added[0]?.[0]?.getRoomId()).toBe(roomId); + }); + + it('ignores events the server did not mark sticky', async () => { + const { room, added } = makeRoom(); + const extension = new StickyEventsExtension(makeClient(room)); + + await extension.onResponse({ + rooms: { [roomId]: { events: [eventJson('$plain', false)] } }, + }); + + expect(added).toHaveLength(0); + }); + + it('does not re-add an event the store already holds', async () => { + const known = new MatrixEvent(eventJson('$one')); + const { room, added } = makeRoom([known]); + const extension = new StickyEventsExtension(makeClient(room)); + + await extension.onResponse({ + rooms: { [roomId]: { events: [eventJson('$one'), eventJson('$two')] } }, + }); + + expect(added).toHaveLength(1); + expect(added[0]?.map((event) => event.getId())).toEqual(['$two']); + }); +}); + +const makeEmitter = () => { + const listeners = new Set<(...args: unknown[]) => void>(); + const mx = { + on: (_event: string, listener: (...args: unknown[]) => void) => listeners.add(listener), + removeListener: (_event: string, listener: (...args: unknown[]) => void) => + listeners.delete(listener), + } as unknown as MatrixClient; + const emit = (...args: unknown[]) => listeners.forEach((listener) => listener(...args)); + return { mx, emit, listeners }; +}; + +describe('forwardTimelineStickyEvents', () => { + it('forwards live sticky timeline events to the room store', () => { + const { room, added } = makeRoom(); + const { mx, emit } = makeEmitter(); + forwardTimelineStickyEvents(mx); + + emit(new MatrixEvent(eventJson('$one')), room, false); + + expect(added).toHaveLength(1); + expect(added[0]?.[0]?.getId()).toBe('$one'); + }); + + it('ignores back-paginated and non-sticky events', () => { + const { room, added } = makeRoom(); + const { mx, emit } = makeEmitter(); + forwardTimelineStickyEvents(mx); + + emit(new MatrixEvent(eventJson('$one')), room, true); + emit(new MatrixEvent(eventJson('$two', false)), room, false); + + expect(added).toHaveLength(0); + }); + + it('stops forwarding once detached', () => { + const { room, added } = makeRoom(); + const { mx, emit, listeners } = makeEmitter(); + const detach = forwardTimelineStickyEvents(mx); + + detach(); + expect(listeners.size).toBe(0); + emit(new MatrixEvent(eventJson('$one')), room, false); + + expect(added).toHaveLength(0); + }); + + it('registers on the timeline event', () => { + const on = vi.fn<(event: string, listener: () => void) => void>(); + const removeListener = vi.fn<(event: string, listener: () => void) => void>(); + forwardTimelineStickyEvents({ on, removeListener } as unknown as MatrixClient); + expect(on).toHaveBeenCalledWith(RoomEvent.Timeline, expect.any(Function)); + }); +}); diff --git a/src/client/stickyEvents.ts b/src/client/stickyEvents.ts new file mode 100644 index 000000000..d751fb922 --- /dev/null +++ b/src/client/stickyEvents.ts @@ -0,0 +1,102 @@ +import type { Extension, IRoomEvent, MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; +import { ExtensionState, RoomEvent, UNSTABLE_MSC4354_STICKY_EVENTS } from '$types/matrix-sdk'; +import { createDebugLogger } from '$utils/debugLogger'; + +const debugLog = createDebugLogger('slidingSync'); + +const STICKY_EVENTS_EXTENSION = 'org.matrix.msc4354.sticky_events'; +const STICKY_EVENTS_LIMIT = 100; + +type StickyEventsRequest = { + enabled: boolean; + limit?: number; + since?: string; +}; + +type StickyEventsResponse = { + next_batch?: string; + rooms?: Record; +}; + +const isSticky = (event: MatrixEvent): boolean => event.unstableStickyInfo !== undefined; + +const rejectKnownStickyEvents = (room: Room, events: MatrixEvent[]): MatrixEvent[] => { + const known = new Set(); + for (const event of room._unstable_getStickyEvents()) { + const eventId = event.getId(); + if (eventId) known.add(eventId); + } + return events.filter((event) => { + const eventId = event.getId(); + return !eventId || !known.has(eventId); + }); +}; + +export const addStickyEvents = (room: Room, events: MatrixEvent[]): void => { + const sticky = rejectKnownStickyEvents(room, events.filter(isSticky)); + if (sticky.length === 0) return; + room._unstable_addStickyEvents(sticky); +}; + +export class StickyEventsExtension implements Extension { + private since: string | undefined; + + private serverSupport: Promise | undefined; + + public constructor(private readonly mx: MatrixClient) {} + + public name(): string { + return STICKY_EVENTS_EXTENSION; + } + + public when(): ExtensionState { + return ExtensionState.PostProcess; + } + + private supported(): Promise { + this.serverSupport ??= this.mx + .doesServerSupportUnstableFeature(UNSTABLE_MSC4354_STICKY_EVENTS) + .catch(() => false); + return this.serverSupport; + } + + public async onRequest(isInitial: boolean): Promise { + if (isInitial) this.since = undefined; + if (!(await this.supported())) return { enabled: false }; + return { + enabled: true, + limit: STICKY_EVENTS_LIMIT, + ...(this.since ? { since: this.since } : {}), + }; + } + + public async onResponse(data: StickyEventsResponse): Promise { + if (!data) return; + if (data.next_batch) this.since = data.next_batch; + + const mapper = this.mx.getEventMapper(); + for (const [roomId, roomData] of Object.entries(data.rooms ?? {})) { + const room = this.mx.getRoom(roomId); + if (!room) { + debugLog.warn('sync', `sticky events for unknown room ${roomId}`); + continue; + } + const events = (roomData.events ?? []).map((event) => mapper({ ...event, room_id: roomId })); + addStickyEvents(room, events); + } + } +} + +export const forwardTimelineStickyEvents = (mx: MatrixClient): (() => void) => { + const onTimeline = ( + event: MatrixEvent, + room: Room | undefined, + toStartOfTimeline: boolean | undefined + ) => { + if (!room || toStartOfTimeline || !isSticky(event)) return; + addStickyEvents(room, [event]); + }; + + mx.on(RoomEvent.Timeline, onTimeline); + return () => mx.removeListener(RoomEvent.Timeline, onTimeline); +};