Internal
Internal
Cryptography bits
This module is internal to the js-sdk; the public API is via MatrixClient.
base matrix api interface
The user ID for the local user
The identifier for this device.
the MatrixClient data store.
storage for the crypto layer.
Array of verification methods to use. Each element can either be a string from MatrixClient.verificationMethods or a class that implements a verification method.
Readonly
backupReadonly
basebase matrix api interface
Readonly
crossReadonly
cryptostorage for the crypto layer.
Readonly
dehydrationReadonly
deviceGlobal 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
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.
Readonly
inReadonly
olmReadonly
secretReadonly
supportedReadonly
userThe user ID for the local user
Alias for on.
Optional
keyID: stringUse MatrixClient#secretStorage and SecretStorage.ServerSideSecretStorage#addKey.
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:
The cross-signing API is currently UNSTABLE and may change without notice.
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
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.
Cancel any earlier room key request
parameters to match for cancellation
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.
The private key
The public key
true if the key matches, otherwise false
Check whether a given deviceinfo is trusted.
The ID of the user whose devices is to be checked.
Optional
device: DeviceInfoThe device info object to check
Force a re-check of the key backup and enable/disable it as appropriate.
Implementation of Crypto.CryptoApi.checkKeyBackupAndEnable.
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.
Use MatrixClient#secretStorage and SecretStorage.ServerSideSecretStorage#checkKey.
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 private key
The public key
true if the key matches, otherwise false
Check whether a given user is trusted.
The ID of the user to check.
Create a recovery key from a user-supplied passphrase.
Optional
password: stringPassphrase string that can be entered by the user when restoring the backup as an alternative to entering the recovery key. Optional.
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.
Blindly cross-sign one of our other devices.
Implementation of Crypto.CryptoApi#crossSignDevice.
Decrypt a received event
resolves once we have
finished decrypting. Rejects with an algorithms.DecryptionError
if there
is a problem decrypting the event.
Implementation of Crypto.CryptoApi#deleteKeyBackupVersion.
Download the keys for a list of users and stores the keys in the session store.
The users to fetch.
Optional
forceDownload: booleanAlways download the keys even if cached.
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.
The name of the event to emit
Rest
...args: Parameters<CryptoEventHandlerMap[T]>Arguments to pass to the listener
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
Rest
...args: Parameters<CryptoEventHandlerMap[T]>Similar to emit
but calls all listeners within a Promise.all
and returns the promise chain
The name of the event to emit
Rest
...args: Parameters<CryptoEventHandlerMap[T]>Arguments to pass to the listener
true
if the event had listeners, false
otherwise.
Rest
...args: Parameters<CryptoEventHandlerMap[T]>Encrypts and sends a given object via Olm to-device messages to a given set of devices.
the devices to send to
fields to include in the encrypted payload
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.
Instead use encryptToDeviceMessages followed by MatrixClient.queueToDevice.
Encrypt an event according to the configuration of the room.
event to be sent
destination room.
Promise which resolves when the event has been encrypted, or null if nothing was needed
Implementation of Crypto.CryptoApi#encryptToDeviceMessages.
Try to make sure we have established olm sessions for all known devices for the given users.
list of user ids
Optional
force: booleanIf true, force a new Olm session to be created. Default false.
resolves once the sessions are complete, to
an Object mapping from userId to deviceId to
IOlmSessionResult
Get a list containing all of the room keys
a list of session export objects
Finds a DM verification request that is already in progress for the given room id
the room to use for verification
Optional
userId: stringthe VerificationRequest that is in progress, if any
Get the current status of key backup.
Implementation of Crypto.CryptoApi.getActiveSessionBackupVersion.
Implementation of CryptoBackend#getBackupDecryptor.
Get the user's cross-signing key ID.
The type of key to get the ID of. One of "master", "self_signing", or "user_signing". Defaults to "master".
the key ID
Implementation of Crypto.CryptoApi#getCrossSigningStatus
Use MatrixClient#secretStorage and SecretStorage.ServerSideSecretStorage#getDefaultKeyId.
Check whether a given device is trusted.
The ID of the user whose device is to be checked.
The ID of the device to check
Implementation of Crypto.CryptoApi.getEncryptionInfoForEvent.
Get information about the encryption of an event
event to be checked
An object with the fields:
sender
is set)Get the device which sent an event
event to be checked
whether to blacklist all unverified devices by default
Reference CryptoApi.globalBlacklistUnverifiedDevices directly.
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 OlmDevice#getSessionInfoForDevice).
This method is provided for debugging purposes.
id of user to inspect
Implementation of Crypto.CryptoApi#getOwnDeviceKeys.
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.
room id for decryptor. If undefined, a temporary decryptor is instantiated.
crypto algorithm
information about the encryption on the room with the supplied ID, or null if the room is not encrypted or unknown to us.
Use MatrixClient#secretStorage and SecretStorage.ServerSideSecretStorage#get.
Optional
keyID: stringUse MatrixClient#secretStorage and SecretStorage.ServerSideSecretStorage#getKey.
Fetches the backup private key, if cached
the key, if any, or null
Get the cross signing information for a given user.
the user ID to get the cross-signing info for.
the cross signing information for the user.
Get the stored keys for a single device
device, or undefined if we don't know about this device
Get the stored device keys for a user id
the user to list keys for.
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
True if trusting cross-signed devices
Get the device information for the given list of users.
The users to fetch.
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.
A map {@link DeviceMap}
.
Implementation of Crypto.CryptoApi.getUserVerificationStatus.
Returns to-device verification requests that are already in progress for the given user id.
the ID of the user to query
the VerificationRequests that are in progress
Implementation of Crypto.CryptoApi#getVersion.
Optional
keyID: stringUse MatrixClient#secretStorage and SecretStorage.ServerSideSecretStorage#hasKey.
Implementation of CryptoBackend#importBackedUpRoomKeys.
Import a list of room keys previously exported by exportRoomKeys
a list of session export objects
a promise which resolves once the keys have been imported
Import a JSON string encoding a list of room keys previously exported by exportRoomKeysAsJson
a JSON string encoding a list of session export objects, each of which is an IMegolmSessionData
Optional
opts: ImportRoomKeysOptsoptions object
a promise which resolves once the keys have been imported
Checks whether cross signing:
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.
True if cross-signing is ready to be used on this device
Implementation of Crypto.CryptoApi#isEncryptionEnabledInRoom.
Determine if a key backup can be trusted.
Implementation of Crypto.CryptoApi.isKeyBackupTrusted.
Checks whether secret storage:
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.
True if secret storage is ready to be used on this device
Use MatrixClient#secretStorage and SecretStorage.ServerSideSecretStorage#isStored.
Returns the number of listeners listening to the event named event
.
The name of the event being listened for
Returns a copy of the array of listeners for the event named event
.
Alias for removeListener
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.
The name of the event.
The callback function
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.
The name of the event.
The callback function
a reference to the EventEmitter
, so that calls can be chained.
handle an m.room.encryption event
in which the event was received
encryption event to be processed
handle the completion of a /sync
This is called after the processing of each successful /sync response. It is an opportunity to do a batch process on the information received.
the data from the 'MatrixClient.sync' event
Called before the result of a sync is processed
the data from the 'MatrixClient.sync' event
Implementation of Crypto.CryptoApi.pinCurrentUserIdentity.
Perform any background tasks that can be done before a message is ready to send, in order to speed up sending of the message.
the room the event is in
Adds the listener
function to the beginning 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.
The name of the event.
The callback function
a reference to the EventEmitter
, so that calls can be chained.
Adds a one-timelistener
function for the event named event
to the beginning of the listeners array.
The next time event
is triggered, this listener is removed, and then invoked.
The name of the event.
The callback function
a reference to the EventEmitter
, so that calls can be chained.
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 ClientEvent.ToDeviceEvent events, this is called on the raw to-device messages, rather than the results of any decryption attempts.
the received to-device messages
A list of preprocessed to-device messages.
Handle the notification from /sync that device lists have been changed.
device_lists field from /sync
Called by the /sync loop when one time key counts and unused fallback key details are received.
Optional
oneTimeKeysCounts: Record<string, number>the received one time key counts
Optional
unusedFallbackKeys: string[]the received unused fallback keys
Returns a copy of the array of listeners for the event named eventName
,
including any wrappers (such as those created by .once()
).
Tell the crypto module to register for MatrixClient events which it needs to listen for
event source where we can register for event notifications
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).
Optional
event: EventEmitterEvents | CryptoEventThe name of the event. If undefined, all listeners everywhere are removed.
a reference to the EventEmitter
, so that calls can be chained.
Removes the specified listener
from the listener array for the event named event
.
a reference to the EventEmitter
, so that calls can be chained.
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
.
ID of the owner of the device to verify
ID of the device to verify
a VerificationRequest when the request has been sent to the other party.
Send a verification request to our other devices.
This is normally used when the current device is new, and we want to ask another of our devices to cross-sign.
If an all-devices verification is already in flight, returns it. Otherwise, initiates a new one.
To control the methods offered, set matrix.ICreateClientOpts.verificationMethods when creating the
MatrixClient
.
a VerificationRequest when the request has been sent to the other party.
Send a request for some room keys, if we have not already done so
whether to resend the key request if there is already one
a promise that resolves when the key request is queued
Optional
devices: string[]Request a key verification from another user, using a DM.
the user to request verification with.
the room to use for verification.
resolves to a VerificationRequest when the request has been sent to the other party.
Implementation of Crypto.CryptoApi#resetKeyBackup.
Save the device list, if necessary
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.
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.
Use MatrixClient#secretStorage and SecretStorage.ServerSideSecretStorage#setDefaultKeyId.
Implementation of Crypto.CryptoApi#setDeviceIsolationMode.
Update the blocked/verified state of the given device
owner of the device
unique identifier for the device or user's cross-signing public key ID.
whether to mark the device as verified. Null to leave unchanged.
whether to mark the device as blocked. Null to leave unchanged.
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.
updated DeviceInfo
Mark the given device as locally verified.
Implementation of Crypto.CryptoApi#setDeviceVerified.
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.
whether to blacklist all unverified devices by default
Set CryptoApi.globalBlacklistUnverifiedDevices directly.
Configure a room to use encryption (ie, save a flag in the cryptoStore).
The room ID to enable encryption in.
The encryption config for the room.
Optional
inhibitDeviceQuery: booleantrue 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.
sign the given object with our ed25519 key
Object to which we will add a 'signatures' property
Optional
keys: string[]Use MatrixClient#secretStorage and SecretStorage.ServerSideSecretStorage#store.
Upload the device keys to the homeserver.
A promise that will resolve when the keys are uploaded.
Static
get
Common interface for the crypto implementations