Common interface for the crypto implementations

Hierarchy

Implements

Constructors

Properties

Methods

addListener addSecretStorageKey afterCrossSigningLocalKeyChange beginKeyVerification bootstrapCrossSigning bootstrapSecretStorage cancelAndResendAllOutgoingKeyRequests cancelRoomKeyRequest checkCrossSigningPrivateKey checkDeviceInfoTrust checkDeviceTrust checkDeviceVerifications checkForDeviceVerificationUpgrade checkForValidDeviceSignature checkIfOwnDeviceCrossSigned checkOwnCrossSigningTrust checkSecretStorageKey checkSecretStoragePrivateKey checkUserTrust countSessionsNeedingBackup createRecoveryKeyFromPassphrase decryptEvent downloadKeys emit enableLazyLoading encryptAndSendToDevices encryptEvent ensureOlmSessionsForUsers evalDeviceListChanges eventNames exportRoomKeys findVerificationRequestDMInProgress forceDiscardSession getCrossSigningId getCryptoTrustCrossSignedDevices getDefaultSecretStorageKeyId getDeviceCurve25519Key getDeviceEd25519Key getEventEncryptionInfo getEventSenderDeviceInfo getGlobalBlacklistUnverifiedDevices getNeedsNewFallback getOlmSessionsForUser getRoomDecryptor getRoomDecryptors getSecret getSecretStorageKey getSessionBackupPrivateKey getStoredCrossSigningForUser getStoredDevice getStoredDevicesForUser getTrackedE2eRooms getTrackedE2eUsers getVerificationRequestsToDeviceInProgress handleDeviceListChanges handleVerificationEvent hasSecretStorageKey importRoomKeys init isCrossSigningReady isSecretStorageReady isSecretStored legacyDeviceVerification listenerCount listeners maybeUploadOneTimeKeys off on onCryptoEvent onDeviceListUserCrossSigningUpdated onKeyVerificationMessage onMembership onRoomKeyEvent onRoomKeyRequestEvent onRoomKeyWithheldEvent onRoomMembership onSyncCompleted onSyncWillProcess onTimelineEvent onToDeviceBadEncrypted onToDeviceEvent once prepareToEncrypt prependListener prependOnceListener preprocessToDeviceMessages processReceivedRoomKeyRequest processReceivedRoomKeyRequestCancellation processReceivedRoomKeyRequests rawListeners registerEventHandlers removeAllListeners removeListener requestRoomKey requestSecret requestVerification requestVerificationDM requestVerificationWithChannel saveDeviceList setCryptoTrustCrossSignedDevices setDefaultSecretStorageKeyId setDeviceVerification setGlobalBlacklistUnverifiedDevices setNeedsNewFallback setRoomEncryption setRoomEncryptionImpl signObject start stop storeSecret storeSessionBackupPrivateKey storeTrustedSelfKeys trackRoomDevices trackRoomDevicesImpl updateOneTimeKeyCount uploadDeviceKeys uploadOneTimeKeys userHasCrossSigningKeys getOlmVersion

Constructors

  • Internal

    Cryptography bits

    This module is internal to the js-sdk; the public API is via MatrixClient.

    Parameters

    • baseApis: MatrixClient

      base matrix api interface

    • userId: string

      The user ID for the local user

    • deviceId: string

      The identifier for this device.

    • clientStore: IStore

      the MatrixClient data store.

    • cryptoStore: CryptoStore

      storage for the crypto layer.

    • roomList: RoomList

      An initialised RoomList object

    • verificationMethods: (string | typeof VerificationBase & {
          NAME: string;
      })[]

      Array of verification methods to use. Each element can either be a string from MatrixClient.verificationMethods or a class that implements a verification method.

    Returns Crypto

Properties

backupManager: BackupManager
baseApis: MatrixClient

base matrix api interface

clientStore: IStore

the MatrixClient data store.

crossSigningInfo: CrossSigningInfo
cryptoStore: CryptoStore

storage for the crypto layer.

dehydrationManager: DehydrationManager
deviceId: string

The identifier for this device.

deviceKeys: Record<string, string> = {}
deviceList: DeviceList
fallbackCleanup?: Timeout
globalBlacklistUnverifiedDevices: boolean = false

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 = true

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.

inRoomVerificationRequests: InRoomRequests
lastNewSessionForced: Record<string, Record<string, number>> = {}
lastOneTimeKeyCheck: null | number = null
lazyLoadMembers: boolean = false
needsNewFallback?: boolean
olmDevice: OlmDevice
oneTimeKeyCheckInProgress: boolean = false
oneTimeKeyCount?: number
outgoingRoomKeyRequestManager: OutgoingRoomKeyRequestManager
processingRoomKeyRequests: boolean = false
receivedRoomKeyRequestCancellations: IncomingRoomKeyRequestCancellation[] = []
receivedRoomKeyRequests: IncomingRoomKeyRequest[] = []
roomDecryptors: Map<string, Map<string, DecryptionAlgorithm>> = ...
roomDeviceTrackingState: {
    [roomId: string]: Promise<void>;
} = {}

Type declaration

  • [roomId: string]: Promise<void>
roomEncryptors: Map<string, EncryptionAlgorithm> = ...
roomList: RoomList

An initialised RoomList object

secretStorage: SecretStorage<MatrixClient>
sendKeyRequestsImmediately: boolean = false
supportedAlgorithms: string[]
toDeviceVerificationRequests: ToDeviceRequests
trustCrossSignedDevices: boolean = true
userId: string

The user ID for the local user

verificationMethods: Map<string, typeof VerificationBase>

Methods

  • Run various follow-up actions after cross-signing keys have changed locally (either by resetting the keys for the account or by getting them from secret storage), such as signing the current device, upgrading device verifications, etc.

    Returns Promise<void>

  • Parameters

    • method: string
    • userId: string
    • deviceId: string
    • transactionId: null | string = null

    Returns VerificationBase<any, any>

  • 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 setup)

    The cross-signing API is currently UNSTABLE and may change without notice.

    Parameters

    Returns Promise<void>

  • 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

    The Secure Secret Storage API is currently UNSTABLE and may change without notice.

    Parameters

    Returns Promise<void>

  • Re-send any outgoing key requests, eg after verification

    Returns

    Returns Promise<void>

  • 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.

    Returns

    true if the key matches, otherwise false

    Parameters

    • privateKey: Uint8Array

      The private key

    • expectedPublicKey: string

      The public key

    Returns boolean

  • Check if the master key is signed by a verified device, and if so, prompt the application to mark it as verified.

    Parameters

    • userId: string

      the user ID whose key should be checked

    Returns Promise<void>

  • Check if the cross-signing key is signed by a verified device.

    Parameters

    • userId: string

      the user ID whose key is being checked

    • key: ICrossSigningKey

      the key that is being checked

    • devices: Record<string, IDevice>

      the user's devices. Should be a map from device ID to device info

    Returns Promise<string[]>

  • Check whether one of our own devices is cross-signed by our user's stored keys, regardless of whether we trust those keys yet.

    Returns

    true if the device is cross-signed

    Parameters

    • deviceId: string

      The ID of the device to check

    Returns boolean

  • 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.

    Returns

    true if the key matches, otherwise false

    Parameters

    • privateKey: Uint8Array

      The private key

    • expectedPublicKey: string

      The public key

    Returns boolean

  • 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

    Returns Promise<number>

  • Create a recovery key from a user-supplied passphrase.

    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.

    Parameters

    • Optional password: string

      Passphrase string that can be entered by the user when restoring the backup as an alternative to entering the recovery key. Optional.

    Returns Promise<IRecoveryKey>

  • Download the keys for a list of users and stores the keys in the session store.

    Returns

    A promise which resolves to a map userId->deviceId->{@link DeviceInfo}.

    Parameters

    • userIds: string[]

      The users to fetch.

    • Optional forceDownload: boolean

      Always download the keys even if cached.

    Returns Promise<DeviceInfoMap>

  • Encrypts and sends a given object via Olm to-device messages to a given set of devices.

    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.

    Parameters

    • userDeviceInfoArr: IOlmDevice<DeviceInfo>[]

      the devices to send to

    • payload: object

      fields to include in the encrypted payload

    Returns Promise<void>

  • Encrypt an event according to the configuration of the room.

    Returns

    Promise which resolves when the event has been encrypted, or null if nothing was needed

    Parameters

    • event: MatrixEvent

      event to be sent

    • Optional room: Room

      destination room.

    Returns Promise<void>

  • Try to make sure we have established olm sessions for all known devices for the given users.

    Returns

    resolves once the sessions are complete, to an Object mapping from userId to deviceId to OlmSessionResult

    Parameters

    • users: string[]

      list of user ids

    • Optional force: boolean

      If true, force a new Olm session to be created. Default false.

    Returns Promise<Record<string, Record<string, IOlmSessionResult>>>

  • Trigger the appropriate invalidations and removes for a given device list

    Parameters

    • deviceLists: IDeviceLists

      device_lists field from /sync, or response from /keys/changes

    Returns Promise<void>

  • Forces the current outbound group session to be discarded such that another one will be created next time an event is sent.

    Parameters

    • roomId: string

      The ID of the room to discard the session for

      This should not normally be necessary.

    Returns void

  • Get the user's cross-signing key ID.

    Returns

    the key ID

    Parameters

    • type: string

      The type of key to get the ID of. One of "master", "self_signing", or "user_signing". Defaults to "master".

    Returns null | string

  • 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

    Returns boolean

  • Returns Promise<null | string>

  • Get the Curve25519 key for this device

    Returns

    base64-encoded curve25519 key.

    Returns null | string

  • Get the Ed25519 key for this device

    Returns

    base64-encoded ed25519 key.

    Returns null | string

  • Get information about the encryption of an event

    Returns

    An object with the fields:

    • encrypted: whether the event is encrypted (if not encrypted, some of the other properties may not be set)
    • senderKey: the sender's key
    • algorithm: the algorithm used to encrypt the event
    • authenticated: whether we can be sure that the owner of the senderKey sent the event
    • sender: the sender's device information, if available
    • mismatchedSender: if the event's ed25519 and curve25519 keys don't match (only meaningful if sender is set)

    Parameters

    Returns IEncryptedEventInfo

  • Returns

    whether to blacklist all unverified devices by default

    Deprecated

    For external code, use getGlobalBlacklistUnverifiedDevices. For internal code, reference MatrixClient#globalBlacklistUnverifiedDevices directly.

    Returns boolean

  • Get information on the active olm sessions with a user

    Returns a map from device id to an object with keys 'deviceIdKey' (the device's curve25519 identity key) and 'sessions' (an array of objects in the same format as that returned by getSessionInfoForDevice).

    This method is provided for debugging purposes.

    Parameters

    • userId: string

      id of user to inspect

    Returns Promise<Record<string, IUserOlmSession>>

  • Internal

    Get a decryptor for a given room and algorithm.

    If we already have a decryptor for the given room and algorithm, return it. Otherwise try to instantiate it.

    Throws

    DecryptionError if the algorithm is unknown

    Parameters

    • roomId: null | string

      room id for decryptor. If undefined, a temporary decryptor is instantiated.

    • algorithm: string

      crypto algorithm

    Returns DecryptionAlgorithm

  • Parameters

    • name: string

    Returns Promise<undefined | string>

  • Fetches the backup private key, if cached

    Returns

    the key, if any, or null

    Returns Promise<null | Uint8Array>

  • Get the cross signing information for a given user.

    Returns

    the cross signing information for the user.

    Parameters

    • userId: string

      the user ID to get the cross-signing info for.

    Returns null | CrossSigningInfo

  • Get the stored keys for a single device

    Returns

    device, or undefined if we don't know about this device

    Parameters

    • userId: string
    • deviceId: string

    Returns undefined | DeviceInfo

  • Get the stored device keys for a user id

    Returns

    list of devices, or null if we haven't managed to get a list of devices for this user yet.

    Parameters

    • userId: string

      the user to list keys for.

    Returns null | DeviceInfo[]

  • Get a list of the e2e-enabled rooms we are members of, and for which we are already tracking the devices

    Returns

    Returns Room[]

  • Get a list of all the IDs of users we share an e2e room with for which we are tracking devices already

    Returns

    List of user IDs

    Returns Promise<string[]>

  • Handle the notification from /sync or /keys/changes that device lists have been changed.

    Parameters

    • syncData: ISyncStateData

      Object containing sync tokens associated with this sync

    • syncDeviceLists: IDeviceLists

      device_lists field from /sync, or response from /keys/changes

    Returns Promise<void>

  • Parameters

    • Optional keyID: string

    Returns Promise<boolean>

  • Initialise the crypto module so that it is ready for use

    Returns a promise which resolves once the crypto module is ready for use.

    Parameters

    • exportedOlmDevice: IInitOpts = {}

      (Optional) data from exported device that must be re-created.

    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, 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.

    The cross-signing API is currently UNSTABLE and may change without notice.

    Returns

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

    Returns Promise<boolean>

  • 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.

    The Secure Secret Storage API is currently UNSTABLE and may change without notice.

    Returns

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

    Returns Promise<boolean>

  • Parameters

    • userId: string

    Returns Promise<void>

  • Internal

    Handle a change in the membership state of a member of a room

    Parameters

    • event: MatrixEvent

      event causing the change

    • member: RoomMember

      user whose membership changed

    • Optional oldMembership: string

      previous membership

    Returns void

  • Internal

    Handle key verification requests sent as timeline events

    Parameters

    • event: MatrixEvent

      the timeline event

    • room: Room

      not used

    • atStart: boolean

      not used

    • removed: boolean

      not used

    • whether: {
          liveEvent: undefined | boolean;
      } = {}

      this is a live event

      • liveEvent: undefined | boolean

    Returns void

  • Perform any background tasks that can be done before a message is ready to send, in order to speed up sending of the message.

    Parameters

    • room: Room

      the room the event is in

    Returns void

  • Called by the /sync loop whenever there are incoming to-device messages.

    The implementation may preprocess the received messages (eg, decrypt them) and return an updated list of messages for dispatch to the rest of the system.

    Note that, unlike ToDeviceEvent events, this is called on the raw to-device messages, rather than the results of any decryption attempts.

    Returns

    A list of preprocessed to-device messages.

    Parameters

    Returns Promise<IToDeviceEvent[]>

  • Internal

    Process any m.room_key_request events which were queued up during the current sync.

    Returns Promise<void>

  • Save the device list, if necessary

    Returns

    true if the data was saved, false if it was not (eg. because no changes were pending). The promise will only resolve once the data is saved, so may take some time to resolve.

    Parameters

    • delay: number

      Time in ms before which the save actually happens. By default, the save is delayed for a short period in order to batch multiple writes, but this behaviour can be disabled by passing 0.

    Returns Promise<boolean>

  • See getCryptoTrustCrossSignedDevices

    This may be set before initCrypto() is called to ensure no races occur.

    Parameters

    • val: boolean

      True to trust cross-signed devices

    Returns void

  • Parameters

    • k: string

    Returns Promise<void>

  • Update the blocked/verified state of the given device

    Returns

    updated DeviceInfo

    Parameters

    • userId: string

      owner of the device

    • deviceId: string

      unique identifier for the device or user's cross-signing public key ID.

    • verified: null | boolean = null

      whether to mark the device as verified. Null to leave unchanged.

    • blocked: null | boolean = null

      whether to mark the device as blocked. Null to leave unchanged.

    • known: null | boolean = null

      whether to mark that the user has been made aware of the existence of this device. Null to leave unchanged

    • Optional keys: Record<string, string>

      The list of keys that was present during the device verification. This will be double checked with the list of keys the given device has currently.

    Returns Promise<DeviceInfo | CrossSigningInfo>

  • 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.

    Deprecated

    For external code, use setGlobalBlacklistUnverifiedDevices. For internal code, set MatrixClient#globalBlacklistUnverifiedDevices directly.

    Parameters

    • value: boolean

      whether to blacklist all unverified devices by default

    Returns void

  • Parameters

    • needsNewFallback: boolean

    Returns void

  • Configure a room to use encryption (ie, save a flag in the cryptoStore).

    Deprecated

    It is normally incorrect to call this method directly. Encryption is enabled by receiving an m.room.encryption event (which we may have sent previously).

    Parameters

    • roomId: string

      The room ID to enable encryption in.

    • config: IRoomEncryption

      The encryption config for the room.

    • Optional inhibitDeviceQuery: boolean

      true to suppress device list query for users in the room (for now). In case lazy loading is enabled, the device query is always inhibited as the members are not tracked.

    Returns Promise<void>

  • Set up encryption for a room.

    This is called when an m.room.encryption event is received. It saves a flag for the room in the cryptoStore (if it wasn't already set), sets up an "encryptor" for the room, and enables device-list tracking for the room.

    It does not initiate a device list query for the room. That is normally done once we finish processing the sync, in onSyncCompleted.

    Parameters

    • room: Room

      The room to enable encryption in.

    • config: IRoomEncryption

      The encryption config for the room.

    Returns Promise<void>

  • sign the given object with our ed25519 key

    Type Parameters

    Parameters

    • obj: T

      Object to which we will add a 'signatures' property

    Returns Promise<void>

  • Deprecated

    this does nothing and will be removed in a future version

    Returns void

  • Parameters

    • name: string
    • secret: string
    • Optional keys: string[]

    Returns Promise<void>

  • Stores the session backup key to the cache

    Returns

    a promise so you can catch failures

    Parameters

    • key: ArrayLike<number>

      the private key

    Returns Promise<void>

  • Store a set of keys as our own, trusted, cross-signing keys.

    Parameters

    Returns Promise<void>

  • Make sure we are tracking the device lists for all users in this room.

    Returns

    when all devices for the room have been fetched and marked to track

    Deprecated

    there's normally no need to call this function: device list tracking will be enabled as soon as we have the full membership list.

    Parameters

    • roomId: string

      The room ID to start tracking devices in.

    Returns Promise<void>

  • Make sure we are tracking the device lists for all users in this room.

    This is normally called when we are about to send an encrypted event, to make sure we have all the devices in the room; but it is also called when processing an m.room.encryption state event (if lazy-loading is disabled), or when members are loaded (if lazy-loading is enabled), to prepare the device list.

    Parameters

    • room: Room

      Room to enable device-list tracking in

    Returns Promise<void>

  • Stores the current one_time_key count which will be handled later (in a call of onSyncCompleted). The count is e.g. coming from a /sync response.

    Parameters

    • currentCount: number

      The current count of one_time_keys to be stored

    Returns void

  • Internal

    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.

    Returns Promise<boolean>

  • Returns

    The version of Olm.

    Returns [number, number, number]

Generated using TypeDoc