State machine implementation of the Olm/Megolm encryption protocol used for Matrix end to end encryption.

Constructors

  • Constructor will always fail. To create a new OlmMachine, please use the initialize method.

    Why this pattern? initialize returns a Promise. Returning a

    Returns OlmMachine

Properties

deviceCreationTimeMs: number

The time, in milliseconds since the unix epoch, at which the Account backing this OlmMachine was created.

An Account is created when an OlmMachine is first instantiated against a given Store, at which point it creates identity keys etc. This method returns the timestamp, according to the local clock, at which that happened.

deviceId: DeviceId

The unique device ID that identifies this OlmMachine.

displayName: Promise<any>

Get the display name of our own device.

identityKeys: IdentityKeys

Get the public parts of our Olm identity keys.

roomKeyForwardingEnabled: boolean

Whether room key forwarding is enabled.

If room key forwarding is enabled, we will automatically reply to incoming m.room_key_request messages from verified devices by forwarding the requested key (if we have it).

roomKeyRequestsEnabled: boolean

Whether automatic transmission of room key requests is enabled.

Room key requests allow the device to request room keys that it might have missed in the original share using m.room_key_request events.

userId: UserId

The unique user ID that owns this OlmMachine instance.

Methods

  • Encrypt a batch of room keys and return a request that needs to be sent out to backup the room keys.

    Returns an optional KeysBackupRequest.

    Returns Promise<any>

  • Create a new cross signing identity and get the upload request to push the new public keys to the server.

    Warning: This will delete any existing cross signing keys that might exist on the server and thus will reset the trust between all the devices.

    Uploading these keys will require user interactive auth.

    Arguments

    • reset, whether the method should create a new identity or use the existing one during the request. If set to true, the request will attempt to upload a new identity. If set to false, the request will attempt to upload the existing identity. Since the uploading process requires user interactive authentication, which involves sending out the same request multiple times, setting this argument to false enables you to reuse the same request.

    Returns a CrossSigningBootstrapRequests.

    Parameters

    • reset: boolean

    Returns Promise<any>

  • Shut down the OlmMachine.

    The OlmMachine cannot be used after this method has been called.

    All associated resources will be closed too, like IndexedDB connections.

    Returns void

  • Get the status of the private cross signing keys.

    This can be used to check which private cross signing keys we have stored locally.

    Returns Promise<any>

  • Decrypt an event from a room timeline.

    Arguments

    • event, the event that should be decrypted.
    • room_id, the ID of the room where the event was sent to.

    Returns

    A Promise which resolves to a DecryptedRoomEvent instance, or rejects with a MegolmDecryptionError instance.

    Parameters

    Returns Promise<any>

  • Delete all secrets with the given secret name from the inbox.

    Should be called after handling the secrets with get_secrets_from_inbox.

    Arguments

    • secret_name - The name of the secret to delete.

    Parameters

    • secret_name: string

    Returns Promise<Promise<any>>

  • Disable and reset our backup state.

    This will remove any pending backup request, remove the backup key and reset the backup state of each room key we have.

    Returns Promise<void>.

    Returns Promise<any>

  • Activate the given backup key to be used with the given backup version.

    Warning: The caller needs to make sure that the given BackupKey is trusted, otherwise we might be encrypting room keys that a malicious party could decrypt.

    The #verifyBackup method can be used to do so.

    Returns Promise<void>.

    Parameters

    • public_key_base_64: string
    • version: string

    Returns Promise<any>

  • Encrypt a room message for the given room.

    Note: A room key needs to be shared with the group of users that are members in the given room. If this is not done this method will panic.

    The usual flow to encrypt an event using this state machine is as follows:

    1. Get the one-time key claim request to establish 1:1 Olm sessions for the room members of the room we wish to participate in. This is done using the get_missing_sessions() method. This method call should be locked per call.

    2. Share a room key with all the room members using the share_room_key(). This method call should be locked per room.

    3. Encrypt the event using this method.

    4. Send the encrypted event to the server.

    After the room key is shared steps 1 and 2 will become noops, unless there's some changes in the room membership or in the list of devices a member has.

    room_id is the ID of the room for which the message should be encrypted. event_type is the type of the event. content is the plaintext content of the message that should be encrypted.

    Panics

    Panics if a group session for the given room wasn't shared beforehand.

    Parameters

    • room_id: RoomId
    • event_type: string
    • content: string

    Returns Promise<any>

  • Export all the private cross signing keys we have.

    The export will contain the seeds for the ed25519 keys as unpadded base64 encoded strings.

    Returns null if we don’t have any private cross signing keys; otherwise returns a CrossSigningKeyExport.

    Returns Promise<any>

  • Export the keys that match the given predicate.

    predicate is a closure that will be called for every known InboundGroupSession, which represents a room key. If the closure returns true, the InboundGroupSession will be included in the export; otherwise it won't.

    Returns a Promise containing a Result containing a String which is a JSON-encoded array of ExportedRoomKey objects.

    Parameters

    • predicate: Function

    Returns Promise<any>

  • Export all the secrets we have in the store into a SecretsBundle.

    This method will export all the private cross-signing keys and, if available, the private part of a backup key and its accompanying version.

    The method will fail if we don't have all three private cross-signing keys available.

    Warning: Only export this and share it with a trusted recipient, i.e. if an existing device is sharing this with a new device.

    Returns Promise<SecretsBundle>

  • Returns void

  • Get the backup keys we have saved in our store. Returns a Promise for BackupKeys.

    Returns Promise<any>

  • Get a specific device of a user.

    • user_id - The unique ID of the user that the device belongs to.

    • device_id - The unique ID of the device.

    • timeout_secs - The amount of time we should wait for a /keys/query response before returning if the user's device list has been marked as stale. Note, this assumes that the requests from OlmMachine.outgoingRequests are being processed and sent out.

      If unset, we will return immediately even if the device list is stale.

    If the device is known, a Device. Otherwise, undefined.

    Parameters

    Returns Promise<any>

  • Get the cross signing user identity of a user.

    Returns a promise for an identities.OwnUserIdentity, a identities.OtherUserIdentity, or undefined.

    Parameters

    Returns Promise<any>

  • Get the a key claiming request for the user/device pairs that we are missing Olm sessions for.

    Returns null if no key claiming request needs to be sent out, otherwise it returns a KeysClaimRequest object.

    Sessions need to be established between devices so group sessions for a room can be shared with them.

    This should be called every time a group session needs to be shared as well as between sync calls. After a sync some devices may request room keys without us having a valid Olm session with them, making it impossible to server the room key request, thus it’s necessary to check for missing sessions between sync as well.

    Note: Care should be taken that only one such request at a time is in flight, e.g. using a lock.

    The response of a successful key claiming requests needs to be passed to the OlmMachine with the mark_request_as_sent.

    users represents the list of users that we should check if we lack a session with one of their devices. This can be an empty iterator when calling this method between sync requests.

    Items inside users will be invalidated by this method. Be careful not to use the UserIds after this method has been called.

    Parameters

    Returns Promise<any>

  • Get encryption info for a decrypted timeline event.

    This recalculates the EncryptionInfo data that is returned by decryptRoomEvent, based on the current verification status of the sender, etc.

    Returns an error for an unencrypted event.

    Arguments

    • event - The event to get information for.
    • room_id - The ID of the room where the event was sent to.

    Returns

    EncryptionInfo

    Parameters

    Returns Promise<any>

  • Get the stored room settings, such as the encryption algorithm or whether to encrypt only for trusted devices.

    These settings can be modified via #setRoomSettings.

    Returns

    Promise<RoomSettings|undefined>

    Parameters

    Returns Promise<any>

  • Get all the secrets with the given secret_name we have currently stored. The only secret this will currently return is the m.megolm_backup.v1 secret.

    Usually you would just register a callback with [register_receive_secret_callback], but if the client is shut down before handling them, this method can be used to retrieve them. This method should therefore be called at client startup to retrieve any secrets received during the previous session.

    The secrets are guaranteed to have been received over a 1-to-1 encrypted to_device message from one of the user's own verified devices.

    Returns a Promise for a Set of String corresponding to the secret values.

    If the secret is valid and handled, the secret inbox should be cleared by calling delete_secrets_from_inbox.

    Parameters

    • secret_name: string

    Returns Promise<Promise<any>>

  • Get a map holding all the devices of a user.

    • user_id - The unique ID of the user that the device belongs to.

    • timeout_secs - The amount of time we should wait for a /keys/query response before returning if the user's device list has been marked as stale. Note, this assumes that the requests from OlmMachine.outgoingRequests are being processed and sent out.

      If unset, we will return immediately even if the device list is stale.

    A UserDevices object.

    Parameters

    • user_id: UserId
    • Optionaltimeout_secs: number

    Returns Promise<any>

  • Get a verification object for the given user ID with the given flow ID (a to-device request ID if the verification has been requested by a to-device request, or a room event ID if the verification has been requested by a room event).

    It returns a “Verification object”, which is either a Sas or Qr object.

    Parameters

    • user_id: UserId
    • flow_id: string

    Returns any

  • Get a verification request object with the given flow ID.

    Parameters

    • user_id: UserId
    • flow_id: string

    Returns undefined | VerificationRequest

  • Get all the verification requests of a given user.

    Parameters

    Returns any[]

  • Import the given room keys into our store.

    Arguments

    • backed_up_room_keys: keys that were retrieved from backup and that should be added to our store (provided they are better than our current versions of those keys). Specifically, it should be a Map from RoomId, to a Map from session ID to a (decrypted) session data structure.

    • progress_listener: an optional callback that takes 3 arguments: progress (the number of keys that have successfully been imported), total (the total number of keys), and failures (the number of keys that failed to import), and returns nothing.

    Returns

    A RoomKeyImportResult.

    Parameters

    • backed_up_room_keys: Map<any, any>
    • progress_listener: undefined | Function
    • backup_version: string

    Returns Promise<any>

  • Import our private cross signing keys.

    The keys should be provided as unpadded-base64-encoded strings.

    Returns a CrossSigningStatus.

    Parameters

    • Optionalmaster_key: string
    • Optionalself_signing_key: string
    • Optionaluser_signing_key: string

    Returns Promise<any>

  • Import the given room keys into our store.

    exported_keys is a JSON-encoded list of previously exported keys that should be imported into our store. If we already have a better version of a key, the key will not be imported.

    progress_listener is a closure that takes 2 BigInt arguments: progress and total, and returns nothing.

    Returns a RoomKeyImportResult.

    Parameters

    • exported_room_keys: string
    • progress_listener: Function

    Returns Promise<any>

  • Import the given room keys into our store.

    Mostly, a deprecated alias for importExportedRoomKeys, though the return type is different.

    Returns a String containing a JSON-encoded object, holding three properties:

    • total_count (the total number of keys found in the export data).
    • imported_count (the number of keys that were imported).
    • keys (the keys that were imported; a map from room id to a map of the sender key to a list of session ids).

    Parameters

    • exported_room_keys: string
    • progress_listener: Function

    Returns Promise<any>

    Use importExportedRoomKeys or importBackedUpRoomKeys.

  • Import and persists secrets from a SecretsBundle.

    This method will import all the private cross-signing keys and, if available, the private part of a backup key and its accompanying version into the store.

    Warning: Only import this from a trusted source, i.e. if an existing device is sharing this with a new device. The imported cross-signing keys will create a OwnUserIdentity and mark it as verified.

    The backup key will be persisted in the store and can be enabled using the BackupMachine.

    The provided SecretsBundle is freed by this method; be careful not to use it once this method has been called.

    Parameters

    Returns Promise<void>

  • Invalidate the currently active outbound group session for the given room.

    Returns true if a session was invalidated, false if there was no session to invalidate.

    Parameters

    Returns Promise<any>

  • Are we able to encrypt room keys.

    This returns true if we have an active BackupKey and backup version registered with the state machine.

    Returns Promise<bool>.

    Returns Promise<any>

  • Mark all tracked users as dirty.

    All users whose device lists we are tracking are flagged as needing a key query. Users whose devices we are not tracking are ignored.

    Returns Promise<void>

  • Mark the request with the given request ID as sent (see outgoing_requests).

    Arguments are:

    • request_id represents the unique ID of the request that was sent out. This is needed to couple the response with the now sent out request.
    • response_type represents the type of the request that was sent out.
    • response represents the response that was received from the server after the outgoing request was sent out.

    Parameters

    • request_id: string
    • request_type: RequestType
    • response: string

    Returns Promise<any>

  • Generate an "out-of-band" key query request for the given set of users.

    This can be useful if we need the results from getIdentity or getUserDevices to be as up-to-date as possible.

    Returns a KeysQueryRequest object. The response of the request should be passed to the OlmMachine with the mark_request_as_sent.

    Items inside users will be invalidated by this method. Be careful not to use the UserIds after this method has been called.

    Parameters

    Returns KeysQueryRequest

  • Handle to-device events and one-time key counts from a sync response.

    This will decrypt and handle to-device events returning the decrypted versions of them.

    To decrypt an event from the room timeline call decrypt_room_event.

    Arguments

    • to_device_events: the JSON-encoded to-device evens from the /sync response
    • changed_devices: the mapping of changed and left devices, from the /sync response
    • one_time_keys_counts: The number of one-time keys on the server, from the /sync response. A Map from string (encryption algorithm) to number (number of keys).
    • unused_fallback_keys: Optionally, a Set of unused fallback keys on the server, from the /sync response. If this is set, it is used to determine if new fallback keys should be uploaded.

    Returns

    A list of JSON strings, containing the decrypted to-device events.

    Parameters

    • to_device_events: string
    • changed_devices: DeviceLists
    • one_time_keys_counts: Map<any, any>
    • Optionalunused_fallback_keys: Set<any>

    Returns Promise<any>

  • Receive a verification event.

    This method can be used to pass verification events that are happening in rooms to the OlmMachine. The event should be in the decrypted form.

    Parameters

    Returns Promise<any>

  • Register a callback which will be called whenever there is an update to a device.

    callback should be a function that takes a single argument (an array of user IDs as strings) and returns a Promise.

    Parameters

    • callback: Function

    Returns Promise<void>

  • Register a callback which will be called whenever a secret (m.secret.send) is received.

    The only secret this will currently broadcast is the m.megolm_backup.v1 (the cross signing secrets are handled internally).

    To request a secret from other devices, a client sends an m.secret.request device event with action set to request and name set to the identifier of the secret. A device that wishes to share the secret will reply with an m.secret.send event, encrypted using olm.

    The secrets are guaranteed to have been received over a 1-to-1 encrypted to_device message from a one of the user's own verified devices.

    See https://matrix-org.github.io/matrix-rust-sdk/matrix_sdk_crypto/store/struct.Store.html#method.secrets_stream for more information.

    callback should be a function that takes 2 arguments: the secret name (string) and value (string).

    Note: if the secret is valid and handled on the javascript side, the secret inbox should be cleared by calling delete_secrets_from_inbox.

    Parameters

    • callback: Function

    Returns Promise<void>

  • Register a callback which will be called whenever we receive a notification that some room keys have been withheld.

    callback should be a function that takes a single argument (an array of RoomKeyWithheldInfo) and returns a Promise.

    Parameters

    • callback: Function

    Returns Promise<void>

  • Register a callback which will be called whenever there is an update to a room key.

    callback should be a function that takes a single argument (an array of RoomKeyInfo) and returns a Promise.

    Parameters

    • callback: Function

    Returns Promise<void>

  • Register a callback which will be called whenever there is an update to a user identity.

    callback should be a function that takes a single argument (a UserId) and returns a Promise.

    Parameters

    • callback: Function

    Returns Promise<void>

  • Request missing local secrets from our other trusted devices.

    "Local secrets" refers to secrets which can be shared between trusted devices, such as private cross-signing keys, and the megolm backup decryption key.

    This method will cause the sdk to generated outgoing secret requests (m.secret.request) to get the missing secrets. These requests will then be returned by a future call to OlmMachine#outgoing_requests.

    Returns

    A Promise for a bool result, which will be true if secrets were missing, and a request was generated.

    Returns Promise<Promise<any>>

  • Get the number of backed up room keys and the total number of room keys. Returns a RoomKeyCounts.

    Returns Promise<any>

  • Store the backup decryption key in the crypto store.

    This is useful if the client wants to support gossiping of the backup key.

    Returns Promise<void>.

    Parameters

    Returns Promise<any>

  • Store encryption settings for the given room.

    This method checks if the new settings are "safe" -- ie, that they do not represent a downgrade in encryption security from any previous settings. Attempts to downgrade security will result in an error.

    If the settings are valid, they will be persisted to the crypto store. These settings are not used directly by this library, but the saved settings can be retrieved via #getRoomSettings.

    Parameters

    Returns Promise<void>

  • Get to-device requests to share a room key with users in a room.

    room_id is the room ID. users is an array of UserId objects. encryption_settings are an EncryptionSettings object.

    Note: Care should be taken that only one such request at a time is in flight for the same room, e.g. using a lock.

    Returns an array of ToDeviceRequests.

    Items inside users will be invalidated by this method. Be careful not to use the UserIds after this method has been called.

    Parameters

    Returns Promise<any>

  • Sign the given message using our device key and if available cross-signing master key.

    Parameters

    • message: string

    Returns Promise<any>

  • Get the list of users whose devices we are currently tracking.

    A user can be marked for tracking using the update_tracked_users method.

    Returns a Set<UserId>.

    Returns Promise<any>

  • Update the list of tracked users.

    The OlmMachine maintains a list of users whose devices we are keeping track of: these are known as "tracked users". These must be users that we share a room with, so that the server sends us updates for their device lists.

    Arguments

    • users - An array of user ids that should be added to the list of tracked users

    Any users that hadn't been seen before will be flagged for a key query immediately, and whenever receive_sync_changes receives a "changed" notification for that user in the future.

    Users that were already in the list are unaffected.

    Items inside users will be invalidated by this method. Be careful not to use the UserIds after this method has been called.

    Parameters

    Returns Promise<any>

  • Check if the given backup has been verified by us or by another of our devices that we trust.

    The backup_info should be a Javascript object with the following format:

    {
    "algorithm": "m.megolm_backup.v1.curve25519-aes-sha2",
    "auth_data": {
    "public_key":"XjhWTCjW7l59pbfx9tlCBQolfnIQWARoKOzjTOPSlWM",
    "signatures": {}
    }
    }

    Returns a SignatureVerification object.

    Parameters

    • backup_info: any

    Returns Promise<any>

  • Try to decrypt a reader into a list of exported room keys.

    encrypted_exported_room_keys is the result from encrypt_exported_room_keys. passphrase is the passphrase that was used when calling encrypt_exported_room_keys.

    Parameters

    • encrypted_exported_room_keys: string
    • passphrase: string

    Returns string

  • Encrypt the list of exported room keys using the given passphrase.

    exported_room_keys is a list of sessions that should be encrypted (it's generally returned by export_room_keys). passphrase is the passphrase that will be used to encrypt the exported room keys. And rounds is the number of rounds that should be used for the key derivation when the passphrase gets turned into an AES key. More rounds are increasingly computationnally intensive and as such help against brute-force attacks. Should be at least 10_000, while values in the 100_000 ranges should be preferred.

    Parameters

    • exported_room_keys: string
    • passphrase: string
    • rounds: number

    Returns string

  • Create a new OlmMachine backed by an existing store.

    Arguments

    • user_id - represents the unique ID of the user that owns this machine.

    • device_id - represents the unique ID of the device that owns this machine.

    • store_handle - the connection to the crypto store to be used for this machine.

    Parameters

    Returns Promise<any>

  • Create a new OlmMachine.

    The created machine will keep the encryption keys either in a IndexedDB based store, or in a memory store and once the objects is dropped, the keys will be lost.

    Arguments

    • user_id - represents the unique ID of the user that owns this machine.

    • device_id - represents the unique ID of the device that owns this machine.

    • store_name - The name that should be used to open the IndexedDB based database. If this isn't provided, a memory-only store will be used. Note the memory-only store will lose your E2EE keys when the OlmMachine gets dropped.

    • store_passphrase - The passphrase that should be used to encrypt the IndexedDB-based store.

    Parameters

    • user_id: UserId
    • device_id: DeviceId
    • Optionalstore_name: string
    • Optionalstore_passphrase: string

    Returns Promise<any>