From 89cec0ad78eb74fdeb60652523026b4f73de3f79 Mon Sep 17 00:00:00 2001 From: Florian Duros Date: Tue, 28 Jan 2025 15:27:09 +0100 Subject: [PATCH] Remove deprecated methods and attributes of `MatrixClient` (#4659) * feat(legacy crypto)!: remove deprecated methods of `MatrixClient` * test(legacy crypto): update existing tests to not use legacy crypto - `Embedded.spec.ts`: casting since `encryptAndSendToDevices` is removed from `MatrixClient`. - `room.spec.ts`: remove deprecated usage of `MatrixClient.crypto` - `matrix-client.spec.ts` & `matrix-client-methods.spec.ts`: remove calls of deprecated methods of `MatrixClient` * test(legacy crypto): remove test files using `MatrixClient` deprecated methods * test(legacy crypto): update existing integ tests to run successfully * feat(legacy crypto!): remove `ICreateClientOpts.deviceToImport`. `ICreateClientOpts.deviceToImport` was used in the legacy cryto. The rust crypto doesn't support to import devices in this way. * feat(legacy crypto!): remove `{get,set}GlobalErrorOnUnknownDevices` `globalErrorOnUnknownDevices` is not used in the rust-crypto. The API is marked as unstable, we can remove it. --- spec/integ/crypto/cross-signing.spec.ts | 3 +- spec/integ/crypto/crypto.spec.ts | 530 +--- spec/integ/crypto/device-dehydration.spec.ts | 4 +- spec/integ/crypto/megolm-backup.spec.ts | 114 +- spec/integ/crypto/rust-crypto.spec.ts | 3 +- spec/integ/crypto/verification.spec.ts | 5 +- spec/integ/matrix-client-methods.spec.ts | 45 - spec/unit/crypto/backup.spec.ts | 214 -- spec/unit/crypto/dehydration.spec.ts | 62 - spec/unit/embedded.spec.ts | 3 +- spec/unit/matrix-client.spec.ts | 93 +- spec/unit/room.spec.ts | 2 +- src/client.ts | 2438 ++---------------- 13 files changed, 218 insertions(+), 3298 deletions(-) delete mode 100644 spec/unit/crypto/backup.spec.ts delete mode 100644 spec/unit/crypto/dehydration.spec.ts diff --git a/spec/integ/crypto/cross-signing.spec.ts b/spec/integ/crypto/cross-signing.spec.ts index 95b0f756e0a..840970aebc2 100644 --- a/spec/integ/crypto/cross-signing.spec.ts +++ b/spec/integ/crypto/cross-signing.spec.ts @@ -19,7 +19,7 @@ import "fake-indexeddb/auto"; import { IDBFactory } from "fake-indexeddb"; import { CRYPTO_BACKENDS, InitCrypto, syncPromise } from "../../test-utils/test-utils"; -import { AuthDict, createClient, CryptoEvent, MatrixClient } from "../../../src"; +import { AuthDict, createClient, MatrixClient } from "../../../src"; import { mockInitialApiRequests, mockSetupCrossSigningRequests } from "../../test-utils/mockEndpoints"; import encryptAESSecretStorageItem from "../../../src/utils/encryptAESSecretStorageItem.ts"; import { CryptoCallbacks, CrossSigningKey } from "../../../src/crypto-api"; @@ -37,6 +37,7 @@ import { import * as testData from "../../test-utils/test-data"; import { E2EKeyResponder } from "../../test-utils/E2EKeyResponder"; import { AccountDataAccumulator } from "../../test-utils/AccountDataAccumulator"; +import { CryptoEvent } from "../../../src/crypto-api"; afterEach(() => { // reset fake-indexeddb after each test, to make sure we don't leak connections diff --git a/spec/integ/crypto/crypto.spec.ts b/spec/integ/crypto/crypto.spec.ts index 466a46e39a7..b241975af70 100644 --- a/spec/integ/crypto/crypto.spec.ts +++ b/spec/integ/crypto/crypto.spec.ts @@ -24,7 +24,6 @@ import Olm from "@matrix-org/olm"; import * as testUtils from "../../test-utils/test-utils"; import { - advanceTimersUntil, CRYPTO_BACKENDS, emitPromise, getSyncResponse, @@ -49,7 +48,6 @@ import { Category, ClientEvent, createClient, - CryptoEvent, HistoryVisibility, IClaimOTKsResult, IContent, @@ -65,7 +63,6 @@ import { RoomMember, RoomStateEvent, } from "../../../src/matrix"; -import { DeviceInfo } from "../../../src/crypto/deviceinfo"; import { E2EKeyReceiver } from "../../test-utils/E2EKeyReceiver"; import { ISyncResponder, SyncResponder } from "../../test-utils/SyncResponder"; import { defer, escapeRegExp } from "../../../src/utils"; @@ -98,11 +95,11 @@ import { establishOlmSession, getTestOlmAccountKeys, } from "./olm-utils"; -import { ToDevicePayload } from "../../../src/models/ToDeviceMessage"; import { AccountDataAccumulator } from "../../test-utils/AccountDataAccumulator"; import { UNSIGNED_MEMBERSHIP_FIELD } from "../../../src/@types/event"; import { KnownMembership } from "../../../src/@types/membership"; import { KeyBackup } from "../../../src/rust-crypto/backup.ts"; +import { CryptoEvent } from "../../../src/crypto-api"; afterEach(() => { // reset fake-indexeddb after each test, to make sure we don't leak connections @@ -415,13 +412,6 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, expectAliceKeyQuery({ device_keys: { "@alice:localhost": {} }, failures: {} }); await startClientAndAwaitFirstSync(); - // if we're using the old crypto impl, stub out some methods in the device manager. - // TODO: replace this with intercepts of the /keys/query endpoint to make it impl agnostic. - if (aliceClient.crypto) { - aliceClient.crypto.deviceList.downloadKeys = () => Promise.resolve(new Map()); - aliceClient.crypto.deviceList.getUserByIdentityKey = () => "@bob:xyz"; - } - const p2pSession = await createOlmSession(testOlmAccount, keyReceiver); const groupSession = new Olm.OutboundGroupSession(); groupSession.create(); @@ -878,13 +868,6 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, expectAliceKeyQuery({ device_keys: { "@alice:localhost": {} }, failures: {} }); await startClientAndAwaitFirstSync(); - // if we're using the old crypto impl, stub out some methods in the device manager. - // TODO: replace this with intercepts of the /keys/query endpoint to make it impl agnostic. - if (aliceClient.crypto) { - aliceClient.crypto.deviceList.downloadKeys = () => Promise.resolve(new Map()); - aliceClient.crypto.deviceList.getUserByIdentityKey = () => "@bob:xyz"; - } - const p2pSession = await createOlmSession(testOlmAccount, keyReceiver); const groupSession = new Olm.OutboundGroupSession(); groupSession.create(); @@ -939,13 +922,6 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, expectAliceKeyQuery({ device_keys: { "@alice:localhost": {} }, failures: {} }); await startClientAndAwaitFirstSync(); - // if we're using the old crypto impl, stub out some methods in the device manager. - // TODO: replace this with intercepts of the /keys/query endpoint to make it impl agnostic. - if (aliceClient.crypto) { - aliceClient.crypto.deviceList.downloadKeys = () => Promise.resolve(new Map()); - aliceClient.crypto.deviceList.getUserByIdentityKey = () => "@bob:xyz"; - } - const p2pSession = await createOlmSession(testOlmAccount, keyReceiver); const groupSession = new Olm.OutboundGroupSession(); groupSession.create(); @@ -1018,7 +994,6 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, keyResponder.addDeviceKeys(testDeviceKeys); await startClientAndAwaitFirstSync(); - aliceClient.setGlobalErrorOnUnknownDevices(false); // tell alice she is sharing a room with bob syncResponder.sendOrQueueSyncResponse(getSyncResponse(["@bob:xyz"])); @@ -1030,17 +1005,13 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, // fire off the prepare request const room = aliceClient.getRoom(ROOM_ID); expect(room).toBeTruthy(); - const p = aliceClient.prepareToEncrypt(room!); + aliceClient.getCrypto()?.prepareToEncrypt(room!); // we expect to get a room key message await expectSendRoomKey("@bob:xyz", testOlmAccount); - - // the prepare request should complete successfully. - await p; }); - it("Alice sends a megolm message with GlobalErrorOnUnknownDevices=false", async () => { - aliceClient.setGlobalErrorOnUnknownDevices(false); + it("Alice sends a megolm message", async () => { const homeserverUrl = aliceClient.getHomeserverUrl(); const keyResponder = new E2EKeyResponder(homeserverUrl); keyResponder.addKeyReceiver("@alice:localhost", keyReceiver); @@ -1068,7 +1039,6 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, }); it("We should start a new megolm session after forceDiscardSession", async () => { - aliceClient.setGlobalErrorOnUnknownDevices(false); const homeserverUrl = aliceClient.getHomeserverUrl(); const keyResponder = new E2EKeyResponder(homeserverUrl); keyResponder.addKeyReceiver("@alice:localhost", keyReceiver); @@ -1095,7 +1065,7 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, ]); // Finally the interesting part: discard the session. - aliceClient.forceDiscardSession(ROOM_ID); + aliceClient.getCrypto()!.forceDiscardSession(ROOM_ID); // Now when we send the next message, we should get a *new* megolm session. const inboundGroupSessionPromise2 = expectSendRoomKey("@bob:xyz", testOlmAccount); @@ -1103,207 +1073,6 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, await Promise.all([aliceClient.sendTextMessage(ROOM_ID, "test2"), p2]); }); - oldBackendOnly("Alice sends a megolm message", async () => { - // TODO: do something about this for the rust backend. - // Currently it fails because we don't respect the default GlobalErrorOnUnknownDevices and - // send messages to unknown devices. - - expectAliceKeyQuery({ device_keys: { "@alice:localhost": {} }, failures: {} }); - await startClientAndAwaitFirstSync(); - const p2pSession = await establishOlmSession(aliceClient, keyReceiver, syncResponder, testOlmAccount); - - syncResponder.sendOrQueueSyncResponse(getSyncResponse(["@bob:xyz"])); - await syncPromise(aliceClient); - - // start out with the device unknown - the send should be rejected. - expectAliceKeyQuery(getTestKeysQueryResponse("@bob:xyz")); - expectAliceKeyQuery(getTestKeysQueryResponse("@bob:xyz")); - - await aliceClient.sendTextMessage(ROOM_ID, "test").then( - () => { - throw new Error("sendTextMessage failed on an unknown device"); - }, - (e) => { - expect(e.name).toEqual("UnknownDeviceError"); - }, - ); - - // mark the device as known, and resend. - aliceClient.setDeviceKnown("@bob:xyz", "DEVICE_ID"); - - const room = aliceClient.getRoom(ROOM_ID)!; - const pendingMsg = room.getPendingEvents()[0]; - - const inboundGroupSessionPromise = expectSendRoomKey("@bob:xyz", testOlmAccount, p2pSession); - - await Promise.all([ - aliceClient.resendEvent(pendingMsg, room), - expectSendMegolmMessage(inboundGroupSessionPromise), - ]); - }); - - oldBackendOnly("We shouldn't attempt to send to blocked devices", async () => { - expectAliceKeyQuery({ device_keys: { "@alice:localhost": {} }, failures: {} }); - await startClientAndAwaitFirstSync(); - await establishOlmSession(aliceClient, keyReceiver, syncResponder, testOlmAccount); - - syncResponder.sendOrQueueSyncResponse(getSyncResponse(["@bob:xyz"])); - await syncPromise(aliceClient); - - logger.log("Forcing alice to download our device keys"); - - expectAliceKeyQuery(getTestKeysQueryResponse("@bob:xyz")); - expectAliceKeyQuery(getTestKeysQueryResponse("@bob:xyz")); - - await aliceClient.downloadKeys(["@bob:xyz"]); - - logger.log("Telling alice to block our device"); - aliceClient.setDeviceBlocked("@bob:xyz", "DEVICE_ID"); - - logger.log("Telling alice to send a megolm message"); - fetchMock.putOnce({ url: new RegExp("/send/"), name: "send-event" }, { event_id: "$event_id" }); - fetchMock.putOnce({ url: new RegExp("/sendToDevice/m.room_key.withheld/"), name: "send-withheld" }, {}); - - await aliceClient.sendTextMessage(ROOM_ID, "test"); - - // check that the event and withheld notifications were both sent - expect(fetchMock.done("send-event")).toBeTruthy(); - expect(fetchMock.done("send-withheld")).toBeTruthy(); - }); - - describe("get|setGlobalErrorOnUnknownDevices", () => { - it("should raise an error if crypto is disabled", () => { - aliceClient["cryptoBackend"] = undefined; - expect(() => aliceClient.setGlobalErrorOnUnknownDevices(true)).toThrow("encryption disabled"); - expect(() => aliceClient.getGlobalErrorOnUnknownDevices()).toThrow("encryption disabled"); - }); - - oldBackendOnly("should permit sending to unknown devices", async () => { - expect(aliceClient.getGlobalErrorOnUnknownDevices()).toBeTruthy(); - - expectAliceKeyQuery({ device_keys: { "@alice:localhost": {} }, failures: {} }); - await startClientAndAwaitFirstSync(); - const p2pSession = await establishOlmSession(aliceClient, keyReceiver, syncResponder, testOlmAccount); - - syncResponder.sendOrQueueSyncResponse(getSyncResponse(["@bob:xyz"])); - await syncPromise(aliceClient); - - // start out with the device unknown - the send should be rejected. - expectAliceKeyQuery(getTestKeysQueryResponse("@bob:xyz")); - expectAliceKeyQuery(getTestKeysQueryResponse("@bob:xyz")); - - await aliceClient.sendTextMessage(ROOM_ID, "test").then( - () => { - throw new Error("sendTextMessage failed on an unknown device"); - }, - (e) => { - expect(e.name).toEqual("UnknownDeviceError"); - }, - ); - - // enable sending to unknown devices, and resend - aliceClient.setGlobalErrorOnUnknownDevices(false); - expect(aliceClient.getGlobalErrorOnUnknownDevices()).toBeFalsy(); - - const room = aliceClient.getRoom(ROOM_ID)!; - const pendingMsg = room.getPendingEvents()[0]; - - const inboundGroupSessionPromise = expectSendRoomKey("@bob:xyz", testOlmAccount, p2pSession); - - await Promise.all([ - aliceClient.resendEvent(pendingMsg, room), - expectSendMegolmMessage(inboundGroupSessionPromise), - ]); - }); - }); - - describe("get|setGlobalBlacklistUnverifiedDevices", () => { - it("should raise an error if crypto is disabled", () => { - aliceClient["cryptoBackend"] = undefined; - expect(() => aliceClient.setGlobalBlacklistUnverifiedDevices(true)).toThrow("encryption disabled"); - expect(() => aliceClient.getGlobalBlacklistUnverifiedDevices()).toThrow("encryption disabled"); - }); - - oldBackendOnly("should disable sending to unverified devices", async () => { - expectAliceKeyQuery({ device_keys: { "@alice:localhost": {} }, failures: {} }); - await startClientAndAwaitFirstSync(); - const p2pSession = await establishOlmSession(aliceClient, keyReceiver, syncResponder, testOlmAccount); - - // tell alice we share a room with bob - syncResponder.sendOrQueueSyncResponse(getSyncResponse(["@bob:xyz"])); - await syncPromise(aliceClient); - - logger.log("Forcing alice to download our device keys"); - expectAliceKeyQuery(getTestKeysQueryResponse("@bob:xyz")); - expectAliceKeyQuery(getTestKeysQueryResponse("@bob:xyz")); - - await aliceClient.downloadKeys(["@bob:xyz"]); - - logger.log("Telling alice to block messages to unverified devices"); - expect(aliceClient.getGlobalBlacklistUnverifiedDevices()).toBeFalsy(); - aliceClient.setGlobalBlacklistUnverifiedDevices(true); - expect(aliceClient.getGlobalBlacklistUnverifiedDevices()).toBeTruthy(); - - logger.log("Telling alice to send a megolm message"); - fetchMock.putOnce(new RegExp("/send/"), { event_id: "$event_id" }); - fetchMock.putOnce(new RegExp("/sendToDevice/m.room_key.withheld/"), {}); - - await aliceClient.sendTextMessage(ROOM_ID, "test"); - - // Now, let's mark the device as verified, and check that keys are sent to it. - - logger.log("Marking the device as verified"); - // XXX: this is an integration test; we really ought to do this via the cross-signing dance - const d = aliceClient.crypto!.deviceList.getStoredDevice("@bob:xyz", "DEVICE_ID")!; - d.verified = DeviceInfo.DeviceVerification.VERIFIED; - aliceClient.crypto?.deviceList.storeDevicesForUser("@bob:xyz", { DEVICE_ID: d }); - - const inboundGroupSessionPromise = expectSendRoomKey("@bob:xyz", testOlmAccount, p2pSession); - - logger.log("Asking alice to re-send"); - await Promise.all([ - expectSendMegolmMessage(inboundGroupSessionPromise).then((decrypted) => { - expect(decrypted.type).toEqual("m.room.message"); - expect(decrypted.content!.body).toEqual("test"); - }), - aliceClient.sendTextMessage(ROOM_ID, "test"), - ]); - }); - - it("should send a m.unverified code in toDevice messages to an unverified device when globalBlacklistUnverifiedDevices=true", async () => { - aliceClient.getCrypto()!.globalBlacklistUnverifiedDevices = true; - - expectAliceKeyQuery({ device_keys: { "@alice:localhost": {} }, failures: {} }); - await startClientAndAwaitFirstSync(); - await establishOlmSession(aliceClient, keyReceiver, syncResponder, testOlmAccount); - - // Tell alice we share a room with bob - syncResponder.sendOrQueueSyncResponse(getSyncResponse(["@bob:xyz"])); - await syncPromise(aliceClient); - - // Force alice to download bob keys - expectAliceKeyQuery(getTestKeysQueryResponse("@bob:xyz")); - - // Wait to receive the toDevice message and return bob device content - const toDevicePromise = new Promise((resolve) => { - fetchMock.putOnce(new RegExp("/sendToDevice/m.room_key.withheld/"), (url, request) => { - const content = JSON.parse(request.body as string); - resolve(content.messages["@bob:xyz"]["DEVICE_ID"]); - return {}; - }); - }); - - // Mock endpoint of message sending - fetchMock.put(new RegExp("/send/"), { event_id: "$event_id" }); - - await aliceClient.sendTextMessage(ROOM_ID, "test"); - - // Finally, check that the toDevice message has the m.unverified code - const toDeviceContent = await toDevicePromise; - expect(toDeviceContent.code).toBe("m.unverified"); - }); - }); - describe("Session should rotate according to encryption settings", () => { /** * Send a message to bob and get the encrypted message @@ -1472,272 +1241,10 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, expect(sessionId).not.toEqual(newSessionId); }); - oldBackendOnly("We should start a new megolm session when a device is blocked", async () => { - expectAliceKeyQuery({ device_keys: { "@alice:localhost": {} }, failures: {} }); - await startClientAndAwaitFirstSync(); - const p2pSession = await establishOlmSession(aliceClient, keyReceiver, syncResponder, testOlmAccount); - - syncResponder.sendOrQueueSyncResponse(getSyncResponse(["@bob:xyz"])); - await syncPromise(aliceClient); - - logger.log("Fetching bob's devices and marking known"); - - expectAliceKeyQuery(getTestKeysQueryResponse("@bob:xyz")); - expectAliceKeyQuery(getTestKeysQueryResponse("@bob:xyz")); - - await aliceClient.downloadKeys(["@bob:xyz"]); - await aliceClient.setDeviceKnown("@bob:xyz", "DEVICE_ID"); - - logger.log("Telling alice to send a megolm message"); - - let megolmSessionId: string; - const inboundGroupSessionPromise = expectSendRoomKey("@bob:xyz", testOlmAccount, p2pSession); - inboundGroupSessionPromise.then((igs) => { - megolmSessionId = igs.session_id(); - }); - - await Promise.all([ - aliceClient.sendTextMessage(ROOM_ID, "test"), - expectSendMegolmMessage(inboundGroupSessionPromise), - ]); - - logger.log("Telling alice to block our device"); - aliceClient.setDeviceBlocked("@bob:xyz", "DEVICE_ID"); - - logger.log("Telling alice to send another megolm message"); - - fetchMock.putOnce( - { url: new RegExp("/send/"), name: "send-event" }, - (url: string, opts: RequestInit): FetchMock.MockResponse => { - const content = JSON.parse(opts.body as string); - logger.log("/send:", content); - // make sure that a new session is used - expect(content.session_id).not.toEqual(megolmSessionId); - return { - event_id: "$event_id", - }; - }, - ); - fetchMock.putOnce({ url: new RegExp("/sendToDevice/m.room_key.withheld/"), name: "send-withheld" }, {}); - - await aliceClient.sendTextMessage(ROOM_ID, "test2"); - - // check that the event and withheld notifications were both sent - expect(fetchMock.done("send-event")).toBeTruthy(); - expect(fetchMock.done("send-withheld")).toBeTruthy(); - }); - - // https://github.com/vector-im/element-web/issues/2676 - oldBackendOnly("Alice should send to her other devices", async () => { - // for this test, we make the testOlmAccount be another of Alice's devices. - // it ought to get included in messages Alice sends. - expectAliceKeyQuery(getTestKeysQueryResponse(aliceClient.getUserId()!)); - - await startClientAndAwaitFirstSync(); - // an encrypted room with just alice - const syncResponse = { - next_batch: 1, - rooms: { - join: { - [ROOM_ID]: { - state: { - events: [ - testUtils.mkEvent({ - type: "m.room.encryption", - skey: "", - content: { algorithm: "m.megolm.v1.aes-sha2" }, - }), - testUtils.mkMembership({ - mship: KnownMembership.Join, - sender: aliceClient.getUserId()!, - }), - ], - }, - }, - }, - }, - }; - syncResponder.sendOrQueueSyncResponse(syncResponse); - - await syncPromise(aliceClient); - - // start out with the device unknown - the send should be rejected. - try { - await aliceClient.sendTextMessage(ROOM_ID, "test"); - throw new Error("sendTextMessage succeeded on an unknown device"); - } catch (e) { - expect((e as any).name).toEqual("UnknownDeviceError"); - expect([...(e as any).devices.keys()]).toEqual([aliceClient.getUserId()!]); - expect((e as any).devices.get(aliceClient.getUserId()!).has("DEVICE_ID")).toBeTruthy(); - } - - // mark the device as known, and resend. - aliceClient.setDeviceKnown(aliceClient.getUserId()!, "DEVICE_ID"); - expectAliceKeyClaim((url: string, opts: RequestInit): FetchMock.MockResponse => { - const content = JSON.parse(opts.body as string); - expect(content.one_time_keys[aliceClient.getUserId()!].DEVICE_ID).toEqual("signed_curve25519"); - return getTestKeysClaimResponse(aliceClient.getUserId()!); - }); - - const inboundGroupSessionPromise = expectSendRoomKey(aliceClient.getUserId()!, testOlmAccount); - - let decrypted: Partial = {}; - - // Grab the event that we'll need to resend - const room = aliceClient.getRoom(ROOM_ID)!; - const pendingEvents = room.getPendingEvents(); - expect(pendingEvents.length).toEqual(1); - const unsentEvent = pendingEvents[0]; - - await Promise.all([ - expectSendMegolmMessage(inboundGroupSessionPromise).then((d) => { - decrypted = d; - }), - aliceClient.resendEvent(unsentEvent, room), - ]); - - expect(decrypted.type).toEqual("m.room.message"); - expect(decrypted.content?.body).toEqual("test"); - }); - - oldBackendOnly("Alice should wait for device list to complete when sending a megolm message", async () => { - expectAliceKeyQuery({ device_keys: { "@alice:localhost": {} }, failures: {} }); - await startClientAndAwaitFirstSync(); - await establishOlmSession(aliceClient, keyReceiver, syncResponder, testOlmAccount); - - syncResponder.sendOrQueueSyncResponse(getSyncResponse(["@bob:xyz"])); - await syncPromise(aliceClient); - - // this will block - logger.log("Forcing alice to download our device keys"); - const downloadPromise = aliceClient.downloadKeys(["@bob:xyz"]); - - expectAliceKeyQuery(getTestKeysQueryResponse("@bob:xyz")); - - // so will this. - const sendPromise = aliceClient.sendTextMessage(ROOM_ID, "test").then( - () => { - throw new Error("sendTextMessage failed on an unknown device"); - }, - (e) => { - expect(e.name).toEqual("UnknownDeviceError"); - }, - ); - - expectAliceKeyQuery(getTestKeysQueryResponse("@bob:xyz")); - - await Promise.all([downloadPromise, sendPromise]); - }); - - oldBackendOnly("Alice exports megolm keys and imports them to a new device", async () => { - expectAliceKeyQuery({ device_keys: { "@alice:localhost": {} }, failures: {} }); - await startClientAndAwaitFirstSync(); - - // if we're using the old crypto impl, stub out some methods in the device manager. - // TODO: replace this with intercepts of the /keys/query endpoint to make it impl agnostic. - if (aliceClient.crypto) { - aliceClient.crypto.deviceList.downloadKeys = () => Promise.resolve(new Map()); - aliceClient.crypto.deviceList.getUserByIdentityKey = () => "@bob:xyz"; - } - - // establish an olm session with alice - const p2pSession = await createOlmSession(testOlmAccount, keyReceiver); - - const groupSession = new Olm.OutboundGroupSession(); - groupSession.create(); - - // make the room_key event - const roomKeyEncrypted = encryptGroupSessionKey({ - recipient: aliceClient.getUserId()!, - recipientCurve25519Key: keyReceiver.getDeviceKey(), - recipientEd25519Key: keyReceiver.getSigningKey(), - olmAccount: testOlmAccount, - p2pSession: p2pSession, - groupSession: groupSession, - room_id: ROOM_ID, - }); - - // encrypt a message with the group session - const messageEncrypted = encryptMegolmEvent({ - senderKey: testSenderKey, - groupSession: groupSession, - room_id: ROOM_ID, - }); - - // Alice gets both the events in a single sync - syncResponder.sendOrQueueSyncResponse({ - next_batch: 1, - to_device: { - events: [roomKeyEncrypted], - }, - rooms: { - join: { [ROOM_ID]: { timeline: { events: [messageEncrypted] } } }, - }, - }); - await syncPromise(aliceClient); - - const room = aliceClient.getRoom(ROOM_ID)!; - await room.decryptCriticalEvents(); - - // it probably won't be decrypted yet, because it takes a while to process the olm keys - const decryptedEvent = await testUtils.awaitDecryption(room.getLiveTimeline().getEvents()[0], { - waitOnDecryptionFailure: true, - }); - expect(decryptedEvent.getContent().body).toEqual("42"); - - const exported = await aliceClient.getCrypto()!.exportRoomKeysAsJson(); - - // start a new client - await aliceClient.stopClient(); - - const homeserverUrl = "https://alice-server2.com"; - aliceClient = createClient({ - baseUrl: homeserverUrl, - userId: "@alice:localhost", - accessToken: "akjgkrgjs", - deviceId: "xzcvb", - }); - - keyReceiver = new E2EKeyReceiver(homeserverUrl); - syncResponder = new SyncResponder(homeserverUrl); - await initCrypto(aliceClient); - await aliceClient.getCrypto()!.importRoomKeysAsJson(exported); - expectAliceKeyQuery({ device_keys: { "@alice:localhost": {} }, failures: {} }); - await startClientAndAwaitFirstSync(); - - aliceClient.startClient(); - - // if we're using the old crypto impl, stub out some methods in the device manager. - // TODO: replace this with intercepts of the /keys/query endpoint to make it impl agnostic. - if (aliceClient.crypto) { - aliceClient.crypto.deviceList.getUserByIdentityKey = () => "@bob:xyz"; - } - - const syncResponse = { - next_batch: 1, - rooms: { - join: { [ROOM_ID]: { timeline: { events: [messageEncrypted] } } }, - }, - }; - - syncResponder.sendOrQueueSyncResponse(syncResponse); - await syncPromise(aliceClient); - - const event = room.getLiveTimeline().getEvents()[0]; - expect(event.getContent().body).toEqual("42"); - }); - it("Alice can decrypt a message with falsey content", async () => { expectAliceKeyQuery({ device_keys: { "@alice:localhost": {} }, failures: {} }); await startClientAndAwaitFirstSync(); - // if we're using the old crypto impl, stub out some methods in the device manager. - // TODO: replace this with intercepts of the /keys/query endpoint to make it impl agnostic. - if (aliceClient.crypto) { - aliceClient.crypto.deviceList.downloadKeys = () => Promise.resolve(new Map()); - aliceClient.crypto.deviceList.getUserByIdentityKey = () => "@bob:xyz"; - } - const p2pSession = await createOlmSession(testOlmAccount, keyReceiver); const groupSession = new Olm.OutboundGroupSession(); groupSession.create(); @@ -1883,7 +1390,6 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, describe("getEncryptionInfoForEvent", () => { it("handles outgoing events", async () => { - aliceClient.setGlobalErrorOnUnknownDevices(false); expectAliceKeyQuery({ device_keys: { "@alice:localhost": {} }, failures: {} }); await startClientAndAwaitFirstSync(); @@ -1987,7 +1493,6 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, // set up the aliceTestClient so that it is a room with no known members expectAliceKeyQuery({ device_keys: { "@alice:localhost": {} }, failures: {} }); await startClientAndAwaitFirstSync({ lazyLoadMembers: true }); - aliceClient.setGlobalErrorOnUnknownDevices(false); syncResponder.sendOrQueueSyncResponse(getSyncResponse([])); await syncPromise(aliceClient); @@ -2790,6 +2295,10 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, await bootstrapSecurity(backupVersion); const check = await aliceClient.getCrypto()!.checkKeyBackupAndEnable(); + fetchMock.get( + `path:/_matrix/client/v3/room_keys/version/${check!.backupInfo.version}`, + check!.backupInfo!, + ); // Import a new key that should be uploaded const newKey = testData.MEGOLM_SESSION_DATA; @@ -2824,9 +2333,8 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, fetchMock.get("express:/_matrix/client/v3/room_keys/keys", keyBackupData); // should be able to restore from 4S - const importResult = await advanceTimersUntil( - aliceClient.restoreKeyBackupWithSecretStorage(check!.backupInfo!), - ); + await aliceClient.getCrypto()!.loadSessionBackupPrivateKeyFromSecretStorage(); + const importResult = await aliceClient.getCrypto()!.restoreKeyBackup(); expect(importResult.imported).toStrictEqual(1); }); @@ -2891,19 +2399,6 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, const newBackupUploadPromise = awaitMegolmBackupKeyUpload(); - // Track calls to scheduleAllGroupSessionsForBackup. This is - // only relevant on legacy encryption. - const scheduleAllGroupSessionsForBackup = jest.fn(); - if (backend === "libolm") { - aliceClient.crypto!.backupManager.scheduleAllGroupSessionsForBackup = - scheduleAllGroupSessionsForBackup; - } else { - // With Rust crypto, we don't need to call this function, so - // we call the dummy value here so we pass our later - // expectation. - scheduleAllGroupSessionsForBackup(); - } - await aliceClient.getCrypto()!.resetKeyBackup(); await awaitDeleteCalled; await newBackupStatusUpdate; @@ -2915,11 +2410,8 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("crypto (%s)", (backend: string, expect(nextVersion).toBeDefined(); expect(nextVersion).not.toEqual(currentVersion); expect(nextKey).not.toEqual(currentBackupKey); - expect(scheduleAllGroupSessionsForBackup).toHaveBeenCalled(); - // The `deleteKeyBackupVersion` API is deprecated but has been modified to work with both crypto backend - // ensure that it works anyhow - await aliceClient.deleteKeyBackupVersion(nextVersion!); + await aliceClient.getCrypto()!.deleteKeyBackupVersion(nextVersion!); await aliceClient.getCrypto()!.checkKeyBackupAndEnable(); // XXX Legacy crypto does not update 4S when doing that; should ensure that rust implem does it. expect(await aliceClient.getCrypto()!.getActiveSessionBackupVersion()).toBeNull(); diff --git a/spec/integ/crypto/device-dehydration.spec.ts b/spec/integ/crypto/device-dehydration.spec.ts index cf319a9878c..4a1165128e1 100644 --- a/spec/integ/crypto/device-dehydration.spec.ts +++ b/spec/integ/crypto/device-dehydration.spec.ts @@ -172,8 +172,8 @@ async function initializeSecretStorage( privateKey: new Uint8Array(32), }; } - await matrixClient.bootstrapCrossSigning({ setupNewCrossSigning: true }); - await matrixClient.bootstrapSecretStorage({ + await matrixClient.getCrypto()!.bootstrapCrossSigning({ setupNewCrossSigning: true }); + await matrixClient.getCrypto()!.bootstrapSecretStorage({ createSecretStorageKey, setupNewSecretStorage: true, setupNewKeyBackup: false, diff --git a/spec/integ/crypto/megolm-backup.spec.ts b/spec/integ/crypto/megolm-backup.spec.ts index eff0ff567e1..b3d6fe335a8 100644 --- a/spec/integ/crypto/megolm-backup.spec.ts +++ b/spec/integ/crypto/megolm-backup.spec.ts @@ -117,7 +117,6 @@ function mockUploadEmitter( describe.each(Object.entries(CRYPTO_BACKENDS))("megolm-keys backup (%s)", (backend: string, initCrypto: InitCrypto) => { // oldBackendOnly is an alternative to `it` or `test` which will skip the test if we are running against the // Rust backend. Once we have full support in the rust sdk, it will go away. - const oldBackendOnly = backend === "rust-sdk" ? test.skip : test; const newBackendOnly = backend === "libolm" ? test.skip : test; const isNewBackend = backend === "rust-sdk"; @@ -344,43 +343,14 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("megolm-keys backup (%s)", (backe fetchMock.get("express:/_matrix/client/v3/room_keys/keys", fullBackup); const check = await aliceCrypto.checkKeyBackupAndEnable(); - - let onKeyCached: () => void; - const awaitKeyCached = new Promise((resolve) => { - onKeyCached = resolve; - }); - await aliceCrypto.storeSessionBackupPrivateKey( decodeRecoveryKey(testData.BACKUP_DECRYPTION_KEY_BASE58), check!.backupInfo!.version!, ); - const result = await advanceTimersUntil( - isNewBackend - ? aliceCrypto.restoreKeyBackup() - : aliceClient.restoreKeyBackupWithRecoveryKey( - testData.BACKUP_DECRYPTION_KEY_BASE58, - undefined, - undefined, - check!.backupInfo!, - { - cacheCompleteCallback: () => onKeyCached(), - }, - ), - ); + const result = await advanceTimersUntil(aliceCrypto.restoreKeyBackup()); expect(result.imported).toStrictEqual(1); - - if (isNewBackend) return; - - await awaitKeyCached; - - // The key should be now cached - const afterCache = await advanceTimersUntil( - aliceClient.restoreKeyBackupWithCache(undefined, undefined, check!.backupInfo!), - ); - - expect(afterCache.imported).toStrictEqual(1); }); /** @@ -434,19 +404,9 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("megolm-keys backup (%s)", (backe ); const progressCallback = jest.fn(); - const result = await (isNewBackend - ? aliceCrypto.restoreKeyBackup({ - progressCallback, - }) - : aliceClient.restoreKeyBackupWithRecoveryKey( - testData.BACKUP_DECRYPTION_KEY_BASE58, - undefined, - undefined, - check!.backupInfo!, - { - progressCallback, - }, - )); + const result = await aliceCrypto.restoreKeyBackup({ + progressCallback, + }); expect(result.imported).toStrictEqual(expectedTotal); // Should be called 5 times: 200*4 plus one chunk with the remaining 32 @@ -508,17 +468,7 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("megolm-keys backup (%s)", (backe ); const progressCallback = jest.fn(); - const result = await (isNewBackend - ? aliceCrypto.restoreKeyBackup({ progressCallback }) - : aliceClient.restoreKeyBackupWithRecoveryKey( - testData.BACKUP_DECRYPTION_KEY_BASE58, - undefined, - undefined, - check!.backupInfo!, - { - progressCallback, - }, - )); + const result = await aliceCrypto.restoreKeyBackup({ progressCallback }); expect(result.total).toStrictEqual(expectedTotal); // A chunk failed to import @@ -574,40 +524,13 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("megolm-keys backup (%s)", (backe check!.backupInfo!.version!, ); - const result = await (isNewBackend - ? aliceCrypto.restoreKeyBackup() - : aliceClient.restoreKeyBackupWithRecoveryKey( - testData.BACKUP_DECRYPTION_KEY_BASE58, - undefined, - undefined, - check!.backupInfo!, - )); + const result = await aliceCrypto.restoreKeyBackup(); expect(result.total).toStrictEqual(expectedTotal); // A chunk failed to import expect(result.imported).toStrictEqual(expectedTotal - decryptionFailureCount); }); - oldBackendOnly("recover specific session from backup", async function () { - fetchMock.get( - "express:/_matrix/client/v3/room_keys/keys/:room_id/:session_id", - testData.CURVE25519_KEY_BACKUP_DATA, - ); - - const check = await aliceCrypto.checkKeyBackupAndEnable(); - - const result = await advanceTimersUntil( - aliceClient.restoreKeyBackupWithRecoveryKey( - testData.BACKUP_DECRYPTION_KEY_BASE58, - ROOM_ID, - testData.MEGOLM_SESSION_DATA.session_id, - check!.backupInfo!, - ), - ); - - expect(result.imported).toStrictEqual(1); - }); - newBackendOnly( "Should get the decryption key from the secret storage and restore the key backup", async function () { @@ -634,31 +557,6 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("megolm-keys backup (%s)", (backe }, ); - oldBackendOnly("Fails on bad recovery key", async function () { - const fullBackup = { - rooms: { - [ROOM_ID]: { - sessions: { - [testData.MEGOLM_SESSION_DATA.session_id]: testData.CURVE25519_KEY_BACKUP_DATA, - }, - }, - }, - }; - - fetchMock.get("express:/_matrix/client/v3/room_keys/keys", fullBackup); - - const check = await aliceCrypto.checkKeyBackupAndEnable(); - - await expect( - aliceClient.restoreKeyBackupWithRecoveryKey( - "EsTx A7Xn aNFF k3jH zpV3 MQoN LJEg mscC HecF 982L wC77 mYQD", - undefined, - undefined, - check!.backupInfo!, - ), - ).rejects.toThrow(); - }); - newBackendOnly("Should throw an error if the decryption key is not found in cache", async () => { await expect(aliceCrypto.restoreKeyBackup()).rejects.toThrow("No decryption key found in crypto store"); }); diff --git a/spec/integ/crypto/rust-crypto.spec.ts b/spec/integ/crypto/rust-crypto.spec.ts index 5aee7e83582..2394d9a3ef9 100644 --- a/spec/integ/crypto/rust-crypto.spec.ts +++ b/spec/integ/crypto/rust-crypto.spec.ts @@ -18,12 +18,13 @@ import "fake-indexeddb/auto"; import { IDBFactory } from "fake-indexeddb"; import fetchMock from "fetch-mock-jest"; -import { createClient, CryptoEvent, IndexedDBCryptoStore } from "../../../src"; +import { createClient, IndexedDBCryptoStore } from "../../../src"; import { populateStore } from "../../test-utils/test_indexeddb_cryptostore_dump"; import { MSK_NOT_CACHED_DATASET } from "../../test-utils/test_indexeddb_cryptostore_dump/no_cached_msk_dump"; import { IDENTITY_NOT_TRUSTED_DATASET } from "../../test-utils/test_indexeddb_cryptostore_dump/unverified"; import { FULL_ACCOUNT_DATASET } from "../../test-utils/test_indexeddb_cryptostore_dump/full_account"; import { EMPTY_ACCOUNT_DATASET } from "../../test-utils/test_indexeddb_cryptostore_dump/empty_account"; +import { CryptoEvent } from "../../../src/crypto-api"; jest.setTimeout(15000); diff --git a/spec/integ/crypto/verification.spec.ts b/spec/integ/crypto/verification.spec.ts index a4cee9e8365..47d92d3e96e 100644 --- a/spec/integ/crypto/verification.spec.ts +++ b/spec/integ/crypto/verification.spec.ts @@ -25,7 +25,6 @@ import Olm from "@matrix-org/olm"; import { createClient, - CryptoEvent, DeviceVerification, IContent, ICreateClientOpts, @@ -81,7 +80,7 @@ import { getTestOlmAccountKeys, ToDeviceEvent, } from "./olm-utils"; -import { KeyBackupInfo } from "../../../src/crypto-api"; +import { KeyBackupInfo, CryptoEvent } from "../../../src/crypto-api"; import { encodeBase64 } from "../../../src/base64"; // The verification flows use javascript timers to set timeouts. We tell jest to use mock timer implementations @@ -907,7 +906,6 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("verification (%s)", (backend: st describe("Send verification request in DM", () => { beforeEach(async () => { aliceClient = await startTestClient(); - aliceClient.setGlobalErrorOnUnknownDevices(false); e2eKeyResponder.addCrossSigningData(BOB_SIGNED_CROSS_SIGNING_KEYS_DATA); e2eKeyResponder.addDeviceKeys(BOB_SIGNED_TEST_DEVICE_DATA); @@ -990,7 +988,6 @@ describe.each(Object.entries(CRYPTO_BACKENDS))("verification (%s)", (backend: st testOlmAccount.create(); aliceClient = await startTestClient(); - aliceClient.setGlobalErrorOnUnknownDevices(false); syncResponder.sendOrQueueSyncResponse(getSyncResponse([BOB_TEST_USER_ID])); await syncPromise(aliceClient); diff --git a/spec/integ/matrix-client-methods.spec.ts b/spec/integ/matrix-client-methods.spec.ts index 11603f53432..6a1544e6f15 100644 --- a/spec/integ/matrix-client-methods.spec.ts +++ b/spec/integ/matrix-client-methods.spec.ts @@ -14,7 +14,6 @@ See the License for the specific language governing permissions and limitations under the License. */ import HttpBackend from "matrix-mock-request"; -import { Mocked } from "jest-mock"; import * as utils from "../test-utils/test-utils"; import { IStoredClientOpts, MatrixClient } from "../../src/client"; @@ -34,7 +33,6 @@ import { THREAD_RELATION_TYPE } from "../../src/models/thread"; import { IFilterDefinition } from "../../src/filter"; import { ISearchResults } from "../../src/@types/search"; import { IStore } from "../../src/store"; -import { CryptoBackend } from "../../src/common-crypto/CryptoBackend"; import { SetPresence } from "../../src/sync"; import { KnownMembership } from "../../src/@types/membership"; @@ -1508,49 +1506,6 @@ describe("MatrixClient", function () { }); }); - describe("uploadKeys", () => { - // uploadKeys() is a no-op nowadays, so there's not much to test here. - it("should complete successfully", async () => { - await client.uploadKeys(); - }); - }); - - describe("getCryptoTrustCrossSignedDevices", () => { - it("should throw if e2e is disabled", () => { - expect(() => client.getCryptoTrustCrossSignedDevices()).toThrow("End-to-end encryption disabled"); - }); - - it("should proxy to the crypto backend", async () => { - const mockBackend = { - getTrustCrossSignedDevices: jest.fn().mockReturnValue(true), - } as unknown as Mocked; - client["cryptoBackend"] = mockBackend; - - expect(client.getCryptoTrustCrossSignedDevices()).toBe(true); - mockBackend.getTrustCrossSignedDevices.mockReturnValue(false); - expect(client.getCryptoTrustCrossSignedDevices()).toBe(false); - }); - }); - - describe("setCryptoTrustCrossSignedDevices", () => { - it("should throw if e2e is disabled", () => { - expect(() => client.setCryptoTrustCrossSignedDevices(false)).toThrow("End-to-end encryption disabled"); - }); - - it("should proxy to the crypto backend", async () => { - const mockBackend = { - setTrustCrossSignedDevices: jest.fn(), - } as unknown as Mocked; - client["cryptoBackend"] = mockBackend; - - client.setCryptoTrustCrossSignedDevices(true); - expect(mockBackend.setTrustCrossSignedDevices).toHaveBeenLastCalledWith(true); - - client.setCryptoTrustCrossSignedDevices(false); - expect(mockBackend.setTrustCrossSignedDevices).toHaveBeenLastCalledWith(false); - }); - }); - describe("setSyncPresence", () => { it("should pass calls through to the underlying sync api", () => { const setPresence = jest.fn(); diff --git a/spec/unit/crypto/backup.spec.ts b/spec/unit/crypto/backup.spec.ts deleted file mode 100644 index 6fc367959bf..00000000000 --- a/spec/unit/crypto/backup.spec.ts +++ /dev/null @@ -1,214 +0,0 @@ -/* -Copyright 2018 New Vector Ltd -Copyright 2019 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -import "../../olm-loader"; -import { logger } from "../../../src/logger"; -import * as olmlib from "../../../src/crypto/olmlib"; -import { MatrixClient } from "../../../src/client"; -import { MatrixEvent } from "../../../src/models/event"; -import * as algorithms from "../../../src/crypto/algorithms"; -import { MemoryCryptoStore } from "../../../src/crypto/store/memory-crypto-store"; -import * as testUtils from "../../test-utils/test-utils"; -import { OlmDevice } from "../../../src/crypto/OlmDevice"; -import { Crypto } from "../../../src/crypto"; -import { BackupManager } from "../../../src/crypto/backup"; -import { StubStore } from "../../../src/store/stub"; -import { MatrixScheduler } from "../../../src"; -import { CryptoStore } from "../../../src/crypto/store/base"; -import { MegolmDecryption as MegolmDecryptionClass } from "../../../src/crypto/algorithms/megolm"; - -const Olm = globalThis.Olm; - -const MegolmDecryption = algorithms.DECRYPTION_CLASSES.get("m.megolm.v1.aes-sha2")!; - -const ROOM_ID = "!ROOM:ID"; - -const CURVE25519_BACKUP_INFO = { - algorithm: olmlib.MEGOLM_BACKUP_ALGORITHM, - version: "1", - auth_data: { - public_key: "hSDwCYkwp1R0i33ctD73Wg2/Og0mOBr066SpjqqbTmo", - }, -}; - -const keys: Record = {}; - -function getCrossSigningKey(type: string) { - return Promise.resolve(keys[type]); -} - -function saveCrossSigningKeys(k: Record) { - Object.assign(keys, k); -} - -function makeTestScheduler(): MatrixScheduler { - return (["getQueueForEvent", "queueEvent", "removeEventFromQueue", "setProcessFunction"] as const).reduce( - (r, k) => { - r[k] = jest.fn(); - return r; - }, - {} as MatrixScheduler, - ); -} - -function makeTestClient(cryptoStore: CryptoStore) { - const scheduler = makeTestScheduler(); - const store = new StubStore(); - - const client = new MatrixClient({ - baseUrl: "https://my.home.server", - idBaseUrl: "https://identity.server", - accessToken: "my.access.token", - fetchFn: jest.fn(), // NOP - store: store, - scheduler: scheduler, - userId: "@alice:bar", - deviceId: "device", - cryptoStore: cryptoStore, - cryptoCallbacks: { getCrossSigningKey, saveCrossSigningKeys }, - }); - - // initialising the crypto library will trigger a key upload request, which we can stub out - client.uploadKeysRequest = jest.fn(); - return client; -} - -describe("MegolmBackup", function () { - if (!globalThis.Olm) { - logger.warn("Not running megolm backup unit tests: libolm not present"); - return; - } - - beforeAll(function () { - return Olm.init(); - }); - - let olmDevice: OlmDevice; - let mockOlmLib: typeof olmlib; - let mockCrypto: Crypto; - let cryptoStore: CryptoStore; - let megolmDecryption: MegolmDecryptionClass; - beforeEach(async function () { - mockCrypto = testUtils.mock(Crypto, "Crypto"); - // @ts-ignore making mock - mockCrypto.backupManager = testUtils.mock(BackupManager, "BackupManager"); - mockCrypto.backupManager.backupInfo = CURVE25519_BACKUP_INFO; - - cryptoStore = new MemoryCryptoStore(); - - olmDevice = new OlmDevice(cryptoStore); - - // we stub out the olm encryption bits - mockOlmLib = {} as unknown as typeof olmlib; - mockOlmLib.ensureOlmSessionsForDevices = jest.fn(); - mockOlmLib.encryptMessageForDevice = jest.fn().mockResolvedValue(undefined); - }); - - describe("backup", function () { - let mockBaseApis: MatrixClient; - - beforeEach(function () { - mockBaseApis = {} as unknown as MatrixClient; - - megolmDecryption = new MegolmDecryption({ - userId: "@user:id", - crypto: mockCrypto, - olmDevice: olmDevice, - baseApis: mockBaseApis, - roomId: ROOM_ID, - }) as MegolmDecryptionClass; - - // @ts-ignore private field access - megolmDecryption.olmlib = mockOlmLib; - - // clobber the setTimeout function to run 100x faster. - // ideally we would use lolex, but we have no oportunity - // to tick the clock between the first try and the retry. - const realSetTimeout = globalThis.setTimeout; - jest.spyOn(globalThis, "setTimeout").mockImplementation(function (f, n) { - return realSetTimeout(f!, n! / 100); - }); - }); - - afterEach(function () { - jest.spyOn(globalThis, "setTimeout").mockRestore(); - }); - - test("fail if crypto not enabled", async () => { - const client = makeTestClient(cryptoStore); - const data = { - algorithm: olmlib.MEGOLM_BACKUP_ALGORITHM, - version: "1", - auth_data: { - public_key: "hSDwCYkwp1R0i33ctD73Wg2/Og0mOBr066SpjqqbTmo", - }, - }; - await expect(client.restoreKeyBackupWithSecretStorage(data)).rejects.toThrow( - "End-to-end encryption disabled", - ); - }); - - it("automatically calls the key back up", function () { - const groupSession = new Olm.OutboundGroupSession(); - groupSession.create(); - - // construct a fake decrypted key event via the use of a mocked - // 'crypto' implementation. - const event = new MatrixEvent({ - type: "m.room.encrypted", - }); - event.getWireType = () => "m.room.encrypted"; - event.getWireContent = () => { - return { - algorithm: "m.olm.v1.curve25519-aes-sha2", - }; - }; - const decryptedData = { - clearEvent: { - type: "m.room_key", - content: { - algorithm: "m.megolm.v1.aes-sha2", - room_id: ROOM_ID, - session_id: groupSession.session_id(), - session_key: groupSession.session_key(), - }, - }, - senderCurve25519Key: "SENDER_CURVE25519", - claimedEd25519Key: "SENDER_ED25519", - }; - - mockCrypto.decryptEvent = function () { - return Promise.resolve(decryptedData); - }; - mockCrypto.cancelRoomKeyRequest = function () {}; - - // @ts-ignore readonly field write - mockCrypto.backupManager = { - backupGroupSession: jest.fn(), - }; - - return event - .attemptDecryption(mockCrypto) - .then(() => { - return megolmDecryption.onRoomKeyEvent(event); - }) - .then(() => { - expect(mockCrypto.backupManager.backupGroupSession).toHaveBeenCalled(); - }); - }); - }); -}); diff --git a/spec/unit/crypto/dehydration.spec.ts b/spec/unit/crypto/dehydration.spec.ts deleted file mode 100644 index 8df92e6314c..00000000000 --- a/spec/unit/crypto/dehydration.spec.ts +++ /dev/null @@ -1,62 +0,0 @@ -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -import "../../olm-loader"; -import { TestClient } from "../../TestClient"; -import { logger } from "../../../src/logger"; -import { DEHYDRATION_ALGORITHM } from "../../../src/crypto/dehydration"; - -const Olm = globalThis.Olm; - -describe("Dehydration", () => { - if (!globalThis.Olm) { - logger.warn("Not running dehydration unit tests: libolm not present"); - return; - } - - beforeAll(function () { - return globalThis.Olm.init(); - }); - - it("should rehydrate a dehydrated device", async () => { - const key = new Uint8Array([1, 2, 3]); - const alice = new TestClient("@alice:example.com", "Osborne2", undefined, undefined, { - cryptoCallbacks: { - getDehydrationKey: async (t) => key, - }, - }); - - const dehydratedDevice = new Olm.Account(); - dehydratedDevice.create(); - - alice.httpBackend.when("GET", "/dehydrated_device").respond(200, { - device_id: "ABCDEFG", - device_data: { - algorithm: DEHYDRATION_ALGORITHM, - account: dehydratedDevice.pickle(new Uint8Array(key)), - }, - }); - alice.httpBackend.when("POST", "/dehydrated_device/claim").respond(200, { - success: true, - }); - - expect((await Promise.all([alice.client.rehydrateDevice(), alice.httpBackend.flushAllExpected()]))[0]).toEqual( - "ABCDEFG", - ); - - expect(alice.client.getDeviceId()).toEqual("ABCDEFG"); - }); -}); diff --git a/spec/unit/embedded.spec.ts b/spec/unit/embedded.spec.ts index c5ef3a6a2c6..fcc315b4574 100644 --- a/spec/unit/embedded.spec.ts +++ b/spec/unit/embedded.spec.ts @@ -728,7 +728,8 @@ describe("RoomWidgetClient", () => { expect(widgetApi.requestCapabilityToSendToDevice).toHaveBeenCalledWith("org.example.foo"); const payload = { type: "org.example.foo", hello: "world" }; - await client.encryptAndSendToDevices( + const embeddedClient = client as RoomWidgetClient; + await embeddedClient.encryptAndSendToDevices( [ { userId: "@alice:example.org", deviceInfo: new DeviceInfo("aliceWeb") }, { userId: "@bob:example.org", deviceInfo: new DeviceInfo("bobDesktop") }, diff --git a/spec/unit/matrix-client.spec.ts b/spec/unit/matrix-client.spec.ts index fa261c9ce69..d5482ccfaf6 100644 --- a/spec/unit/matrix-client.spec.ts +++ b/spec/unit/matrix-client.spec.ts @@ -68,13 +68,11 @@ import { PolicyRecommendation, PolicyScope, } from "../../src/models/invites-ignorer"; -import { IOlmDevice } from "../../src/crypto/algorithms/megolm"; import { defer, QueryDict } from "../../src/utils"; import { SyncState } from "../../src/sync"; import * as featureUtils from "../../src/feature"; import { StubStore } from "../../src/store/stub"; -import { SecretStorageKeyDescriptionAesV1, ServerSideSecretStorageImpl } from "../../src/secret-storage"; -import { CryptoBackend } from "../../src/common-crypto/CryptoBackend"; +import { ServerSideSecretStorageImpl } from "../../src/secret-storage"; import { KnownMembership } from "../../src/@types/membership"; import { RoomMessageEventContent } from "../../src/@types/events"; import { mockOpenIdConfiguration } from "../test-utils/oidc.ts"; @@ -1937,7 +1935,7 @@ describe("MatrixClient", function () { encryptEvent: jest.fn(), stop: jest.fn(), } as unknown as Mocked; - client.crypto = client["cryptoBackend"] = mockCrypto; + client["cryptoBackend"] = mockCrypto; }); function assertCancelled() { @@ -2323,21 +2321,6 @@ describe("MatrixClient", function () { }); }); - describe("encryptAndSendToDevices", () => { - it("throws an error if crypto is unavailable", () => { - client.crypto = undefined; - expect(() => client.encryptAndSendToDevices([], {})).toThrow(); - }); - - it("is an alias for the crypto method", async () => { - client.crypto = testUtils.mock(Crypto, "Crypto"); - const deviceInfos: IOlmDevice[] = []; - const payload = {}; - await client.encryptAndSendToDevices(deviceInfos, payload); - expect(client.crypto.encryptAndSendToDevices).toHaveBeenLastCalledWith(deviceInfos, payload); - }); - }); - describe("support for ignoring invites", () => { beforeEach(() => { // Mockup `getAccountData`/`setAccountData`. @@ -3199,24 +3182,6 @@ describe("MatrixClient", function () { client["_secretStorage"] = mockSecretStorage; }); - it("hasSecretStorageKey", async () => { - mockSecretStorage.hasKey.mockResolvedValue(false); - expect(await client.hasSecretStorageKey("mykey")).toBe(false); - expect(mockSecretStorage.hasKey).toHaveBeenCalledWith("mykey"); - }); - - it("isSecretStored", async () => { - const mockResult = { key: {} as SecretStorageKeyDescriptionAesV1 }; - mockSecretStorage.isStored.mockResolvedValue(mockResult); - expect(await client.isSecretStored("mysecret")).toBe(mockResult); - expect(mockSecretStorage.isStored).toHaveBeenCalledWith("mysecret"); - }); - - it("getDefaultSecretStorageKeyId", async () => { - mockSecretStorage.getDefaultKeyId.mockResolvedValue("bzz"); - expect(await client.getDefaultSecretStorageKeyId()).toEqual("bzz"); - }); - it("isKeyBackupKeyStored", async () => { mockSecretStorage.isStored.mockResolvedValue(null); expect(await client.isKeyBackupKeyStored()).toBe(null); @@ -3224,60 +3189,6 @@ describe("MatrixClient", function () { }); }); - // these wrappers are deprecated, but we need coverage of them to pass the quality gate - describe("Crypto wrappers", () => { - describe("exception if no crypto", () => { - it("isCrossSigningReady", () => { - expect(() => client.isCrossSigningReady()).toThrow("End-to-end encryption disabled"); - }); - - it("bootstrapCrossSigning", () => { - expect(() => client.bootstrapCrossSigning({})).toThrow("End-to-end encryption disabled"); - }); - - it("isSecretStorageReady", () => { - expect(() => client.isSecretStorageReady()).toThrow("End-to-end encryption disabled"); - }); - }); - - describe("defer to crypto backend", () => { - let mockCryptoBackend: Mocked; - - beforeEach(() => { - mockCryptoBackend = { - isCrossSigningReady: jest.fn(), - bootstrapCrossSigning: jest.fn(), - isSecretStorageReady: jest.fn(), - stop: jest.fn().mockResolvedValue(undefined), - } as unknown as Mocked; - client["cryptoBackend"] = mockCryptoBackend; - }); - - it("isCrossSigningReady", async () => { - const testResult = "test"; - mockCryptoBackend.isCrossSigningReady.mockResolvedValue(testResult as unknown as boolean); - expect(await client.isCrossSigningReady()).toBe(testResult); - expect(mockCryptoBackend.isCrossSigningReady).toHaveBeenCalledTimes(1); - }); - - it("bootstrapCrossSigning", async () => { - const testOpts = {}; - mockCryptoBackend.bootstrapCrossSigning.mockResolvedValue(undefined); - await client.bootstrapCrossSigning(testOpts); - expect(mockCryptoBackend.bootstrapCrossSigning).toHaveBeenCalledTimes(1); - expect(mockCryptoBackend.bootstrapCrossSigning).toHaveBeenCalledWith(testOpts); - }); - - it("isSecretStorageReady", async () => { - client["cryptoBackend"] = mockCryptoBackend; - const testResult = "test"; - mockCryptoBackend.isSecretStorageReady.mockResolvedValue(testResult as unknown as boolean); - expect(await client.isSecretStorageReady()).toBe(testResult); - expect(mockCryptoBackend.isSecretStorageReady).toHaveBeenCalledTimes(1); - }); - }); - }); - describe("paginateEventTimeline()", () => { describe("notifications timeline", () => { const unsafeNotification = { diff --git a/spec/unit/room.spec.ts b/spec/unit/room.spec.ts index 9a31e492f3c..c3d08f9a359 100644 --- a/spec/unit/room.spec.ts +++ b/spec/unit/room.spec.ts @@ -3774,7 +3774,7 @@ describe("Room", function () { it("should load pending events from from the store and decrypt if needed", async () => { const client = new TestClient(userA).client; - client.crypto = client["cryptoBackend"] = { + client["cryptoBackend"] = { decryptEvent: jest.fn().mockResolvedValue({ clearEvent: { body: "enc" } }), } as unknown as Crypto; client.store.getPendingEvents = jest.fn(async (roomId) => [ diff --git a/src/client.ts b/src/client.ts index 7447b7f415e..8b4f35f0f6c 100644 --- a/src/client.ts +++ b/src/client.ts @@ -20,7 +20,7 @@ limitations under the License. import { Optional } from "matrix-events-sdk"; -import type { IDeviceKeys, IMegolmSessionData, IOneTimeKey } from "./@types/crypto.ts"; +import type { IDeviceKeys, IOneTimeKey } from "./@types/crypto.ts"; import { ISyncStateData, SetPresence, SyncApi, SyncApiOptions, SyncState } from "./sync.ts"; import { EventStatus, @@ -46,11 +46,8 @@ import { noUnsafeEventProps, QueryDict, replaceParam, safeSet, sleep } from "./u import { Direction, EventTimeline } from "./models/event-timeline.ts"; import { IActionsObject, PushProcessor } from "./pushprocessor.ts"; import { AutoDiscovery, AutoDiscoveryAction } from "./autodiscovery.ts"; -import { decodeBase64, encodeBase64, encodeUnpaddedBase64Url } from "./base64.ts"; -import { IExportedDevice as IExportedOlmDevice } from "./crypto/OlmDevice.ts"; -import { IOlmDevice } from "./crypto/algorithms/megolm.ts"; +import { encodeUnpaddedBase64Url } from "./base64.ts"; import { TypedReEmitter } from "./ReEmitter.ts"; -import { IRoomEncryption } from "./crypto/RoomList.ts"; import { logger, Logger } from "./logger.ts"; import { SERVICE_TYPES } from "./service-types.ts"; import { @@ -73,39 +70,16 @@ import { UploadOpts, UploadResponse, } from "./http-api/index.ts"; -import { - Crypto, - CryptoEvent as LegacyCryptoEvent, - CryptoEventHandlerMap as LegacyCryptoEventHandlerMap, - fixBackupKey, - ICheckOwnCrossSigningTrustOpts, - IRoomKeyRequestBody, - isCryptoAvailable, -} from "./crypto/index.ts"; -import { DeviceInfo } from "./crypto/deviceinfo.ts"; import { User, UserEvent, UserEventHandlerMap } from "./models/user.ts"; import { getHttpUriForMxc } from "./content-repo.ts"; import { SearchResult } from "./models/search-result.ts"; -import { DEHYDRATION_ALGORITHM, IDehydratedDevice, IDehydratedDeviceKeyInfo } from "./crypto/dehydration.ts"; -import { - IKeyBackupInfo, - IKeyBackupPrepareOpts, - IKeyBackupRestoreOpts, - IKeyBackupRestoreResult, - IKeyBackupRoomSessions, - IKeyBackupSession, -} from "./crypto/keybackup.ts"; import { IIdentityServerProvider } from "./@types/IIdentityServerProvider.ts"; import { MatrixScheduler } from "./scheduler.ts"; import { BeaconEvent, BeaconEventHandlerMap } from "./models/beacon.ts"; import { AuthDict } from "./interactive-auth.ts"; import { IMinimalEvent, IRoomEvent, IStateEvent } from "./sync-accumulator.ts"; -import { CrossSigningKey, ICreateSecretStorageOpts, IEncryptedEventInfo, IRecoveryKey } from "./crypto/api.ts"; import { EventTimelineSet } from "./models/event-timeline-set.ts"; -import { VerificationRequest } from "./crypto/verification/request/VerificationRequest.ts"; -import { VerificationBase as Verification } from "./crypto/verification/Base.ts"; import * as ContentHelpers from "./content-helpers.ts"; -import { CrossSigningInfo, DeviceTrustLevel, ICacheCallbacks, UserTrustLevel } from "./crypto/CrossSigning.ts"; import { NotificationCountType, Room, RoomEvent, RoomEventHandlerMap, RoomNameState } from "./models/room.ts"; import { RoomMemberEvent, RoomMemberEventHandlerMap } from "./models/room-member.ts"; import { IPowerLevelsContent, RoomStateEvent, RoomStateEventHandlerMap } from "./models/room-state.ts"; @@ -161,11 +135,9 @@ import { } from "./@types/partials.ts"; import { EventMapper, eventMapperFor, MapperOpts } from "./event-mapper.ts"; import { secureRandomString } from "./randomstring.ts"; -import { BackupManager, IKeyBackup, IKeyBackupCheck, IPreparedKeyBackupVersion, TrustInfo } from "./crypto/backup.ts"; import { DEFAULT_TREE_POWER_LEVELS_TEMPLATE, MSC3089TreeSpace } from "./models/MSC3089TreeSpace.ts"; import { ISignatures } from "./@types/signed.ts"; import { IStore } from "./store/index.ts"; -import { ISecretRequest } from "./crypto/SecretStorage.ts"; import { IEventWithRoomId, ISearchRequestBody, @@ -187,7 +159,7 @@ import { RuleId, } from "./@types/PushRules.ts"; import { IThreepid } from "./@types/threepids.ts"; -import { CryptoStore, OutgoingRoomKeyRequest } from "./crypto/store/base.ts"; +import { CryptoStore } from "./crypto/store/base.ts"; import { GroupCall, GroupCallIntent, GroupCallType, IGroupCallDataChannelOptions } from "./webrtc/groupCall.ts"; import { MediaHandler } from "./webrtc/mediaHandler.ts"; import { @@ -218,26 +190,16 @@ import { IgnoredInvites } from "./models/invites-ignorer.ts"; import { UIARequest, UIAResponse } from "./@types/uia.ts"; import { LocalNotificationSettings } from "./@types/local_notifications.ts"; import { buildFeatureSupportMap, Feature, ServerSupport } from "./feature.ts"; -import { BackupDecryptor, CryptoBackend } from "./common-crypto/CryptoBackend.ts"; +import { CryptoBackend } from "./common-crypto/CryptoBackend.ts"; import { RUST_SDK_STORE_PREFIX } from "./rust-crypto/constants.ts"; import { - BootstrapCrossSigningOpts, CrossSigningKeyInfo, CryptoApi, - decodeRecoveryKey, - ImportRoomKeysOpts, CryptoEvent, CryptoEventHandlerMap, CryptoCallbacks, } from "./crypto-api/index.ts"; -import { DeviceInfoMap } from "./crypto/DeviceList.ts"; -import { - AddSecretStorageKeyOpts, - SecretStorageKey, - SecretStorageKeyDescription, - ServerSideSecretStorage, - ServerSideSecretStorageImpl, -} from "./secret-storage.ts"; +import { SecretStorageKeyDescription, ServerSideSecretStorage, ServerSideSecretStorageImpl } from "./secret-storage.ts"; import { RegisterRequest, RegisterResponse } from "./@types/registration.ts"; import { MatrixRTCSessionManager } from "./matrixrtc/MatrixRTCSessionManager.ts"; import { getRelationsThreadFilter } from "./thread-utils.ts"; @@ -246,7 +208,6 @@ import { RoomMessageEventContent, StickerEventContent } from "./@types/events.ts import { ImageInfo } from "./@types/media.ts"; import { Capabilities, ServerCapabilities } from "./serverCapabilities.ts"; import { sha256 } from "./digest.ts"; -import { keyFromAuthData } from "./common-crypto/key-passphrase.ts"; import { discoverAndValidateOIDCIssuerWellKnown, OidcClientConfig, validateAuthMetadataAndKeys } from "./oidc/index.ts"; export type Store = IStore; @@ -254,10 +215,7 @@ export type Store = IStore; export type ResetTimelineCallback = (roomId: string) => boolean; const SCROLLBACK_DELAY_MS = 3000; -/** - * @deprecated Not supported for Rust Cryptography. - */ -export const CRYPTO_ENABLED: boolean = isCryptoAvailable(); + const TURN_CHECK_INTERVAL = 10 * 60 * 1000; // poll for turn credentials every 10 minutes export const UNSTABLE_MSC3852_LAST_SEEN_UA = new UnstableValue( @@ -265,12 +223,6 @@ export const UNSTABLE_MSC3852_LAST_SEEN_UA = new UnstableValue( "org.matrix.msc3852.last_seen_user_agent", ); -interface IExportedDevice { - olmDevice: IExportedOlmDevice; - userId: string; - deviceId: string; -} - export interface IKeysUploadResponse { one_time_key_counts: { // eslint-disable-line camelcase @@ -378,15 +330,6 @@ export interface ICreateClientOpts { */ queryParams?: Record; - /** - * Device data exported with - * "exportDevice" method that must be imported to recreate this device. - * Should only be useful for devices with end-to-end crypto enabled. - * If provided, deviceId and userId should **NOT** be provided at the top - * level (they are present in the exported data). - */ - deviceToImport?: IExportedDevice; - /** * Encryption key used for encrypting sensitive data (such as e2ee keys) in {@link ICreateClientOpts#cryptoStore}. * @@ -884,14 +827,6 @@ export interface RoomSummary extends Omit; -} - interface IRoomHierarchy { rooms: IHierarchyRoom[]; next_batch?: string; @@ -950,24 +885,6 @@ type RoomStateEvents = | RoomStateEvent.Update | RoomStateEvent.Marker; -type LegacyCryptoEvents = - | LegacyCryptoEvent.KeySignatureUploadFailure - | LegacyCryptoEvent.KeyBackupStatus - | LegacyCryptoEvent.KeyBackupFailed - | LegacyCryptoEvent.KeyBackupSessionsRemaining - | LegacyCryptoEvent.KeyBackupDecryptionKeyCached - | LegacyCryptoEvent.RoomKeyRequest - | LegacyCryptoEvent.RoomKeyRequestCancellation - | LegacyCryptoEvent.VerificationRequest - | LegacyCryptoEvent.VerificationRequestReceived - | LegacyCryptoEvent.DeviceVerificationChanged - | LegacyCryptoEvent.UserTrustStatusChanged - | LegacyCryptoEvent.KeysChanged - | LegacyCryptoEvent.Warning - | LegacyCryptoEvent.DevicesUpdated - | LegacyCryptoEvent.WillUpdateDevices - | LegacyCryptoEvent.LegacyCryptoStoreMigrationProgress; - type CryptoEvents = (typeof CryptoEvent)[keyof typeof CryptoEvent]; type MatrixEventEvents = MatrixEventEvent.Decrypted | MatrixEventEvent.Replaced | MatrixEventEvent.VisibilityChange; @@ -989,7 +906,6 @@ export type EmittedEvents = | ClientEvent | RoomEvents | RoomStateEvents - | LegacyCryptoEvents | CryptoEvents | MatrixEventEvents | RoomMemberEvents @@ -1201,7 +1117,6 @@ export type ClientEventHandlerMap = { [ClientEvent.TurnServersError]: (error: Error, fatal: boolean) => void; } & RoomEventHandlerMap & RoomStateEventHandlerMap & - LegacyCryptoEventHandlerMap & CryptoEventHandlerMap & MatrixEventHandlerMap & RoomMemberEventHandlerMap & @@ -1235,12 +1150,9 @@ export class MatrixClient extends TypedEventEmitter; // XXX: Intended private, used in code. - /** - * The libolm crypto implementation, if it is in use. - * - * @deprecated This should not be used. Instead, use the methods exposed directly on this class or - * (where they are available) via {@link getCrypto}. - */ - public crypto?: Crypto; // XXX: Intended private, used in code. Being replaced by cryptoBackend - private cryptoBackend?: CryptoBackend; // one of crypto or rustCrypto public cryptoCallbacks: CryptoCallbacks; // XXX: Intended private, used in code. public callEventHandler?: CallEventHandler; // XXX: Intended private, used in code. @@ -1278,8 +1182,12 @@ export class MatrixClient extends TypedEventEmitter; errorTs?: number } } = {}; protected notifTimelineSet: EventTimelineSet | null = null; - /* @deprecated */ - protected cryptoStore?: CryptoStore; + + /** + * Legacy crypto store used for migration from the legacy crypto to the rust crypto + * @private + */ + private readonly legacyCryptoStore?: CryptoStore; protected verificationMethods?: string[]; protected fallbackICEServerAllowed = false; protected syncApi?: SlidingSyncSdk | SyncApi; @@ -1305,7 +1213,6 @@ export class MatrixClient extends TypedEventEmitter; - protected exportedOlmDeviceToImport?: IExportedOlmDevice; protected txnCtr = 0; protected mediaHandler = new MediaHandler(this); protected sessionId: string; @@ -1367,27 +1274,8 @@ export class MatrixClient extends TypedEventEmitter { - if (this.crypto) { - throw new Error("Cannot rehydrate device after crypto is initialized"); - } - - if (!this.cryptoCallbacks.getDehydrationKey) { - return; - } - - const getDeviceResult = await this.getDehydratedDevice(); - if (!getDeviceResult) { - return; - } - - if (!getDeviceResult.device_data || !getDeviceResult.device_id) { - this.logger.info("no dehydrated device found"); - return; - } - - const account = new globalThis.Olm.Account(); - try { - const deviceData = getDeviceResult.device_data; - if (deviceData.algorithm !== DEHYDRATION_ALGORITHM) { - this.logger.warn("Wrong algorithm for dehydrated device"); - return; - } - this.logger.debug("unpickling dehydrated device"); - const key = await this.cryptoCallbacks.getDehydrationKey(deviceData, (k) => { - // copy the key so that it doesn't get clobbered - account.unpickle(new Uint8Array(k), deviceData.account); - }); - account.unpickle(key, deviceData.account); - this.logger.debug("unpickled device"); - - const rehydrateResult = await this.http.authedRequest<{ success: boolean }>( - Method.Post, - "/dehydrated_device/claim", - undefined, - { - device_id: getDeviceResult.device_id, - }, - { - prefix: "/_matrix/client/unstable/org.matrix.msc2697.v2", - }, - ); - - if (rehydrateResult.success) { - this.deviceId = getDeviceResult.device_id; - this.logger.info("using dehydrated device"); - const pickleKey = this.pickleKey || "DEFAULT_KEY"; - this.exportedOlmDeviceToImport = { - pickledAccount: account.pickle(pickleKey), - sessions: [], - pickleKey: pickleKey, - }; - account.free(); - return this.deviceId; - } else { - account.free(); - this.logger.info("not using dehydrated device"); - return; - } - } catch (e) { - account.free(); - this.logger.warn("could not unpickle", e); - } - } - - /** - * Get the current dehydrated device, if any - * @returns A promise of an object containing the dehydrated device - * - * @deprecated MSC2697 device dehydration is not supported for rust cryptography. - */ - public async getDehydratedDevice(): Promise { - try { - return await this.http.authedRequest( - Method.Get, - "/dehydrated_device", - undefined, - undefined, - { - prefix: "/_matrix/client/unstable/org.matrix.msc2697.v2", - }, - ); - } catch (e) { - this.logger.info("could not get dehydrated device", e); - return; - } - } - - /** - * Set the dehydration key. This will also periodically dehydrate devices to - * the server. - * - * @param key - the dehydration key - * @param keyInfo - Information about the key. Primarily for - * information about how to generate the key from a passphrase. - * @param deviceDisplayName - The device display name for the - * dehydrated device. - * @returns A promise that resolves when the dehydrated device is stored. - * - * @deprecated Not supported for Rust Cryptography. - */ - public async setDehydrationKey( - key: Uint8Array, - keyInfo: IDehydratedDeviceKeyInfo, - deviceDisplayName?: string, - ): Promise { - if (!this.crypto) { - this.logger.warn("not dehydrating device if crypto is not enabled"); - return; - } - return this.crypto.dehydrationManager.setKeyAndQueueDehydration(key, keyInfo, deviceDisplayName); - } - - /** - * Creates a new MSC2967 dehydrated device (without queuing periodic dehydration) - * @param key - the dehydration key - * @param keyInfo - Information about the key. Primarily for - * information about how to generate the key from a passphrase. - * @param deviceDisplayName - The device display name for the - * dehydrated device. - * @returns the device id of the newly created dehydrated device - * - * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.startDehydration}. - */ - public async createDehydratedDevice( - key: Uint8Array, - keyInfo: IDehydratedDeviceKeyInfo, - deviceDisplayName?: string, - ): Promise { - if (!this.crypto) { - this.logger.warn("not dehydrating device if crypto is not enabled"); - return; - } - await this.crypto.dehydrationManager.setKey(key, keyInfo, deviceDisplayName); - return this.crypto.dehydrationManager.dehydrateDevice(); - } - - /** @deprecated Not supported for Rust Cryptography. */ - public async exportDevice(): Promise { - if (!this.crypto) { - this.logger.warn("not exporting device if crypto is not enabled"); - return; - } - return { - userId: this.credentials.userId!, - deviceId: this.deviceId!, - // XXX: Private member access. - olmDevice: await this.crypto.olmDevice.export(), - }; - } - /** * Clear any data out of the persistent stores used by the client. * @@ -1782,8 +1505,8 @@ export class MatrixClient extends TypedEventEmitter[] = []; promises.push(this.store.deleteAllData()); - if (this.cryptoStore) { - promises.push(this.cryptoStore.deleteAllData()); + if (this.legacyCryptoStore) { + promises.push(this.legacyCryptoStore.deleteAllData()); } // delete the stores used by the rust matrix-sdk-crypto, in case they were used @@ -2069,1992 +1792,231 @@ export class MatrixClient extends TypedEventEmitterexplicitly attempts to retry their lost connection. - * Will also retry any outbound to-device messages currently in the queue to be sent - * (retries of regular outgoing events are handled separately, per-event). - * @returns True if this resulted in a request being retried. - */ - public retryImmediately(): boolean { - // don't await for this promise: we just want to kick it off - this.toDeviceMessageQueue.sendQueue(); - return this.syncApi?.retryImmediately() ?? false; - } - - /** - * Return the global notification EventTimelineSet, if any - * - * @returns the globl notification EventTimelineSet - */ - public getNotifTimelineSet(): EventTimelineSet | null { - return this.notifTimelineSet; - } - - /** - * Set the global notification EventTimelineSet - * - */ - public setNotifTimelineSet(set: EventTimelineSet): void { - this.notifTimelineSet = set; - } - - /** - * Gets the cached capabilities of the homeserver, returning cached ones if available. - * If there are no cached capabilities and none can be fetched, throw an exception. - * - * @returns Promise resolving with The capabilities of the homeserver - */ - public async getCapabilities(): Promise { - const caps = this.serverCapabilitiesService.getCachedCapabilities(); - if (caps) return caps; - return this.serverCapabilitiesService.fetchCapabilities(); - } - - /** - * Gets the cached capabilities of the homeserver. If none have been fetched yet, - * return undefined. - * - * @returns The capabilities of the homeserver - */ - public getCachedCapabilities(): Capabilities | undefined { - return this.serverCapabilitiesService.getCachedCapabilities(); - } - - /** - * Fetches the latest capabilities from the homeserver, ignoring any cached - * versions. The newly returned version is cached. - * - * @returns A promise which resolves to the capabilities of the homeserver - */ - public fetchCapabilities(): Promise { - return this.serverCapabilitiesService.fetchCapabilities(); - } - - /** - * Initialise support for end-to-end encryption in this client, using the rust matrix-sdk-crypto. - * - * **WARNING**: the cryptography stack is not thread-safe. Having multiple `MatrixClient` instances connected to - * the same Indexed DB will cause data corruption and decryption failures. The application layer is responsible for - * ensuring that only one `MatrixClient` issue is instantiated at a time. - * - * @param args.useIndexedDB - True to use an indexeddb store, false to use an in-memory store. Defaults to 'true'. - * @param args.storageKey - A key with which to encrypt the indexeddb store. If provided, it must be exactly - * 32 bytes of data, and must be the same each time the client is initialised for a given device. - * If both this and `storagePassword` are unspecified, the store will be unencrypted. - * @param args.storagePassword - An alternative to `storageKey`. A password which will be used to derive a key to - * encrypt the store with. Deriving a key from a password is (deliberately) a slow operation, so prefer - * to pass a `storageKey` directly where possible. - * - * @returns a Promise which will resolve when the crypto layer has been - * successfully initialised. - */ - public async initRustCrypto( - args: { - useIndexedDB?: boolean; - storageKey?: Uint8Array; - storagePassword?: string; - } = {}, - ): Promise { - if (this.cryptoBackend) { - this.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient"); - return; - } - - const userId = this.getUserId(); - if (userId === null) { - throw new Error( - `Cannot enable encryption on MatrixClient with unknown userId: ` + - `ensure userId is passed in createClient().`, - ); - } - const deviceId = this.getDeviceId(); - if (deviceId === null) { - throw new Error( - `Cannot enable encryption on MatrixClient with unknown deviceId: ` + - `ensure deviceId is passed in createClient().`, - ); - } - - // importing rust-crypto will download the webassembly, so we delay it until we know it will be - // needed. - this.logger.debug("Downloading Rust crypto library"); - const RustCrypto = await import("./rust-crypto/index.ts"); - - const rustCrypto = await RustCrypto.initRustCrypto({ - logger: this.logger, - http: this.http, - userId: userId, - deviceId: deviceId, - secretStorage: this.secretStorage, - cryptoCallbacks: this.cryptoCallbacks, - storePrefix: args.useIndexedDB === false ? null : RUST_SDK_STORE_PREFIX, - storeKey: args.storageKey, - storePassphrase: args.storagePassword, - - legacyCryptoStore: this.cryptoStore, - legacyPickleKey: this.pickleKey ?? "DEFAULT_KEY", - legacyMigrationProgressListener: (progress: number, total: number): void => { - this.emit(CryptoEvent.LegacyCryptoStoreMigrationProgress, progress, total); - }, - }); - - rustCrypto.setSupportedVerificationMethods(this.verificationMethods); - - this.cryptoBackend = rustCrypto; - - // attach the event listeners needed by RustCrypto - this.on(RoomMemberEvent.Membership, rustCrypto.onRoomMembership.bind(rustCrypto)); - this.on(ClientEvent.Event, (event) => { - rustCrypto.onLiveEventFromSync(event); - }); - - // re-emit the events emitted by the crypto impl - this.reEmitter.reEmit(rustCrypto, [ - CryptoEvent.VerificationRequestReceived, - CryptoEvent.UserTrustStatusChanged, - CryptoEvent.KeyBackupStatus, - CryptoEvent.KeyBackupSessionsRemaining, - CryptoEvent.KeyBackupFailed, - CryptoEvent.KeyBackupDecryptionKeyCached, - CryptoEvent.KeysChanged, - CryptoEvent.DevicesUpdated, - CryptoEvent.WillUpdateDevices, - ]); - } - - /** - * Access the server-side secret storage API for this client. - */ - public get secretStorage(): ServerSideSecretStorage { - return this._secretStorage; - } - - /** - * Access the crypto API for this client. - * - * If end-to-end encryption has been enabled for this client (via {@link initRustCrypto}), - * returns an object giving access to the crypto API. Otherwise, returns `undefined`. - */ - public getCrypto(): CryptoApi | undefined { - return this.cryptoBackend; - } - - /** - * Is end-to-end crypto enabled for this client. - * @returns True if end-to-end is enabled. - * @deprecated prefer {@link getCrypto} - */ - public isCryptoEnabled(): boolean { - return !!this.cryptoBackend; - } - - /** - * Get the Ed25519 key for this device - * - * @returns base64-encoded ed25519 key. Null if crypto is - * disabled. - * - * @deprecated Not supported for Rust Cryptography.Prefer {@link CryptoApi.getOwnDeviceKeys} - */ - public getDeviceEd25519Key(): string | null { - return this.crypto?.getDeviceEd25519Key() ?? null; - } - - /** - * Get the Curve25519 key for this device - * - * @returns base64-encoded curve25519 key. Null if crypto is - * disabled. - * - * @deprecated Not supported for Rust Cryptography. Use {@link CryptoApi.getOwnDeviceKeys} - */ - public getDeviceCurve25519Key(): string | null { - return this.crypto?.getDeviceCurve25519Key() ?? null; - } - - /** - * @deprecated Does nothing. - */ - public async uploadKeys(): Promise { - this.logger.warn("MatrixClient.uploadKeys is deprecated"); - } - - /** - * Download the keys for a list of users and stores the keys in the session - * store. - * @param userIds - The users to fetch. - * @param forceDownload - Always download the keys even if cached. - * - * @returns A promise which resolves to a map userId-\>deviceId-\>`DeviceInfo` - * - * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.getUserDeviceInfo} - */ - public downloadKeys(userIds: string[], forceDownload?: boolean): Promise { - if (!this.crypto) { - return Promise.reject(new Error("End-to-end encryption disabled")); - } - return this.crypto.downloadKeys(userIds, forceDownload); - } - - /** - * Get the stored device keys for a user id - * - * @param userId - the user to list keys for. - * - * @returns list of devices - * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.getUserDeviceInfo} - */ - public getStoredDevicesForUser(userId: string): DeviceInfo[] { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.getStoredDevicesForUser(userId) || []; - } - - /** - * Get the stored device key for a user id and device id - * - * @param userId - the user to list keys for. - * @param deviceId - unique identifier for the device - * - * @returns device or null - * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.getUserDeviceInfo} - */ - public getStoredDevice(userId: string, deviceId: string): DeviceInfo | null { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.getStoredDevice(userId, deviceId) || null; - } - - /** - * Mark the given device as verified - * - * @param userId - owner of the device - * @param deviceId - unique identifier for the device or user's - * cross-signing public key ID. - * - * @param verified - whether to mark the device as verified. defaults - * to 'true'. - * - * @returns - * - * @remarks - * Fires {@link CryptoEvent#DeviceVerificationChanged} - * - * @deprecated Not supported for Rust Cryptography. - */ - public setDeviceVerified(userId: string, deviceId: string, verified = true): Promise { - const prom = this.setDeviceVerification(userId, deviceId, verified, null, null); - - // if one of the user's own devices is being marked as verified / unverified, - // check the key backup status, since whether or not we use this depends on - // whether it has a signature from a verified device - if (userId == this.credentials.userId) { - this.checkKeyBackup(); - } - return prom; - } - - /** - * Mark the given device as blocked/unblocked - * - * @param userId - owner of the device - * @param deviceId - unique identifier for the device or user's - * cross-signing public key ID. - * - * @param blocked - whether to mark the device as blocked. defaults - * to 'true'. - * - * @returns - * - * @remarks - * Fires {@link LegacyCryptoEvent.DeviceVerificationChanged} - * - * @deprecated Not supported for Rust Cryptography. - */ - public setDeviceBlocked(userId: string, deviceId: string, blocked = true): Promise { - return this.setDeviceVerification(userId, deviceId, null, blocked, null); - } - - /** - * Mark the given device as known/unknown - * - * @param userId - owner of the device - * @param deviceId - unique identifier for the device or user's - * cross-signing public key ID. - * - * @param known - whether to mark the device as known. defaults - * to 'true'. - * - * @returns - * - * @remarks - * Fires {@link CryptoEvent#DeviceVerificationChanged} - * - * @deprecated Not supported for Rust Cryptography. - */ - public setDeviceKnown(userId: string, deviceId: string, known = true): Promise { - return this.setDeviceVerification(userId, deviceId, null, null, known); - } - - private async setDeviceVerification( - userId: string, - deviceId: string, - verified?: boolean | null, - blocked?: boolean | null, - known?: boolean | null, - ): Promise { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - await this.crypto.setDeviceVerification(userId, deviceId, verified, blocked, known); - } - - /** - * Request a key verification from another user, using a DM. - * - * @param userId - the user to request verification with - * @param roomId - the room to use for verification - * - * @returns resolves to a VerificationRequest - * when the request has been sent to the other party. - * - * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.requestVerificationDM}. - */ - public requestVerificationDM(userId: string, roomId: string): Promise { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.requestVerificationDM(userId, roomId); - } - - /** - * Finds a DM verification request that is already in progress for the given room id - * - * @param roomId - the room to use for verification - * - * @returns the VerificationRequest that is in progress, if any - * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.findVerificationRequestDMInProgress}. - */ - public findVerificationRequestDMInProgress(roomId: string): VerificationRequest | undefined { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } else if (!this.crypto) { - // Hack for element-R to avoid breaking the cypress tests. We can get rid of this once the react-sdk is - // updated to use CryptoApi.findVerificationRequestDMInProgress. - return undefined; - } - return this.crypto.findVerificationRequestDMInProgress(roomId); - } - - /** - * Returns all to-device verification requests that are already in progress for the given user id - * - * @param userId - the ID of the user to query - * - * @returns the VerificationRequests that are in progress - * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.getVerificationRequestsToDeviceInProgress}. - */ - public getVerificationRequestsToDeviceInProgress(userId: string): VerificationRequest[] { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.getVerificationRequestsToDeviceInProgress(userId); - } - - /** - * Request a key verification from another user. - * - * @param userId - the user to request verification with - * @param devices - array of device IDs to send requests to. Defaults to - * all devices owned by the user - * - * @returns resolves to a VerificationRequest - * when the request has been sent to the other party. - * - * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi#requestOwnUserVerification} or {@link CryptoApi#requestDeviceVerification}. - */ - public requestVerification(userId: string, devices?: string[]): Promise { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.requestVerification(userId, devices); - } - - /** - * Begin a key verification. - * - * @param method - the verification method to use - * @param userId - the user to verify keys with - * @param deviceId - the device to verify - * - * @returns a verification object - * @deprecated Prefer {@link CryptoApi#requestOwnUserVerification} or {@link CryptoApi#requestDeviceVerification}. - */ - public beginKeyVerification(method: string, userId: string, deviceId: string): Verification { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.beginKeyVerification(method, userId, deviceId); - } - - /** - * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#checkKey}. - */ - public checkSecretStorageKey(key: Uint8Array, info: SecretStorageKeyDescription): Promise { - return this.secretStorage.checkKey(key, info); - } - - /** - * Set the global override for whether the client should ever send encrypted - * messages to unverified devices. This provides the default for rooms which - * do not specify a value. - * - * @param value - whether to blacklist all unverified devices by default - * - * @deprecated Prefer direct access to {@link CryptoApi.globalBlacklistUnverifiedDevices}: - * - * ```javascript - * client.getCrypto().globalBlacklistUnverifiedDevices = value; - * ``` - */ - public setGlobalBlacklistUnverifiedDevices(value: boolean): boolean { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - this.cryptoBackend.globalBlacklistUnverifiedDevices = value; - return value; - } - - /** - * @returns whether to blacklist all unverified devices by default - * - * @deprecated Prefer direct access to {@link CryptoApi.globalBlacklistUnverifiedDevices}: - * - * ```javascript - * value = client.getCrypto().globalBlacklistUnverifiedDevices; - * ``` - */ - public getGlobalBlacklistUnverifiedDevices(): boolean { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.globalBlacklistUnverifiedDevices; - } - - /** - * Set whether sendMessage in a room with unknown and unverified devices - * should throw an error and not send them message. This has 'Global' for - * symmetry with setGlobalBlacklistUnverifiedDevices but there is currently - * no room-level equivalent for this setting. - * - * This API is currently UNSTABLE and may change or be removed without notice. - * - * It has no effect with the Rust crypto implementation. - * - * @param value - whether error on unknown devices - * - * ```ts - * client.getCrypto().globalErrorOnUnknownDevices = value; - * ``` - */ - public setGlobalErrorOnUnknownDevices(value: boolean): void { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - this.cryptoBackend.globalErrorOnUnknownDevices = value; - } - - /** - * @returns whether to error on unknown devices - * - * This API is currently UNSTABLE and may change or be removed without notice. - */ - public getGlobalErrorOnUnknownDevices(): boolean { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.globalErrorOnUnknownDevices; - } - - /** - * Get the ID of one of the user's cross-signing keys - * - * @param type - The type of key to get the ID of. One of - * "master", "self_signing", or "user_signing". Defaults to "master". - * - * @returns the key ID - * @deprecated Not supported for Rust Cryptography. prefer {@link Crypto.CryptoApi#getCrossSigningKeyId} - */ - public getCrossSigningId(type: CrossSigningKey | string = CrossSigningKey.Master): string | null { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.getCrossSigningId(type); - } - - /** - * Get the cross signing information for a given user. - * - * The cross-signing API is currently UNSTABLE and may change without notice. - * - * @param userId - the user ID to get the cross-signing info for. - * - * @returns the cross signing information for the user. - * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi#userHasCrossSigningKeys} - */ - public getStoredCrossSigningForUser(userId: string): CrossSigningInfo | null { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.getStoredCrossSigningForUser(userId); - } - - /** - * Check whether a given user is trusted. - * - * The cross-signing API is currently UNSTABLE and may change without notice. - * - * @param userId - The ID of the user to check. - * - * @deprecated Use {@link Crypto.CryptoApi.getUserVerificationStatus | `CryptoApi.getUserVerificationStatus`} - */ - public checkUserTrust(userId: string): UserTrustLevel { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.checkUserTrust(userId); - } - - /** - * Check whether a given device is trusted. - * - * The cross-signing API is currently UNSTABLE and may change without notice. - * - * @param userId - The ID of the user whose devices is to be checked. - * @param deviceId - The ID of the device to check - * - * @deprecated Use {@link Crypto.CryptoApi.getDeviceVerificationStatus | `CryptoApi.getDeviceVerificationStatus`} - */ - public checkDeviceTrust(userId: string, deviceId: string): DeviceTrustLevel { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.checkDeviceTrust(userId, deviceId); - } - - /** - * Check whether one of our own devices is cross-signed by our - * user's stored keys, regardless of whether we trust those keys yet. - * - * @param deviceId - The ID of the device to check - * - * @returns true if the device is cross-signed - * - * @deprecated Not supported for Rust Cryptography. - */ - public checkIfOwnDeviceCrossSigned(deviceId: string): boolean { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.checkIfOwnDeviceCrossSigned(deviceId); - } - - /** - * Check the copy of our cross-signing key that we have in the device list and - * see if we can get the private key. If so, mark it as trusted. - * @param opts - ICheckOwnCrossSigningTrustOpts object - * - * @deprecated Unneeded for the new crypto - */ - public checkOwnCrossSigningTrust(opts?: ICheckOwnCrossSigningTrustOpts): Promise { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.checkOwnCrossSigningTrust(opts); - } - - /** - * Checks that a given cross-signing private key matches a given public key. - * This can be used by the getCrossSigningKey callback to verify that the - * private key it is about to supply is the one that was requested. - * @param privateKey - The private key - * @param expectedPublicKey - The public key - * @returns true if the key matches, otherwise false - * - * @deprecated Not supported for Rust Cryptography. - */ - public checkCrossSigningPrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.checkCrossSigningPrivateKey(privateKey, expectedPublicKey); - } - - /** - * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi#requestDeviceVerification}. - */ - public legacyDeviceVerification(userId: string, deviceId: string, method: string): Promise { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.legacyDeviceVerification(userId, deviceId, method); - } - - /** - * Perform any background tasks that can be done before a message is ready to - * send, in order to speed up sending of the message. - * @param room - the room the event is in - * - * @deprecated Prefer {@link CryptoApi.prepareToEncrypt | `CryptoApi.prepareToEncrypt`}: - * - * ```javascript - * client.getCrypto().prepareToEncrypt(room); - * ``` - */ - public prepareToEncrypt(room: Room): void { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - this.cryptoBackend.prepareToEncrypt(room); - } - - /** - * Checks if the user has previously published cross-signing keys - * - * This means downloading the devicelist for the user and checking if the list includes - * the cross-signing pseudo-device. - * - * @deprecated Prefer {@link CryptoApi.userHasCrossSigningKeys | `CryptoApi.userHasCrossSigningKeys`}: - * - * ```javascript - * result = client.getCrypto().userHasCrossSigningKeys(); - * ``` - */ - public userHasCrossSigningKeys(): Promise { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.userHasCrossSigningKeys(); - } - - /** - * Checks whether cross signing: - * - is enabled on this account and trusted by this device - * - has private keys either cached locally or stored in secret storage - * - * If this function returns false, bootstrapCrossSigning() can be used - * to fix things such that it returns true. That is to say, after - * bootstrapCrossSigning() completes successfully, this function should - * return true. - * @returns True if cross-signing is ready to be used on this device - * @deprecated Prefer {@link CryptoApi.isCrossSigningReady | `CryptoApi.isCrossSigningReady`}: - */ - public isCrossSigningReady(): Promise { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.isCrossSigningReady(); - } - - /** - * Bootstrap cross-signing by creating keys if needed. If everything is already - * set up, then no changes are made, so this is safe to run to ensure - * cross-signing is ready for use. - * - * This function: - * - creates new cross-signing keys if they are not found locally cached nor in - * secret storage (if it has been set up) - * - * @deprecated Prefer {@link CryptoApi.bootstrapCrossSigning | `CryptoApi.bootstrapCrossSigning`}. - */ - public bootstrapCrossSigning(opts: BootstrapCrossSigningOpts): Promise { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.bootstrapCrossSigning(opts); - } - - /** - * Whether to trust a others users signatures of their devices. - * If false, devices will only be considered 'verified' if we have - * verified that device individually (effectively disabling cross-signing). - * - * Default: true - * - * @returns True if trusting cross-signed devices - * - * @deprecated Prefer {@link CryptoApi.getTrustCrossSignedDevices | `CryptoApi.getTrustCrossSignedDevices`}. - */ - public getCryptoTrustCrossSignedDevices(): boolean { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.getTrustCrossSignedDevices(); - } - - /** - * See getCryptoTrustCrossSignedDevices - * - * @param val - True to trust cross-signed devices - * - * @deprecated Prefer {@link CryptoApi.setTrustCrossSignedDevices | `CryptoApi.setTrustCrossSignedDevices`}. - */ - public setCryptoTrustCrossSignedDevices(val: boolean): void { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - this.cryptoBackend.setTrustCrossSignedDevices(val); - } - - /** - * Counts the number of end to end session keys that are waiting to be backed up - * @returns Promise which resolves to the number of sessions requiring backup - * - * @deprecated Not supported for Rust Cryptography. - */ - public countSessionsNeedingBackup(): Promise { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.countSessionsNeedingBackup(); - } - - /** - * Get information about the encryption of an event - * - * @param event - event to be checked - * @returns The event information. - * @deprecated Prefer {@link Crypto.CryptoApi.getEncryptionInfoForEvent | `CryptoApi.getEncryptionInfoForEvent`}. - */ - public getEventEncryptionInfo(event: MatrixEvent): IEncryptedEventInfo { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.getEventEncryptionInfo(event); - } - - /** - * Create a recovery key from a user-supplied passphrase. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param password - Passphrase string that can be entered by the user - * when restoring the backup as an alternative to entering the recovery key. - * Optional. - * @returns Object with public key metadata, encoded private - * recovery key which should be disposed of after displaying to the user, - * and raw private key to avoid round tripping if needed. - * - * @deprecated Prefer {@link CryptoApi.createRecoveryKeyFromPassphrase | `CryptoApi.createRecoveryKeyFromPassphrase`}. - */ - public createRecoveryKeyFromPassphrase(password?: string): Promise { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.createRecoveryKeyFromPassphrase(password); - } - - /** - * Checks whether secret storage: - * - is enabled on this account - * - is storing cross-signing private keys - * - is storing session backup key (if enabled) - * - * If this function returns false, bootstrapSecretStorage() can be used - * to fix things such that it returns true. That is to say, after - * bootstrapSecretStorage() completes successfully, this function should - * return true. - * - * @returns True if secret storage is ready to be used on this device - * @deprecated Prefer {@link CryptoApi.isSecretStorageReady | `CryptoApi.isSecretStorageReady`}. - */ - public isSecretStorageReady(): Promise { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.isSecretStorageReady(); - } - - /** - * Bootstrap Secure Secret Storage if needed by creating a default key. If everything is - * already set up, then no changes are made, so this is safe to run to ensure secret - * storage is ready for use. - * - * This function - * - creates a new Secure Secret Storage key if no default key exists - * - if a key backup exists, it is migrated to store the key in the Secret - * Storage - * - creates a backup if none exists, and one is requested - * - migrates Secure Secret Storage to use the latest algorithm, if an outdated - * algorithm is found - * - * @deprecated Use {@link CryptoApi.bootstrapSecretStorage | `CryptoApi.bootstrapSecretStorage`}. - */ - public bootstrapSecretStorage(opts: ICreateSecretStorageOpts): Promise { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.bootstrapSecretStorage(opts); - } - - /** - * Add a key for encrypting secrets. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param algorithm - the algorithm used by the key - * @param opts - the options for the algorithm. The properties used - * depend on the algorithm given. - * @param keyName - the name of the key. If not given, a random name will be generated. - * - * @returns An object with: - * keyId: the ID of the key - * keyInfo: details about the key (iv, mac, passphrase) - * - * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#addKey}. - */ - public addSecretStorageKey( - algorithm: string, - opts: AddSecretStorageKeyOpts, - keyName?: string, - ): Promise<{ keyId: string; keyInfo: SecretStorageKeyDescription }> { - return this.secretStorage.addKey(algorithm, opts, keyName); - } - - /** - * Check whether we have a key with a given ID. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param keyId - The ID of the key to check - * for. Defaults to the default key ID if not provided. - * @returns Whether we have the key. - * - * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#hasKey}. - */ - public hasSecretStorageKey(keyId?: string): Promise { - return this.secretStorage.hasKey(keyId); - } - - /** - * Store an encrypted secret on the server. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param name - The name of the secret - * @param secret - The secret contents. - * @param keys - The IDs of the keys to use to encrypt the secret or null/undefined - * to use the default (will throw if no default key is set). - * - * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#store}. - */ - public storeSecret(name: string, secret: string, keys?: string[]): Promise { - return this.secretStorage.store(name, secret, keys); - } - - /** - * Get a secret from storage. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param name - the name of the secret - * - * @returns the contents of the secret - * - * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#get}. - */ - public getSecret(name: string): Promise { - return this.secretStorage.get(name); - } - - /** - * Check if a secret is stored on the server. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param name - the name of the secret - * @returns map of key name to key info the secret is encrypted - * with, or null if it is not present or not encrypted with a trusted - * key - * - * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#isStored}. - */ - public isSecretStored(name: SecretStorageKey): Promise | null> { - return this.secretStorage.isStored(name); - } - - /** - * Request a secret from another device. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param name - the name of the secret to request - * @param devices - the devices to request the secret from - * - * @returns the secret request object - * @deprecated Not supported for Rust Cryptography. - */ - public requestSecret(name: string, devices: string[]): ISecretRequest { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.requestSecret(name, devices); - } - - /** - * Get the current default key ID for encrypting secrets. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @returns The default key ID or null if no default key ID is set - * - * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#getDefaultKeyId}. - */ - public getDefaultSecretStorageKeyId(): Promise { - return this.secretStorage.getDefaultKeyId(); - } - - /** - * Set the current default key ID for encrypting secrets. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param keyId - The new default key ID - * - * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#setDefaultKeyId}. - */ - public setDefaultSecretStorageKeyId(keyId: string): Promise { - return this.secretStorage.setDefaultKeyId(keyId); - } - - /** - * Checks that a given secret storage private key matches a given public key. - * This can be used by the getSecretStorageKey callback to verify that the - * private key it is about to supply is the one that was requested. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param privateKey - The private key - * @param expectedPublicKey - The public key - * @returns true if the key matches, otherwise false - * - * @deprecated The use of asymmetric keys for SSSS is deprecated. - * Use {@link SecretStorage.ServerSideSecretStorage#checkKey} for symmetric keys. - */ - public checkSecretStoragePrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.checkSecretStoragePrivateKey(privateKey, expectedPublicKey); - } - - /** - * Get e2e information on the device that sent an event - * - * @param event - event to be checked - * @deprecated Not supported for Rust Cryptography. - */ - public async getEventSenderDeviceInfo(event: MatrixEvent): Promise { - if (!this.crypto) { - return null; - } - return this.crypto.getEventSenderDeviceInfo(event); - } - - /** - * Check if the sender of an event is verified - * - * @param event - event to be checked - * - * @returns true if the sender of this event has been verified using - * {@link MatrixClient#setDeviceVerified}. - * - * @deprecated Not supported for Rust Cryptography. - */ - public async isEventSenderVerified(event: MatrixEvent): Promise { - const device = await this.getEventSenderDeviceInfo(event); - if (!device) { - return false; - } - return device.isVerified(); - } - - /** - * Get outgoing room key request for this event if there is one. - * @param event - The event to check for - * - * @returns A room key request, or null if there is none - * - * @deprecated Not supported for Rust Cryptography. - */ - public getOutgoingRoomKeyRequest(event: MatrixEvent): Promise { - if (!this.crypto) { - throw new Error("End-to-End encryption disabled"); - } - const wireContent = event.getWireContent(); - const requestBody: IRoomKeyRequestBody = { - session_id: wireContent.session_id, - sender_key: wireContent.sender_key, - algorithm: wireContent.algorithm, - room_id: event.getRoomId()!, - }; - if (!requestBody.session_id || !requestBody.sender_key || !requestBody.algorithm || !requestBody.room_id) { - return Promise.resolve(null); - } - return this.crypto.cryptoStore.getOutgoingRoomKeyRequest(requestBody); - } - - /** - * Cancel a room key request for this event if one is ongoing and resend the - * request. - * @param event - event of which to cancel and resend the room - * key request. - * @returns A promise that will resolve when the key request is queued - * - * @deprecated Not supported for Rust Cryptography. - */ - public cancelAndResendEventRoomKeyRequest(event: MatrixEvent): Promise { - if (!this.crypto) { - throw new Error("End-to-End encryption disabled"); - } - return event.cancelAndResendKeyRequest(this.crypto, this.getUserId()!); - } - - /** - * Enable end-to-end encryption for a room. This does not modify room state. - * Any messages sent before the returned promise resolves will be sent unencrypted. - * @param roomId - The room ID to enable encryption in. - * @param config - The encryption config for the room. - * @returns A promise that will resolve when encryption is set up. - * - * @deprecated Not supported for Rust Cryptography. To enable encryption in a room, send an `m.room.encryption` - * state event. - */ - public setRoomEncryption(roomId: string, config: IRoomEncryption): Promise { - if (!this.crypto) { - throw new Error("End-to-End encryption disabled"); - } - return this.crypto.setRoomEncryption(roomId, config); - } - - /** - * Whether encryption is enabled for a room. - * @param roomId - the room id to query. - * @returns whether encryption is enabled. - * - * @deprecated Not correctly supported for Rust Cryptography. Use {@link CryptoApi.isEncryptionEnabledInRoom} and/or - * {@link Room.hasEncryptionStateEvent}. - */ - public isRoomEncrypted(roomId: string): boolean { - const room = this.getRoom(roomId); - if (!room) { - // we don't know about this room, so can't determine if it should be - // encrypted. Let's assume not. - return false; - } - - // if there is an 'm.room.encryption' event in this room, it should be - // encrypted (independently of whether we actually support encryption) - if (room.hasEncryptionStateEvent()) { - return true; - } - - // we don't have an m.room.encrypted event, but that might be because - // the server is hiding it from us. Check the store to see if it was - // previously encrypted. - return this.crypto?.isRoomEncrypted(roomId) ?? false; - } - - /** - * Encrypts and sends a given object via Olm to-device messages to a given - * set of devices. - * - * @param userDeviceInfoArr - list of deviceInfo objects representing the devices to send to - * - * @param payload - fields to include in the encrypted payload - * - * @returns Promise which - * resolves once the message has been encrypted and sent to the given - * userDeviceMap, and returns the `{ contentMap, deviceInfoByDeviceId }` - * of the successfully sent messages. - * - * @deprecated Instead use {@link CryptoApi.encryptToDeviceMessages} followed by {@link queueToDevice}. - */ - public encryptAndSendToDevices(userDeviceInfoArr: IOlmDevice[], payload: object): Promise { - if (!this.crypto) { - throw new Error("End-to-End encryption disabled"); - } - return this.crypto.encryptAndSendToDevices(userDeviceInfoArr, payload); - } - - /** - * Forces the current outbound group session to be discarded such - * that another one will be created next time an event is sent. - * - * @param roomId - The ID of the room to discard the session for - * - * @deprecated Prefer {@link CryptoApi.forceDiscardSession | `CryptoApi.forceDiscardSession`}: - */ - public forceDiscardSession(roomId: string): void { - if (!this.cryptoBackend) { - throw new Error("End-to-End encryption disabled"); - } - this.cryptoBackend.forceDiscardSession(roomId); - } - - /** - * Get a list containing all of the room keys - * - * This should be encrypted before returning it to the user. - * - * @returns a promise which resolves to a list of session export objects - * - * @deprecated Prefer {@link CryptoApi.exportRoomKeys | `CryptoApi.exportRoomKeys`}: - * - * ```javascript - * sessionData = await client.getCrypto().exportRoomKeys(); - * ``` - */ - public exportRoomKeys(): Promise { - if (!this.cryptoBackend) { - return Promise.reject(new Error("End-to-end encryption disabled")); - } - return this.cryptoBackend.exportRoomKeys(); - } - - /** - * Import a list of room keys previously exported by exportRoomKeys - * - * @param keys - a list of session export objects - * @param opts - options object - * - * @returns a promise which resolves when the keys have been imported - * - * @deprecated Prefer {@link CryptoApi.importRoomKeys | `CryptoApi.importRoomKeys`}: - * ```javascript - * await client.getCrypto()?.importRoomKeys([..]); - * ``` - */ - public importRoomKeys(keys: IMegolmSessionData[], opts?: ImportRoomKeysOpts): Promise { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.importRoomKeys(keys, opts); - } - - /** - * Force a re-check of the local key backup status against - * what's on the server. - * - * @returns Object with backup info (as returned by - * getKeyBackupVersion) in backupInfo and - * trust information (as returned by isKeyBackupTrusted) - * in trustInfo. - * - * @deprecated Prefer {@link Crypto.CryptoApi.checkKeyBackupAndEnable}. - */ - public checkKeyBackup(): Promise { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.backupManager.checkKeyBackup(); - } - - /** - * Get information about the current key backup from the server. - * - * Performs some basic validity checks on the shape of the result, and raises an error if it is not as expected. - * - * **Note**: there is no (supported) way to distinguish between "failure to talk to the server" and "another client - * uploaded a key backup version using an algorithm I don't understand. - * - * @returns Information object from API, or null if no backup is present on the server. - * - * @deprecated Prefer {@link CryptoApi.getKeyBackupInfo}. - */ - public async getKeyBackupVersion(): Promise { - let res: IKeyBackupInfo; - try { - res = await this.http.authedRequest( - Method.Get, - "/room_keys/version", - undefined, - undefined, - { prefix: ClientPrefix.V3 }, - ); - } catch (e) { - if ((e).errcode === "M_NOT_FOUND") { - return null; - } else { - throw e; - } - } - BackupManager.checkBackupVersion(res); - return res; - } - - /** - * @param info - key backup info dict from getKeyBackupVersion() - * - * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.isKeyBackupTrusted | `CryptoApi.isKeyBackupTrusted`}. - */ - public isKeyBackupTrusted(info: IKeyBackupInfo): Promise { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.backupManager.isKeyBackupTrusted(info); - } - - /** - * @returns true if the client is configured to back up keys to - * the server, otherwise false. If we haven't completed a successful check - * of key backup status yet, returns null. - * - * @deprecated Not supported for Rust Cryptography. Prefer direct access to {@link Crypto.CryptoApi.getActiveSessionBackupVersion}: - * - * ```javascript - * let enabled = (await client.getCrypto().getActiveSessionBackupVersion()) !== null; - * ``` - */ - public getKeyBackupEnabled(): boolean | null { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.backupManager.getKeyBackupEnabled(); - } - - /** - * Enable backing up of keys, using data previously returned from - * getKeyBackupVersion. - * - * @param info - Backup information object as returned by getKeyBackupVersion - * @returns Promise which resolves when complete. - * - * @deprecated Do not call this directly. Instead call {@link Crypto.CryptoApi.checkKeyBackupAndEnable}. - */ - public enableKeyBackup(info: IKeyBackupInfo): Promise { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - - return this.crypto.backupManager.enableKeyBackup(info); - } - - /** - * Disable backing up of keys. - * - * @deprecated Not supported for Rust Cryptography. It should be unnecessary to disable key backup. - */ - public disableKeyBackup(): void { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - - this.crypto.backupManager.disableKeyBackup(); - } - - /** - * Set up the data required to create a new backup version. The backup version - * will not be created and enabled until createKeyBackupVersion is called. - * - * @param password - Passphrase string that can be entered by the user - * when restoring the backup as an alternative to entering the recovery key. - * Optional. - * - * @returns Object that can be passed to createKeyBackupVersion and - * additionally has a 'recovery_key' member with the user-facing recovery key string. - * - * @deprecated Not supported for Rust cryptography. Use {@link Crypto.CryptoApi.resetKeyBackup | `CryptoApi.resetKeyBackup`}. - */ - public async prepareKeyBackupVersion( - password?: string | Uint8Array | null, - opts: IKeyBackupPrepareOpts = { secureSecretStorage: false }, - ): Promise> { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - - // eslint-disable-next-line camelcase - const { algorithm, auth_data, recovery_key, privateKey } = - await this.crypto.backupManager.prepareKeyBackupVersion(password); - - if (opts.secureSecretStorage) { - await this.secretStorage.store("m.megolm_backup.v1", encodeBase64(privateKey)); - this.logger.info("Key backup private key stored in secret storage"); - } - - return { - algorithm, - /* eslint-disable camelcase */ - auth_data, - recovery_key, - /* eslint-enable camelcase */ - }; - } - - /** - * Check whether the key backup private key is stored in secret storage. - * @returns map of key name to key info the secret is - * encrypted with, or null if it is not present or not encrypted with a - * trusted key - */ - public isKeyBackupKeyStored(): Promise | null> { - return Promise.resolve(this.secretStorage.isStored("m.megolm_backup.v1")); - } - - /** - * Create a new key backup version and enable it, using the information return - * from prepareKeyBackupVersion. - * - * @param info - Info object from prepareKeyBackupVersion - * @returns Object with 'version' param indicating the version created - * - * @deprecated Use {@link Crypto.CryptoApi.resetKeyBackup | `CryptoApi.resetKeyBackup`}. - */ - public async createKeyBackupVersion(info: IKeyBackupInfo): Promise { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - - await this.crypto.backupManager.createKeyBackupVersion(info); - - const data = { - algorithm: info.algorithm, - auth_data: info.auth_data, - }; - - // Sign the backup auth data with the device key for backwards compat with - // older devices with cross-signing. This can probably go away very soon in - // favour of just signing with the cross-singing master key. - // XXX: Private member access - await this.crypto.signObject(data.auth_data); - - if ( - this.cryptoCallbacks.getCrossSigningKey && - // XXX: Private member access - this.crypto.crossSigningInfo.getId() - ) { - // now also sign the auth data with the cross-signing master key - // we check for the callback explicitly here because we still want to be able - // to create an un-cross-signed key backup if there is a cross-signing key but - // no callback supplied. - // XXX: Private member access - await this.crypto.crossSigningInfo.signObject(data.auth_data, "master"); - } - - const res = await this.http.authedRequest(Method.Post, "/room_keys/version", undefined, data); - - // We could assume everything's okay and enable directly, but this ensures - // we run the same signature verification that will be used for future - // sessions. - await this.checkKeyBackup(); - if (!this.getKeyBackupEnabled()) { - this.logger.error("Key backup not usable even though we just created it"); - } - - return res; - } - - /** - * @deprecated Use {@link Crypto.CryptoApi.deleteKeyBackupVersion | `CryptoApi.deleteKeyBackupVersion`}. - */ - public async deleteKeyBackupVersion(version: string): Promise { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - - await this.cryptoBackend.deleteKeyBackupVersion(version); - } - - private makeKeyBackupPath(roomId?: string, sessionId?: string, version?: string): IKeyBackupPath { - let path: string; - if (sessionId !== undefined) { - path = utils.encodeUri("/room_keys/keys/$roomId/$sessionId", { - $roomId: roomId!, - $sessionId: sessionId, - }); - } else if (roomId !== undefined) { - path = utils.encodeUri("/room_keys/keys/$roomId", { - $roomId: roomId, - }); - } else { - path = "/room_keys/keys"; - } - const queryData = version === undefined ? undefined : { version }; - return { path, queryData }; - } - - /** - * Back up session keys to the homeserver. - * @param roomId - ID of the room that the keys are for Optional. - * @param sessionId - ID of the session that the keys are for Optional. - * @param version - backup version Optional. - * @param data - Object keys to send - * @returns a promise that will resolve when the keys - * are uploaded - * - * @deprecated Not supported for Rust Cryptography. - */ - public sendKeyBackup( - roomId: undefined, - sessionId: undefined, - version: string | undefined, - data: IKeyBackup, - ): Promise; - public sendKeyBackup( - roomId: string, - sessionId: undefined, - version: string | undefined, - data: IKeyBackup, - ): Promise; - public sendKeyBackup( - roomId: string, - sessionId: string, - version: string | undefined, - data: IKeyBackup, - ): Promise; - public async sendKeyBackup( - roomId: string | undefined, - sessionId: string | undefined, - version: string | undefined, - data: IKeyBackup, - ): Promise { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - - const path = this.makeKeyBackupPath(roomId!, sessionId!, version); - await this.http.authedRequest(Method.Put, path.path, path.queryData, data, { prefix: ClientPrefix.V3 }); - } - - /** - * Marks all group sessions as needing to be backed up and schedules them to - * upload in the background as soon as possible. - * - * @deprecated Not supported for Rust Cryptography. This is done automatically as part of - * {@link CryptoApi.resetKeyBackup}, so there is probably no need to call this manually. - */ - public async scheduleAllGroupSessionsForBackup(): Promise { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - - await this.crypto.backupManager.scheduleAllGroupSessionsForBackup(); - } - - /** - * Marks all group sessions as needing to be backed up without scheduling - * them to upload in the background. - * - * (This is done automatically as part of {@link CryptoApi.resetKeyBackup}, - * so there is probably no need to call this manually.) - * - * @returns Promise which resolves to the number of sessions requiring a backup. - * @deprecated Not supported for Rust Cryptography. + * Return the provided scheduler, if any. + * @returns The scheduler or undefined */ - public flagAllGroupSessionsForBackup(): Promise { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - - return this.crypto.backupManager.flagAllGroupSessionsForBackup(); + public getScheduler(): MatrixScheduler | undefined { + return this.scheduler; } /** - * Return true if recovery key is valid. - * Try to decode the recovery key and check if it's successful. - * @param recoveryKey - * @deprecated Use {@link decodeRecoveryKey} directly + * Retry a backed off syncing request immediately. This should only be used when + * the user explicitly attempts to retry their lost connection. + * Will also retry any outbound to-device messages currently in the queue to be sent + * (retries of regular outgoing events are handled separately, per-event). + * @returns True if this resulted in a request being retried. */ - public isValidRecoveryKey(recoveryKey: string): boolean { - try { - decodeRecoveryKey(recoveryKey); - return true; - } catch { - return false; - } + public retryImmediately(): boolean { + // don't await for this promise: we just want to kick it off + this.toDeviceMessageQueue.sendQueue(); + return this.syncApi?.retryImmediately() ?? false; } /** - * Get the raw key for a key backup from the password - * Used when migrating key backups into SSSS - * - * The cross-signing API is currently UNSTABLE and may change without notice. + * Return the global notification EventTimelineSet, if any * - * @param password - Passphrase - * @param backupInfo - Backup metadata from `checkKeyBackup` - * @returns key backup key - * @deprecated Deriving a backup key from a passphrase is not part of the matrix spec. Instead, a random key is generated and stored/shared via 4S. + * @returns the globl notification EventTimelineSet */ - public keyBackupKeyFromPassword(password: string, backupInfo: IKeyBackupInfo): Promise { - return keyFromAuthData(backupInfo.auth_data, password); + public getNotifTimelineSet(): EventTimelineSet | null { + return this.notifTimelineSet; } /** - * Get the raw key for a key backup from the recovery key - * Used when migrating key backups into SSSS - * - * The cross-signing API is currently UNSTABLE and may change without notice. + * Set the global notification EventTimelineSet * - * @param recoveryKey - The recovery key - * @returns key backup key - * @deprecated Use {@link decodeRecoveryKey} directly */ - public keyBackupKeyFromRecoveryKey(recoveryKey: string): Uint8Array { - return decodeRecoveryKey(recoveryKey); + public setNotifTimelineSet(set: EventTimelineSet): void { + this.notifTimelineSet = set; } /** - * Restore from an existing key backup via a passphrase. - * - * @param password - Passphrase - * @param targetRoomId - Room ID to target a specific room. - * Restores all rooms if omitted. - * @param targetSessionId - Session ID to target a specific session. - * Restores all sessions if omitted. - * @param backupInfo - Backup metadata from `getKeyBackupVersion` or `checkKeyBackup`.`backupInfo` - * @param opts - Optional params such as callbacks - * @returns Status of restoration with `total` and `imported` - * key counts. + * Gets the cached capabilities of the homeserver, returning cached ones if available. + * If there are no cached capabilities and none can be fetched, throw an exception. * - * @deprecated Prefer {@link CryptoApi.restoreKeyBackupWithPassphrase | `CryptoApi.restoreKeyBackupWithPassphrase`}. - */ - public async restoreKeyBackupWithPassword( - password: string, - targetRoomId: undefined, - targetSessionId: undefined, - backupInfo: IKeyBackupInfo, - opts: IKeyBackupRestoreOpts, - ): Promise; - /** - * @deprecated Prefer {@link CryptoApi.restoreKeyBackupWithPassphrase | `CryptoApi.restoreKeyBackupWithPassphrase`}. - */ - public async restoreKeyBackupWithPassword( - password: string, - targetRoomId: string, - targetSessionId: undefined, - backupInfo: IKeyBackupInfo, - opts: IKeyBackupRestoreOpts, - ): Promise; - /** - * @deprecated Prefer {@link CryptoApi.restoreKeyBackupWithPassphrase | `CryptoApi.restoreKeyBackupWithPassphrase`}. - */ - public async restoreKeyBackupWithPassword( - password: string, - targetRoomId: string, - targetSessionId: string, - backupInfo: IKeyBackupInfo, - opts: IKeyBackupRestoreOpts, - ): Promise; - /** - * @deprecated Prefer {@link CryptoApi.restoreKeyBackupWithPassphrase | `CryptoApi.restoreKeyBackupWithPassphrase`}. + * @returns Promise resolving with The capabilities of the homeserver */ - public async restoreKeyBackupWithPassword( - password: string, - targetRoomId: string | undefined, - targetSessionId: string | undefined, - backupInfo: IKeyBackupInfo, - opts: IKeyBackupRestoreOpts, - ): Promise { - const privKey = await keyFromAuthData(backupInfo.auth_data, password); - return this.restoreKeyBackup(privKey, targetRoomId!, targetSessionId!, backupInfo, opts); - } - - /** - * Restore from an existing key backup via a private key stored in secret - * storage. - * - * @param backupInfo - Backup metadata from `checkKeyBackup` - * @param targetRoomId - Room ID to target a specific room. - * Restores all rooms if omitted. - * @param targetSessionId - Session ID to target a specific session. - * Restores all sessions if omitted. - * @param opts - Optional params such as callbacks - * @returns Status of restoration with `total` and `imported` - * key counts. - * - * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}. - */ - public async restoreKeyBackupWithSecretStorage( - backupInfo: IKeyBackupInfo, - targetRoomId?: string, - targetSessionId?: string, - opts?: IKeyBackupRestoreOpts, - ): Promise { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - const storedKey = await this.secretStorage.get("m.megolm_backup.v1"); - - // ensure that the key is in the right format. If not, fix the key and - // store the fixed version - const fixedKey = fixBackupKey(storedKey); - if (fixedKey) { - const keys = await this.secretStorage.getKey(); - await this.secretStorage.store("m.megolm_backup.v1", fixedKey, [keys![0]]); - } - - const privKey = decodeBase64(fixedKey || storedKey!); - return this.restoreKeyBackup(privKey, targetRoomId!, targetSessionId!, backupInfo, opts); + public async getCapabilities(): Promise { + const caps = this.serverCapabilitiesService.getCachedCapabilities(); + if (caps) return caps; + return this.serverCapabilitiesService.fetchCapabilities(); } /** - * Restore from an existing key backup via an encoded recovery key. - * - * @param recoveryKey - Encoded recovery key - * @param targetRoomId - Room ID to target a specific room. - * Restores all rooms if omitted. - * @param targetSessionId - Session ID to target a specific session. - * Restores all sessions if omitted. - * @param backupInfo - Backup metadata from `checkKeyBackup` - * @param opts - Optional params such as callbacks - - * @returns Status of restoration with `total` and `imported` - * key counts. + * Gets the cached capabilities of the homeserver. If none have been fetched yet, + * return undefined. * - * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}. - */ - public restoreKeyBackupWithRecoveryKey( - recoveryKey: string, - targetRoomId: undefined, - targetSessionId: undefined, - backupInfo: IKeyBackupInfo, - opts?: IKeyBackupRestoreOpts, - ): Promise; - /** - * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}. - */ - public restoreKeyBackupWithRecoveryKey( - recoveryKey: string, - targetRoomId: string, - targetSessionId: undefined, - backupInfo: IKeyBackupInfo, - opts?: IKeyBackupRestoreOpts, - ): Promise; - /** - * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}. - */ - public restoreKeyBackupWithRecoveryKey( - recoveryKey: string, - targetRoomId: string, - targetSessionId: string, - backupInfo: IKeyBackupInfo, - opts?: IKeyBackupRestoreOpts, - ): Promise; - /** - * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}. + * @returns The capabilities of the homeserver */ - public restoreKeyBackupWithRecoveryKey( - recoveryKey: string, - targetRoomId: string | undefined, - targetSessionId: string | undefined, - backupInfo: IKeyBackupInfo, - opts?: IKeyBackupRestoreOpts, - ): Promise { - const privKey = decodeRecoveryKey(recoveryKey); - return this.restoreKeyBackup(privKey, targetRoomId!, targetSessionId!, backupInfo, opts); + public getCachedCapabilities(): Capabilities | undefined { + return this.serverCapabilitiesService.getCachedCapabilities(); } /** - * Restore from an existing key backup via a private key stored locally - * @param targetRoomId - * @param targetSessionId - * @param backupInfo - * @param opts + * Fetches the latest capabilities from the homeserver, ignoring any cached + * versions. The newly returned version is cached. * - * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}. - */ - public async restoreKeyBackupWithCache( - targetRoomId: undefined, - targetSessionId: undefined, - backupInfo: IKeyBackupInfo, - opts?: IKeyBackupRestoreOpts, - ): Promise; - /** - * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}. + * @returns A promise which resolves to the capabilities of the homeserver */ - public async restoreKeyBackupWithCache( - targetRoomId: string, - targetSessionId: undefined, - backupInfo: IKeyBackupInfo, - opts?: IKeyBackupRestoreOpts, - ): Promise; + public fetchCapabilities(): Promise { + return this.serverCapabilitiesService.fetchCapabilities(); + } + /** - * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}. - */ - public async restoreKeyBackupWithCache( - targetRoomId: string, - targetSessionId: string, - backupInfo: IKeyBackupInfo, - opts?: IKeyBackupRestoreOpts, - ): Promise; - /** - * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}. + * Initialise support for end-to-end encryption in this client, using the rust matrix-sdk-crypto. + * + * **WARNING**: the cryptography stack is not thread-safe. Having multiple `MatrixClient` instances connected to + * the same Indexed DB will cause data corruption and decryption failures. The application layer is responsible for + * ensuring that only one `MatrixClient` issue is instantiated at a time. + * + * @param args.useIndexedDB - True to use an indexeddb store, false to use an in-memory store. Defaults to 'true'. + * @param args.storageKey - A key with which to encrypt the indexeddb store. If provided, it must be exactly + * 32 bytes of data, and must be the same each time the client is initialised for a given device. + * If both this and `storagePassword` are unspecified, the store will be unencrypted. + * @param args.storagePassword - An alternative to `storageKey`. A password which will be used to derive a key to + * encrypt the store with. Deriving a key from a password is (deliberately) a slow operation, so prefer + * to pass a `storageKey` directly where possible. + * + * @returns a Promise which will resolve when the crypto layer has been + * successfully initialised. */ - public async restoreKeyBackupWithCache( - targetRoomId: string | undefined, - targetSessionId: string | undefined, - backupInfo: IKeyBackupInfo, - opts?: IKeyBackupRestoreOpts, - ): Promise { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - const privKey = await this.cryptoBackend.getSessionBackupPrivateKey(); - if (!privKey) { - throw new Error("Couldn't get key"); - } - return this.restoreKeyBackup(privKey, targetRoomId!, targetSessionId!, backupInfo, opts); - } - - private async restoreKeyBackup( - privKey: Uint8Array, - targetRoomId: undefined, - targetSessionId: undefined, - backupInfo: IKeyBackupInfo, - opts?: IKeyBackupRestoreOpts, - ): Promise; - private async restoreKeyBackup( - privKey: Uint8Array, - targetRoomId: string, - targetSessionId: undefined, - backupInfo: IKeyBackupInfo, - opts?: IKeyBackupRestoreOpts, - ): Promise; - private async restoreKeyBackup( - privKey: Uint8Array, - targetRoomId: string, - targetSessionId: string, - backupInfo: IKeyBackupInfo, - opts?: IKeyBackupRestoreOpts, - ): Promise; - private async restoreKeyBackup( - privKey: Uint8Array, - targetRoomId: string | undefined, - targetSessionId: string | undefined, - backupInfo: IKeyBackupInfo, - opts?: IKeyBackupRestoreOpts, - ): Promise { - const cacheCompleteCallback = opts?.cacheCompleteCallback; - const progressCallback = opts?.progressCallback; - - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); + public async initRustCrypto( + args: { + useIndexedDB?: boolean; + storageKey?: Uint8Array; + storagePassword?: string; + } = {}, + ): Promise { + if (this.cryptoBackend) { + this.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient"); + return; } - if (!backupInfo.version) { - throw new Error("Backup version must be defined"); + const userId = this.getUserId(); + if (userId === null) { + throw new Error( + `Cannot enable encryption on MatrixClient with unknown userId: ` + + `ensure userId is passed in createClient().`, + ); + } + const deviceId = this.getDeviceId(); + if (deviceId === null) { + throw new Error( + `Cannot enable encryption on MatrixClient with unknown deviceId: ` + + `ensure deviceId is passed in createClient().`, + ); } - const backupVersion = backupInfo.version!; - - let totalKeyCount = 0; - let totalFailures = 0; - let totalImported = 0; - - const path = this.makeKeyBackupPath(targetRoomId, targetSessionId, backupVersion); - - const backupDecryptor = await this.cryptoBackend.getBackupDecryptor(backupInfo, privKey); - - const untrusted = !backupDecryptor.sourceTrusted; - - try { - if (!(privKey instanceof Uint8Array)) { - // eslint-disable-next-line @typescript-eslint/no-base-to-string - throw new Error(`restoreKeyBackup expects Uint8Array, got ${privKey}`); - } - // Cache the key, if possible. - // This is async. - this.cryptoBackend - .storeSessionBackupPrivateKey(privKey, backupVersion) - .catch((e) => { - this.logger.warn("Error caching session backup key:", e); - }) - .then(cacheCompleteCallback); - if (progressCallback) { - progressCallback({ - stage: "fetch", - }); - } + // importing rust-crypto will download the webassembly, so we delay it until we know it will be + // needed. + this.logger.debug("Downloading Rust crypto library"); + const RustCrypto = await import("./rust-crypto/index.ts"); - const res = await this.http.authedRequest( - Method.Get, - path.path, - path.queryData, - undefined, - { prefix: ClientPrefix.V3 }, - ); + const rustCrypto = await RustCrypto.initRustCrypto({ + logger: this.logger, + http: this.http, + userId: userId, + deviceId: deviceId, + secretStorage: this.secretStorage, + cryptoCallbacks: this.cryptoCallbacks, + storePrefix: args.useIndexedDB === false ? null : RUST_SDK_STORE_PREFIX, + storeKey: args.storageKey, + storePassphrase: args.storagePassword, - // We have finished fetching the backup, go to next step - if (progressCallback) { - progressCallback({ - stage: "load_keys", - }); - } + legacyCryptoStore: this.legacyCryptoStore, + legacyPickleKey: this.legacyPickleKey ?? "DEFAULT_KEY", + legacyMigrationProgressListener: (progress: number, total: number): void => { + this.emit(CryptoEvent.LegacyCryptoStoreMigrationProgress, progress, total); + }, + }); - if ((res as IRoomsKeysResponse).rooms) { - // We have a full backup here, it can get quite big, so we need to decrypt and import it in chunks. - - // Get the total count as a first pass - totalKeyCount = this.getTotalKeyCount(res as IRoomsKeysResponse); - // Now decrypt and import the keys in chunks - await this.handleDecryptionOfAFullBackup( - res as IRoomsKeysResponse, - backupDecryptor, - 200, - async (chunk) => { - // We have a chunk of decrypted keys: import them - try { - const backupVersion = backupInfo.version!; - await this.cryptoBackend!.importBackedUpRoomKeys(chunk, backupVersion, { - untrusted, - }); - totalImported += chunk.length; - } catch (e) { - totalFailures += chunk.length; - // We failed to import some keys, but we should still try to import the rest? - // Log the error and continue - logger.error("Error importing keys from backup", e); - } + rustCrypto.setSupportedVerificationMethods(this.verificationMethods); - if (progressCallback) { - progressCallback({ - total: totalKeyCount, - successes: totalImported, - stage: "load_keys", - failures: totalFailures, - }); - } - }, - ); - } else if ((res as IRoomKeysResponse).sessions) { - // For now we don't chunk for a single room backup, but we could in the future. - // Currently it is not used by the application. - const sessions = (res as IRoomKeysResponse).sessions; - totalKeyCount = Object.keys(sessions).length; - const keys = await backupDecryptor.decryptSessions(sessions); - for (const k of keys) { - k.room_id = targetRoomId!; - } - await this.cryptoBackend.importBackedUpRoomKeys(keys, backupVersion, { - progressCallback, - untrusted, - }); - totalImported = keys.length; - } else { - totalKeyCount = 1; - try { - const [key] = await backupDecryptor.decryptSessions({ - [targetSessionId!]: res as IKeyBackupSession, - }); - key.room_id = targetRoomId!; - key.session_id = targetSessionId!; + this.cryptoBackend = rustCrypto; - await this.cryptoBackend.importBackedUpRoomKeys([key], backupVersion, { - progressCallback, - untrusted, - }); - totalImported = 1; - } catch (e) { - this.logger.debug("Failed to decrypt megolm session from backup", e); - } - } - } finally { - backupDecryptor.free(); - } + // attach the event listeners needed by RustCrypto + this.on(RoomMemberEvent.Membership, rustCrypto.onRoomMembership.bind(rustCrypto)); + this.on(ClientEvent.Event, (event) => { + rustCrypto.onLiveEventFromSync(event); + }); - /// in case entering the passphrase would add a new signature? - await this.cryptoBackend.checkKeyBackupAndEnable(); + // re-emit the events emitted by the crypto impl + this.reEmitter.reEmit(rustCrypto, [ + CryptoEvent.VerificationRequestReceived, + CryptoEvent.UserTrustStatusChanged, + CryptoEvent.KeyBackupStatus, + CryptoEvent.KeyBackupSessionsRemaining, + CryptoEvent.KeyBackupFailed, + CryptoEvent.KeyBackupDecryptionKeyCached, + CryptoEvent.KeysChanged, + CryptoEvent.DevicesUpdated, + CryptoEvent.WillUpdateDevices, + ]); + } - return { total: totalKeyCount, imported: totalImported }; + /** + * Access the server-side secret storage API for this client. + */ + public get secretStorage(): ServerSideSecretStorage { + return this._secretStorage; } /** - * This method calculates the total number of keys present in the response of a `/room_keys/keys` call. - * - * @param res - The response from the server containing the keys to be counted. + * Access the crypto API for this client. * - * @returns The total number of keys in the backup. + * If end-to-end encryption has been enabled for this client (via {@link initRustCrypto}), + * returns an object giving access to the crypto API. Otherwise, returns `undefined`. */ - private getTotalKeyCount(res: IRoomsKeysResponse): number { - const rooms = res.rooms; - let totalKeyCount = 0; - for (const roomData of Object.values(rooms)) { - if (!roomData.sessions) continue; - totalKeyCount += Object.keys(roomData.sessions).length; - } - return totalKeyCount; + public getCrypto(): CryptoApi | undefined { + return this.cryptoBackend; } /** - * This method handles the decryption of a full backup, i.e a call to `/room_keys/keys`. - * It will decrypt the keys in chunks and call the `block` callback for each chunk. - * - * @param res - The response from the server containing the keys to be decrypted. - * @param backupDecryptor - An instance of the BackupDecryptor class used to decrypt the keys. - * @param chunkSize - The size of the chunks to be processed at a time. - * @param block - A callback function that is called for each chunk of keys. + * Whether encryption is enabled for a room. + * @param roomId - the room id to query. + * @returns whether encryption is enabled. * - * @returns A promise that resolves when the decryption is complete. + * @deprecated Not correctly supported for Rust Cryptography. Use {@link CryptoApi.isEncryptionEnabledInRoom} and/or + * {@link Room.hasEncryptionStateEvent}. */ - private async handleDecryptionOfAFullBackup( - res: IRoomsKeysResponse, - backupDecryptor: BackupDecryptor, - chunkSize: number, - block: (chunk: IMegolmSessionData[]) => Promise, - ): Promise { - const rooms = (res as IRoomsKeysResponse).rooms; - - let groupChunkCount = 0; - let chunkGroupByRoom: Map = new Map(); - - const handleChunkCallback = async (roomChunks: Map): Promise => { - const currentChunk: IMegolmSessionData[] = []; - for (const roomId of roomChunks.keys()) { - const decryptedSessions = await backupDecryptor.decryptSessions(roomChunks.get(roomId)!); - for (const sessionId in decryptedSessions) { - const k = decryptedSessions[sessionId]; - k.room_id = roomId; - currentChunk.push(k); - } - } - await block(currentChunk); - }; - - for (const [roomId, roomData] of Object.entries(rooms)) { - if (!roomData.sessions) continue; - - chunkGroupByRoom.set(roomId, {}); - - for (const [sessionId, session] of Object.entries(roomData.sessions)) { - const sessionsForRoom = chunkGroupByRoom.get(roomId)!; - sessionsForRoom[sessionId] = session; - groupChunkCount += 1; - if (groupChunkCount >= chunkSize) { - // We have enough chunks to decrypt - await handleChunkCallback(chunkGroupByRoom); - chunkGroupByRoom = new Map(); - // There might be remaining keys for that room, so add back an entry for the current room. - chunkGroupByRoom.set(roomId, {}); - groupChunkCount = 0; - } - } + public isRoomEncrypted(roomId: string): boolean { + const room = this.getRoom(roomId); + if (!room) { + // we don't know about this room, so can't determine if it should be + // encrypted. Let's assume not. + return false; } - // Handle remaining chunk if needed - if (groupChunkCount > 0) { - await handleChunkCallback(chunkGroupByRoom); + // if there is an 'm.room.encryption' event in this room, it should be + // encrypted (independently of whether we actually support encryption) + return room.hasEncryptionStateEvent(); + } + + /** + * Check whether the key backup private key is stored in secret storage. + * @returns map of key name to key info the secret is + * encrypted with, or null if it is not present or not encrypted with a + * trusted key + */ + public isKeyBackupKeyStored(): Promise | null> { + return Promise.resolve(this.secretStorage.isStored("m.megolm_backup.v1")); + } + + private makeKeyBackupPath(roomId?: string, sessionId?: string, version?: string): IKeyBackupPath { + let path: string; + if (sessionId !== undefined) { + path = utils.encodeUri("/room_keys/keys/$roomId/$sessionId", { + $roomId: roomId!, + $sessionId: sessionId, + }); + } else if (roomId !== undefined) { + path = utils.encodeUri("/room_keys/keys/$roomId", { + $roomId: roomId, + }); + } else { + path = "/room_keys/keys"; } + const queryData = version === undefined ? undefined : { version }; + return { path, queryData }; } public deleteKeysFromBackup(roomId: undefined, sessionId: undefined, version?: string): Promise; @@ -7898,17 +5860,6 @@ export class MatrixClient extends TypedEventEmitterThis * method is experimental and may change. @@ -7924,7 +5875,7 @@ export class MatrixClient extends TypedEventEmitter { - if (event.shouldAttemptDecryption() && this.isCryptoEnabled()) { + if (event.shouldAttemptDecryption() && this.getCrypto()) { event.attemptDecryption(this.cryptoBackend!, options); } @@ -8269,17 +6220,6 @@ export class MatrixClient extends TypedEventEmitter { - if (this.crypto?.backupManager?.getKeyBackupEnabled()) { - try { - while ((await this.crypto.backupManager.backupPendingKeys(200)) > 0); - } catch (err) { - this.logger.error( - "Key backup request failed when logging out. Some keys may be missing from backup", - err, - ); - } - } - if (stopClient) { this.stopClient(); this.http.abort();