Common interface for the crypto implementations

Hierarchy (view full)

Implements

Constructors

Properties

Methods

addListener addSecretStorageKey beginKeyVerification bootstrapCrossSigning bootstrapSecretStorage cancelAndResendAllOutgoingKeyRequests cancelRoomKeyRequest checkCrossSigningPrivateKey checkDeviceInfoTrust checkDeviceTrust checkIfOwnDeviceCrossSigned checkKeyBackupAndEnable checkOwnCrossSigningTrust checkSecretStorageKey checkSecretStoragePrivateKey checkUserTrust countSessionsNeedingBackup createRecoveryKeyFromPassphrase crossSignDevice decryptEvent deleteKeyBackupVersion downloadKeys emit emitPromised enableLazyLoading encryptAndSendToDevices encryptEvent ensureOlmSessionsForUsers exportRoomKeys exportRoomKeysAsJson findVerificationRequestDMInProgress forceDiscardSession getActiveSessionBackupVersion getBackupDecryptor getCrossSigningId getCrossSigningKeyId getCrossSigningStatus getCryptoTrustCrossSignedDevices getDefaultSecretStorageKeyId getDeviceCurve25519Key getDeviceEd25519Key getDeviceVerificationStatus getEncryptionInfoForEvent getEventEncryptionInfo getEventSenderDeviceInfo getGlobalBlacklistUnverifiedDevices getNeedsNewFallback getOlmSessionsForUser getOwnDeviceKeys getRoomDecryptor getRoomEncryption getSecret getSecretStorageKey getSessionBackupPrivateKey getStoredCrossSigningForUser getStoredDevice getStoredDevicesForUser getTrustCrossSignedDevices getUserDeviceInfo getUserVerificationStatus getVerificationRequestsToDeviceInProgress getVersion hasSecretStorageKey importBackedUpRoomKeys importRoomKeys importRoomKeysAsJson init isCrossSigningReady isDehydrationSupported isEncryptionEnabledInRoom isKeyBackupTrusted isRoomEncrypted isSecretStorageReady isSecretStored legacyDeviceVerification listenerCount listeners off on once onCryptoEvent onSyncCompleted onSyncWillProcess pinCurrentUserIdentity prepareToEncrypt prependListener prependOnceListener preprocessToDeviceMessages processDeviceLists processKeyCounts rawListeners registerEventHandlers removeAllListeners removeListener requestDeviceVerification requestOwnUserVerification requestRoomKey requestSecret requestVerification requestVerificationDM resetKeyBackup saveDeviceList setCryptoTrustCrossSignedDevices setDefaultSecretStorageKeyId setDeviceIsolationMode setDeviceVerification setDeviceVerified setGlobalBlacklistUnverifiedDevices setRoomEncryption setTrustCrossSignedDevices signObject start startDehydration stop storeSecret storeSessionBackupPrivateKey trackRoomDevices uploadDeviceKeys 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.

    • 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

crossSigningInfo: CrossSigningInfo
cryptoStore: CryptoStore

storage for the crypto layer.

dehydrationManager: DehydrationManager
deviceList: DeviceList
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.

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

inRoomVerificationRequests: InRoomRequests
olmDevice: OlmDevice
secretStorage: SecretStorage<MatrixClient>
supportedAlgorithms: string[]
userId: string

The user ID for the local user

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

    Returns: A promise which resolves to key creation data for SecretStorage#addKey: an object with passphrase etc fields.

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

    • OptionalforceDownload: boolean

      Always download the keys even if cached.

    Returns Promise<DeviceInfoMap>

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

  • Synchronously calls each of the listeners registered for the event named event, in the order they were registered, passing the supplied arguments to each.

    Type Parameters

    Parameters

    Returns boolean

    true if the event had listeners, false otherwise.

  • Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments to each.

    Returns true if the event had listeners, false otherwise.

    import EventEmitter from 'node:events';
    const myEmitter = new EventEmitter();

    // First listener
    myEmitter.on('event', function firstListener() {
    console.log('Helloooo! first listener');
    });
    // Second listener
    myEmitter.on('event', function secondListener(arg1, arg2) {
    console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
    });
    // Third listener
    myEmitter.on('event', function thirdListener(...args) {
    const parameters = args.join(', ');
    console.log(`event with parameters ${parameters} in third listener`);
    });

    console.log(myEmitter.listeners('event'));

    myEmitter.emit('event', 1, 2, 3, 4, 5);

    // Prints:
    // [
    // [Function: firstListener],
    // [Function: secondListener],
    // [Function: thirdListener]
    // ]
    // Helloooo! first listener
    // event with parameters 1, 2 in second listener
    // event with parameters 1, 2, 3, 4, 5 in third listener

    Type Parameters

    Parameters

    Returns boolean

    v0.1.26

  • 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

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

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

  • 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

    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.

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

  • Import a JSON string encoding a list of room keys previously exported by exportRoomKeysAsJson

    Parameters

    • keys: string

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

    • Optionalopts: ImportRoomKeysOpts

      options object

    Returns Promise<void>

    a promise which resolves once the keys have been imported

  • 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

  • Parameters

    • roomId: string

    Returns 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, 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 this

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

  • Adds a one-time listener function for the event named event. The next time event is triggered, this listener is removed and then invoked.

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

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

    Type Parameters

    Parameters

    Returns this

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

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

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

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

  • 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

    • Optionalkeys: 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<
        | undefined
        | DeviceInfo
        | CrossSigningInfo
        | CrossSigningKeyInfo>

    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.

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

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

  • Returns void

    this does nothing and will be removed in a future version

  • 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

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

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

    Parameters

    • userId: string = ...

    Returns Promise<boolean>

  • Returns [number, number, number]

    The version of Olm.