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 emitPromised enableLazyLoading encryptAndSendToDevices encryptEvent ensureOlmSessionsForUsers evalDeviceListChanges exportRoomKeys findVerificationRequestDMInProgress forceDiscardSession getCrossSigningId getCrossSigningKeyId getCrossSigningStatus getCryptoTrustCrossSignedDevices getDefaultSecretStorageKeyId getDeviceCurve25519Key getDeviceEd25519Key getDeviceVerificationStatus getEventEncryptionInfo getEventSenderDeviceInfo getGlobalBlacklistUnverifiedDevices getNeedsNewFallback getOlmSessionsForUser getRoomDecryptor getRoomDecryptors getSecret getSecretStorageKey getSessionBackupPrivateKey getStoredCrossSigningForUser getStoredDevice getStoredDevicesForUser getTrackedE2eRooms getTrackedE2eUsers getTrustCrossSignedDevices getUserDeviceInfo getVerificationRequestsToDeviceInProgress 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 processDeviceLists processKeyCounts processReceivedRoomKeyRequest processReceivedRoomKeyRequestCancellation processReceivedRoomKeyRequests rawListeners registerEventHandlers removeAllListeners removeListener requestDeviceVerification requestOwnUserVerification requestRoomKey requestSecret requestVerification requestVerificationDM requestVerificationWithChannel saveDeviceList setCryptoTrustCrossSignedDevices setDefaultSecretStorageKeyId setDeviceVerification setGlobalBlacklistUnverifiedDevices setRoomEncryption setRoomEncryptionImpl setTrustCrossSignedDevices 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?: number
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.

Remarks

this is here, rather than in CryptoApi, because I don't think we're going to support it in the rust crypto implementation.

inRoomVerificationRequests: InRoomRequests
lastNewSessionForced: MapWithDefault<string, MapWithDefault<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

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>

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

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

    Parameters

    • privateKey: Uint8Array

      The private key

    • expectedPublicKey: string

      The public key

    Returns boolean

    true if the key matches, otherwise false

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

    Parameters

    • deviceId: string

      The ID of the device to check

    Returns boolean

    true if the device is cross-signed

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

    Parameters

    • privateKey: Uint8Array

      The private key

    • expectedPublicKey: string

      The public key

    Returns boolean

    true if the key matches, otherwise false

  • Counts the number of end to end session keys that are waiting to be backed up

    Returns Promise<number>

    Promise which resolves to the number of sessions requiring backup

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

    Parameters

    • userIds: string[]

      The users to fetch.

    • Optional forceDownload: boolean

      Always download the keys even if cached.

    Returns Promise<DeviceInfoMap>

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

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

    Parameters

    • userDeviceInfoArr: IOlmDevice<DeviceInfo>[]

      the devices to send to

    • payload: object

      fields to include in the encrypted payload

    Returns Promise<void>

    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.

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

    Parameters

    • users: string[]

      list of user ids

    • Optional force: boolean

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

    Returns Promise<Map<string, Map<string, IOlmSessionResult>>>

    resolves once the sessions are complete, to an Object mapping from userId to deviceId to 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 Promise<void>

  • Parameters

    • type: string

    Returns null | string

  • Get the Curve25519 key for this device

    Returns null | string

    base64-encoded curve25519 key.

  • Get the Ed25519 key for this device

    Returns null | string

    base64-encoded ed25519 key.

  • Get information about the encryption of an event

    Parameters

    Returns IEncryptedEventInfo

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

    Parameters

    • roomId: null | string

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

    • algorithm: string

      crypto algorithm

    Returns DecryptionAlgorithm

    Throws

    DecryptionError if the algorithm is unknown

  • Get the stored keys for a single device

    Parameters

    • userId: string
    • deviceId: string

    Returns undefined | DeviceInfo

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

  • Get the stored device keys for a user id

    Parameters

    • userId: string

      the user to list keys for.

    Returns null | DeviceInfo[]

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

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

    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 Promise<string[]>

    List of user IDs

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

    True if trusting cross-signed devices

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

    Parameters

    • userIds: string[]

      The users to fetch.

    • downloadUncached: boolean = false

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

  • 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 Promise<boolean>

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

  • 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 Promise<boolean>

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

  • Adds the listener function to the end of the listeners array for the event named event.

    No checks are made to see if the listener has already been added. Multiple calls passing the same combination of event and listener will result in the listener being added, and called, multiple times.

    By default, event listeners are invoked in the order they are added. The prependListener method can be used as an alternative to add the event listener to the beginning of the listeners array.

    Type Parameters

    Parameters

    Returns Crypto

    a reference to the EventEmitter, so that calls can be chained.

  • Internal

    Handle a general key verification event.

    Parameters

    Returns void

  • Internal

    Called when we get an m.room_key_request event.

    Parameters

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

    Parameters

    Returns Promise<IToDeviceEvent[]>

    A list of preprocessed to-device messages.

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

    Parameters

    • Optional oneTimeKeysCounts: Record<string, number>

      the received one time key counts

    • Optional unusedFallbackKeys: string[]

      the received unused fallback keys

    Returns Promise<void>

  • Internal

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

    Returns Promise<void>

  • Removes all listeners, or those of the specified event.

    It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

    Parameters

    Returns Crypto

    a reference to the EventEmitter, so that calls can be chained.

  • Send a request for some room keys, if we have not already done so

    Parameters

    Returns Promise<void>

    a promise that resolves when the key request is queued

  • Save the device list, if necessary

    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>

    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.

  • Update the blocked/verified state of the given device

    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>

    updated DeviceInfo

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

    Parameters

    • value: boolean

      whether to blacklist all unverified devices by default

    Returns void

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

    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>

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

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

  • Returns void

    Deprecated

    this does nothing and will be removed in a future version

  • Stores the session backup key to the cache

    Parameters

    • key: ArrayLike<number>

      the private key

    Returns Promise<void>

    a promise so you can catch failures

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

    Parameters

    • roomId: string

      The room ID to start tracking devices in.

    Returns Promise<void>

    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.

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

    Parameters

    • currentCount: number

      The current count of one_time_keys to be stored

    Returns void

  • Returns [number, number, number]

    The version of Olm.

Generated using TypeDoc