matrix-js-sdk

    Interface CryptoBackendInternal

    Common interface for the crypto implementations

    interface CryptoBackend {
        globalBlacklistUnverifiedDevices: boolean;
        globalErrorOnUnknownDevices: boolean;
        bootstrapCrossSigning(opts: BootstrapCrossSigningOpts): Promise<void>;
        bootstrapSecretStorage(opts: CreateSecretStorageOpts): Promise<void>;
        checkKeyBackupAndEnable(): Promise<null | KeyBackupCheck>;
        createRecoveryKeyFromPassphrase(
            password?: string,
        ): Promise<GeneratedSecretStorageKey>;
        crossSignDevice(deviceId: string): Promise<void>;
        decryptEvent(event: MatrixEvent): Promise<IEventDecryptionResult>;
        deleteKeyBackupVersion(version: string): Promise<void>;
        disableKeyStorage(): Promise<void>;
        encryptEvent(event: MatrixEvent, room: Room): Promise<void>;
        encryptToDeviceMessages(
            eventType: string,
            devices: { deviceId: string; userId: string }[],
            payload: ToDevicePayload,
        ): Promise<ToDeviceBatch>;
        exportRoomKeys(): Promise<IMegolmSessionData[]>;
        exportRoomKeysAsJson(): Promise<string>;
        exportSecretsBundle(): Promise<
            {
                backup?: { algorithm: string; backup_version: string; key: string };
                cross_signing: {
                    master_key: string;
                    self_signing_key: string;
                    user_signing_key: string;
                };
            },
        >;
        findVerificationRequestDMInProgress(
            roomId: string,
        ): undefined | VerificationRequest;
        findVerificationRequestDMInProgress(
            roomId: string,
            userId?: string,
        ): undefined | VerificationRequest;
        forceDiscardSession(roomId: string): Promise<void>;
        getActiveSessionBackupVersion(): Promise<null | string>;
        getBackupDecryptor(
            backupInfo: KeyBackupInfo,
            privKey: Uint8Array,
        ): Promise<BackupDecryptor>;
        getCrossSigningKeyId(type?: CrossSigningKey): Promise<null | string>;
        getCrossSigningStatus(): Promise<CrossSigningStatus>;
        getDeviceVerificationStatus(
            userId: string,
            deviceId: string,
        ): Promise<null | DeviceVerificationStatus>;
        getEncryptionInfoForEvent(
            event: MatrixEvent,
        ): Promise<null | EventEncryptionInfo>;
        getKeyBackupInfo(): Promise<null | KeyBackupInfo>;
        getOwnDeviceKeys(): Promise<OwnDeviceKeys>;
        getSessionBackupPrivateKey(): Promise<null | Uint8Array<ArrayBufferLike>>;
        getTrustCrossSignedDevices(): boolean;
        getUserDeviceInfo(
            userIds: string[],
            downloadUncached?: boolean,
        ): Promise<DeviceMap>;
        getUserVerificationStatus(userId: string): Promise<UserVerificationStatus>;
        getVerificationRequestsToDeviceInProgress(
            userId: string,
        ): VerificationRequest[];
        getVersion(): string;
        importBackedUpRoomKeys(
            keys: IMegolmSessionData[],
            backupVersion: string,
            opts?: ImportRoomKeysOpts,
        ): Promise<void>;
        importRoomKeys(
            keys: IMegolmSessionData[],
            opts?: ImportRoomKeysOpts,
        ): Promise<void>;
        importRoomKeysAsJson(
            keys: string,
            opts?: ImportRoomKeysOpts,
        ): Promise<void>;
        importSecretsBundle(
            secrets: {
                backup?: { algorithm: string; backup_version: string; key: string };
                cross_signing: {
                    master_key: string;
                    self_signing_key: string;
                    user_signing_key: string;
                };
            },
        ): Promise<void>;
        isCrossSigningReady(): Promise<boolean>;
        isDehydrationSupported(): Promise<boolean>;
        isEncryptionEnabledInRoom(roomId: string): Promise<boolean>;
        isKeyBackupTrusted(info: KeyBackupInfo): Promise<BackupTrustInfo>;
        isSecretStorageReady(): Promise<boolean>;
        loadSessionBackupPrivateKeyFromSecretStorage(): Promise<void>;
        markAllTrackedUsersAsDirty(): Promise<void>;
        onCryptoEvent(room: Room, event: MatrixEvent): Promise<void>;
        onSyncCompleted(syncState: OnSyncCompletedData): void;
        pinCurrentUserIdentity(userId: string): Promise<void>;
        prepareToEncrypt(room: Room): void;
        preprocessToDeviceMessages(
            events: IToDeviceEvent[],
        ): Promise<IToDeviceEvent[]>;
        processDeviceLists(deviceLists: IDeviceLists): Promise<void>;
        processKeyCounts(
            oneTimeKeysCounts?: Record<string, number>,
            unusedFallbackKeys?: string[],
        ): Promise<void>;
        requestDeviceVerification(
            userId: string,
            deviceId: string,
        ): Promise<VerificationRequest>;
        requestOwnUserVerification(): Promise<VerificationRequest>;
        requestVerificationDM(
            userId: string,
            roomId: string,
        ): Promise<VerificationRequest>;
        resetEncryption(
            authUploadDeviceSigningKeys: UIAuthCallback<void>,
        ): Promise<void>;
        resetKeyBackup(): Promise<void>;
        restoreKeyBackup(
            opts?: KeyBackupRestoreOpts,
        ): Promise<KeyBackupRestoreResult>;
        restoreKeyBackupWithPassphrase(
            passphrase: string,
            opts?: KeyBackupRestoreOpts,
        ): Promise<KeyBackupRestoreResult>;
        setDeviceIsolationMode(isolationMode: DeviceIsolationMode): void;
        setDeviceVerified(
            userId: string,
            deviceId: string,
            verified?: boolean,
        ): Promise<void>;
        setTrustCrossSignedDevices(val: boolean): void;
        startDehydration(opts?: boolean | StartDehydrationOpts): Promise<void>;
        stop(): void;
        storeSessionBackupPrivateKey(key: Uint8Array): Promise<void>;
        storeSessionBackupPrivateKey(
            key: Uint8Array,
            version: string,
        ): Promise<void>;
        userHasCrossSigningKeys(
            userId?: string,
            downloadUncached?: boolean,
        ): Promise<boolean>;
        withdrawVerificationRequirement(userId: string): Promise<void>;
    }

    Hierarchy (View Summary, Expand)

    Index

    Properties

    globalBlacklistUnverifiedDevices: boolean

    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.

    If true, all unverified devices will be blacklisted by default

    globalErrorOnUnknownDevices: boolean

    Whether sendMessage in a room with unknown and unverified devices should throw an error and not send the message. This has 'Global' for symmetry with setGlobalBlacklistUnverifiedDevices but there is currently no room-level equivalent for this setting.

    This has no effect in Rust Crypto; it exists only for the sake of the accessors in MatrixClient.

    Methods

    • 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)
      • publishes the public keys to the server if they are not already published
      • stores the private keys in secret storage if secret storage is set up.

      Parameters

      Returns Promise<void>

    • Create a recovery key (ie, a key suitable for use with server-side secret storage).

      The key can either be based on a user-supplied passphrase, or just created randomly.

      Parameters

      • Optionalpassword: string

        Optional passphrase string to use to derive the key, which can later be entered by the user as an alternative to entering the recovery key itself. If omitted, a key is generated randomly.

      Returns Promise<GeneratedSecretStorageKey>

      Object including recovery key and server upload parameters. The private key should be disposed of after displaying to the use.

    • Cross-sign one of our own devices.

      This will create a signature for the device using our self-signing key, and publish that signature. Cross-signing a device indicates, to our other devices and to other users, that we have verified that it really belongs to us.

      Requires that cross-signing has been set up on this device (normally by calling bootstrapCrossSigning).

      Note: Do not call this unless you have verified, somehow, that the device is genuine!

      Parameters

      • deviceId: string

        ID of the device to be signed.

      Returns Promise<void>

    • Disables server-side key storage and deletes server-side backups.

      • Deletes the current key backup version, if any (but not any previous versions).
      • Disables 4S, deleting the info for the default key, the default key pointer itself and any known 4S data (cross-signing keys and the megolm key backup key).
      • Deletes any dehydrated devices.
      • Sets the "m.org.matrix.custom.backup_disabled" account data flag to indicate that the user has disabled backups.

      Returns Promise<void>

    • Get a JSON list containing all of the room keys

      This should be encrypted before returning it to the user.

      Returns Promise<string>

      a promise which resolves to a JSON string encoding a list of session export objects, each of which is an IMegolmSessionData

    • Export secrets bundle for transmitting to another device as part of OIDC QR login

      Returns Promise<
          {
              backup?: { algorithm: string; backup_version: string; key: string };
              cross_signing: {
                  master_key: string;
                  self_signing_key: string;
                  user_signing_key: string;
              };
          },
      >

    • Discard any existing megolm session for the given room.

      This will ensure that a new session is created on the next call to prepareToEncrypt, or the next time a message is sent.

      This should not normally be necessary: it should only be used as a debugging tool if there has been a problem with encryption.

      Parameters

      • roomId: string

        the room to discard sessions for

      Returns Promise<void>

    • Get the ID of one of the user's cross-signing keys, if both private and matching public parts of that key are available (ie. cached in the local crypto store).

      The public part may not be available if a /keys/query request has not yet been performed, or if the device that created the keys failed to publish them.

      If either part of the keypair is not available, this will return null.

      Parameters

      • Optionaltype: CrossSigningKey

        The type of key to get the ID of. One of CrossSigningKey.Master, CrossSigningKey.SelfSigning, or CrossSigningKey.UserSigning. Defaults to CrossSigningKey.Master.

      Returns Promise<null | string>

      If cross-signing has been initialised on this device, the ID of the given key. Otherwise, null

    • Return the details of the latest backup on the server, when we last checked.

      This normally returns a cached value, but if we haven't yet made a request to the server, it will fire one off. It will always return the details of the active backup if key backup is enabled.

      Return null if there is no backup.

      Returns Promise<null | KeyBackupInfo>

      the key backup information

    • Get the device information for the given list of users.

      For any users whose device lists are cached (due to sharing an encrypted room with the user), the cached device data is returned.

      If there are uncached users, and the downloadUncached parameter is set to true, a /keys/query request is made to the server to retrieve these devices.

      Parameters

      • userIds: string[]

        The users to fetch.

      • OptionaldownloadUncached: boolean

        If true, download the device list for users whose device list we are not currently tracking. Defaults to false, in which case such users will not appear at all in the result map.

      Returns Promise<DeviceMap>

      A map {@link DeviceMap}.

    • Return the current version of the crypto module. For example: Rust SDK ${versions.matrix_sdk_crypto} (${versions.git_sha}), Vodozemac ${versions.vodozemac}.

      Returns string

      the formatted version

    • Import secrets bundle transmitted from another device.

      Parameters

      • secrets: {
            backup?: { algorithm: string; backup_version: string; key: string };
            cross_signing: {
                master_key: string;
                self_signing_key: string;
                user_signing_key: string;
            };
        }

        The secrets bundle received from the other device

      Returns Promise<void>

    • 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, () 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 Promise<boolean>

      True if cross-signing is ready to be used on this device

      May throw matrix.ClientStoppedError if the MatrixClient is stopped before or during the call.

    • Returns whether MSC3814 dehydrated devices are supported by the crypto backend and by the server.

      This should be called before calling startDehydration, and if this returns false, startDehydration should not be called.

      Returns Promise<boolean>

    • Check if we believe the given room to be encrypted.

      This method returns true if the room has been configured with encryption. The setting is persistent, so that even if the encryption event is removed from the room state, it still returns true. This helps to guard against a downgrade attack wherein a server admin attempts to remove encryption.

      Parameters

      • roomId: string

      Returns Promise<boolean>

      true if the room with the supplied ID is encrypted. false if the room is not encrypted, or is unknown to us.

    • 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, () 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 Promise<boolean>

      True if secret storage is ready to be used on this device

    • Attempt to fetch the backup decryption key from secret storage.

      If the key is found in secret storage, checks it against the latest backup on the server; if they match, stores the key in the crypto store by calling storeSessionBackupPrivateKey, which enables automatic restore of individual keys when an Unable-to-decrypt error is encountered.

      If we are unable to fetch the key from secret storage, there is no backup on the server, or the key does not match, throws an exception.

      Returns Promise<void>

    • Called by the /sync loop whenever an m.room.encryption event is received.

      This is called before RoomStateEvents are emitted for any of the events in the /sync response (even if the other events technically happened first). This works around a problem if the client uses a RoomStateEvent (typically a membership event) as a trigger to send a message in a new room (or one where encryption has been newly enabled): that would otherwise leave the crypto layer confused because it expects crypto to be set up, but it has not yet been.

      Parameters

      • room: Room

        in which the event was received

      • event: MatrixEvent

        encryption event to be processed

      Returns Promise<void>

    • Called by the /sync loop when one time key counts and unused fallback key details are received.

      Parameters

      • OptionaloneTimeKeysCounts: Record<string, number>

        the received one time key counts

      • OptionalunusedFallbackKeys: string[]

        the received unused fallback keys

      Returns Promise<void>

    • Request an interactive verification with the given device.

      This is normally used on one of our own devices, when the current device is already cross-signed, and we want to validate another device.

      If a verification for this user/device is already in flight, returns it. Otherwise, initiates a new one.

      To control the methods offered, set matrix.ICreateClientOpts.verificationMethods when creating the MatrixClient.

      Parameters

      • userId: string

        ID of the owner of the device to verify

      • deviceId: string

        ID of the device to verify

      Returns Promise<VerificationRequest>

      a VerificationRequest when the request has been sent to the other party.

    • Reset the encryption of the user by going through the following steps:

      • Remove the dehydrated device and stop the periodic creation of dehydrated devices.
      • Disable backing up room keys and delete any existing backups.
      • Remove the default secret storage key from the account data (ie: the recovery key).
      • Reset the cross-signing keys.
      • Create a new key backup.

      Note that the dehydrated device will be removed, but will not be replaced and it will not schedule creating new dehydrated devices. To do this, startDehydration should be called after a new secret storage key is created.

      Parameters

      Returns Promise<void>

    • Mark the given device as locally verified.

      Marking a device as locally verified has much the same effect as completing the verification dance, or receiving a cross-signing signature for it.

      Parameters

      • userId: string

        owner of the device

      • deviceId: string

        unique identifier for the device.

      • Optionalverified: boolean

        whether to mark the device as verified. Defaults to 'true'.

      Returns Promise<void>

      an error if the device is unknown, or has not published any encryption keys.

    • Set whether to trust other user's signatures of their devices.

      If false, devices will only be considered 'verified' if we have verified that device individually (effectively disabling cross-signing).

      true by default.

      Parameters

      • val: boolean

        the new value

      Returns void

    • Start using device dehydration.

      • Rehydrates a dehydrated device, if one is available and opts.rehydrate is true.
      • Creates a new dehydration key, if necessary, and stores it in Secret Storage.
        • If opts.createNewKey is set to true, always creates a new key.
        • If a dehydration key is not available, creates a new one.
      • Creates a new dehydrated device, and schedules periodically creating new dehydrated devices.

      This function must not be called unless isDehydrationSupported returns true, and must not be called until after cross-signing and secret storage have been set up.

      Parameters

      • Optionalopts: boolean | StartDehydrationOpts

        options for device dehydration. For backwards compatibility with old code, a boolean can be given here, which will be treated as the createNewKey option. However, this is deprecated.

      Returns Promise<void>

    • Store the backup decryption key.

      This should be called if the client has received the key from another device via secret sharing (gossiping). It is the responsability of the caller to check that the decryption key is valid for the current backup version.

      Parameters

      Returns Promise<void>

      prefer the variant with a version parameter.

    • Store the backup decryption key.

      This should be called if the client has received the key from another device via secret sharing (gossiping). It is the responsability of the caller to check that the decryption key is valid for the given backup version.

      Parameters

      • key: Uint8Array

        the backup decryption key

      • version: string

        the backup version corresponding to this decryption key

      Returns Promise<void>

    • Check if the given user has published cross-signing keys.

      • If the user is tracked, a /keys/query request is made to update locally the cross signing keys.
      • If the user is not tracked locally and downloadUncached is set to true, a /keys/query request is made to the server to retrieve the cross signing keys.
      • Otherwise, return false

      Parameters

      • OptionaluserId: string

        the user ID to check. Defaults to the local user.

      • OptionaldownloadUncached: boolean

        If true, download the device list for users whose device list we are not currently tracking. Defaults to false, in which case false will be returned for such users.

      Returns Promise<boolean>

      true if the cross signing keys are available.

    MMNEPVFCICPMFPCPTTAAATR