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.
An initialised RoomList object
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
Private
Readonly
clientthe MatrixClient data store.
Readonly
crossReadonly
cryptostorage for the crypto layer.
Readonly
dehydrationPrivate
Readonly
deviceThe identifier for this device.
Private
deviceReadonly
devicePrivate
Optional
fallbackGlobal 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.
this is here, rather than in CryptoApi
, because I don't think we're
going to support it in the rust crypto implementation.
Readonly
inPrivate
lastPrivate
lastPrivate
lazyPrivate
Optional
needsReadonly
olmPrivate
onePrivate
Optional
onePrivate
Readonly
outgoingPrivate
processingPrivate
Readonly
rePrivate
receivedPrivate
receivedPrivate
roomPrivate
roomPrivate
roomPrivate
Readonly
roomAn initialised RoomList object
Readonly
secretPrivate
sendReadonly
supportedPrivate
Readonly
toPrivate
trustReadonly
userThe user ID for the local user
Private
Readonly
verificationAlias for on.
Optional
keyID: stringUse secretStorage and addKey.
Private
afterRun 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.
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.
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
Private
checkPrivate
checkCheck if a user's cross-signing key is a candidate for upgrading from device verification.
the user whose cross-signing information is to be checked
the cross-signing information to check
Private
checkCheck if the cross-signing key is signed by a verified device.
the user ID whose key is being checked
the key that is being checked
the user's devices. Should be a map from device ID to device info
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 secretStorage and 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.
Decrypt a received event
resolves once we have
finished decrypting. Rejects with an algorithms.DecryptionError
if there
is a problem decrypting the event.
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.
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.
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
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
Private
evalTrigger the appropriate invalidations and removes for a given device list
device_lists field from /sync, or response from /keys/changes
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
the VerificationRequest that is in progress, if any
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 getCrossSigningStatus
Use secretStorage and 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
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 getSessionInfoForDevice).
This method is provided for debugging purposes.
id of user to inspect
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
DecryptionError
if the algorithm is unknown
Private
getGet all the room decryptors for a given encryption algorithm.
The encryption algorithm
An array of room decryptors
Use secretStorage and get.
Optional
keyID: stringUse secretStorage and 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.
Private
getPrivate
getWhether 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}
.
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
Private
handleOptional
keyID: stringUse secretStorage and hasKey.
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
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
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 secretStorage and 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
.
Private
maybeAlias 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.
handle an m.room.encryption event
in which the event was received
encryption event to be processed
Private
onPrivate
onInternal
Handle a general key verification event.
verification start event
Private
onOptional
oldMembership: stringPrivate
onInternal
Handle a key event
key event
Private
onInternal
Called when we get an m.room_key_request event.
key request event
Private
onInternal
Handle a key withheld event
key withheld event
Private
onInternal
Handle a change in the membership state of a member of a room
event causing the change
user whose membership changed
Optional
oldMembership: stringprevious membership
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
Private
onInternal
Handle key verification requests sent as timeline events
the timeline event
not used
not used
not used
this is a live event
Private
onInternal
Handle a toDevice event that couldn't be decrypted
undecryptable event
Private
onAdds 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.
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 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
Private
processPrivate
processHelper for processReceivedRoomKeyRequests
Private
processReturns 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 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 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[]Use requestOwnUserVerificationToDevice
or requestDeviceVerification
Private
requestSave 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 secretStorage and setDefaultKeyId.
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
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.
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).
Private
setSet 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.
The room to enable encryption in.
The encryption config for the room.
sign the given object with our ed25519 key
Object to which we will add a 'signatures' property
Optional
keys: string[]Use secretStorage and store.
Private
storeStore a set of keys as our own, trusted, cross-signing keys.
The new trusted set of keys
Make sure we are tracking the device lists for all users in this room.
The room ID to start tracking devices in.
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.
Private
trackMake 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.
Room to enable device-list tracking in
Private
updateUpload the device keys to the homeserver.
A promise that will resolve when the keys are uploaded.
Private
uploadStatic
getGenerated using TypeDoc
Common interface for the crypto implementations