import { MatrixClient } from "../MatrixClient"; import { IMegolmEncrypted, IOlmEncrypted, IToDeviceMessage, OTKAlgorithm, OTKCounts, Signatures } from "../models/Crypto"; import { EncryptedRoomEvent } from "../models/events/EncryptedRoomEvent"; import { RoomEvent } from "../models/events/RoomEvent"; import { EncryptedFile } from "../models/events/MessageEvent"; import { BackupManager, KeyBackupInfo, BackupTrustInfo } from "./BackupManager"; /** * Configuration options for the crypto client. */ export interface CryptoClientConfig { /** * Base64-encoded recovery key for key backup. * If provided, enables automatic key backup and recovery, and is also used * (as a passphrase) to protect the cross-signing identity in Secret * Storage so that the identity survives crypto store resets. */ recoveryKey?: string; } /** * Manages encryption for a MatrixClient. Get an instance from a MatrixClient directly * rather than creating one manually. * @category Encryption */ export declare class CryptoClient { private client; private ready; private deviceId; private deviceEd25519; private deviceCurve25519; private roomTracker; private engine; private backupManager; private config; private roomScanTimer; private roomScanDelayMs; constructor(client: MatrixClient, config?: CryptoClientConfig); private get storage(); /** * The device ID for the MatrixClient. */ get clientDeviceId(): string; /** * The device's Ed25519 identity */ get clientDeviceEd25519(): string; /** * Whether or not the crypto client is ready to be used. If not ready, prepare() should be called. * @see prepare */ get isReady(): boolean; /** * Prepares the crypto client for usage. * @param {string[]} roomIds The room IDs the MatrixClient is joined to. */ prepare(roomIds: string[]): Promise; /** * Handles a room event. * @internal * @param roomId The room ID. * @param event The event. */ onRoomEvent(roomId: string, event: any): Promise; /** * Handles a room join. * @internal * @param roomId The room ID. */ onRoomJoin(roomId: string): Promise; /** * Cancels the deferred room scan scheduled by prepare(). Call when * shutting the client down. */ cancelDeferredRoomScan(): void; /** * Checks if a room is encrypted. * @param {string} roomId The room ID to check. * @param {boolean} failClosed When true, a failure to determine the room's * encryption state throws instead of returning false. Use on paths where a * wrong "not encrypted" answer would leak plaintext into an encrypted room. * @returns {Promise} Resolves to true if encrypted, false otherwise. */ isRoomEncrypted(roomId: string, failClosed?: boolean): Promise; /** * Updates the client's sync-related data. * @param {Array.>} toDeviceMessages The to-device messages received. * @param {OTKCounts} otkCounts The current OTK counts. * @param {OTKAlgorithm[]} unusedFallbackKeyAlgs The unused fallback key algorithms. * @param {string[]} changedDeviceLists The user IDs which had device list changes. * @param {string[]} leftDeviceLists The user IDs which the server believes we no longer need to track. * @returns {Promise} Resolves when complete. */ updateSyncData(toDeviceMessages: IToDeviceMessage[], otkCounts: OTKCounts, unusedFallbackKeyAlgs: OTKAlgorithm[], changedDeviceLists: string[], leftDeviceLists: string[]): Promise; /** * Signs an object using the device keys. * @param {object} obj The object to sign. * @returns {Promise} The signatures for the object. */ sign(obj: object): Promise; /** * Encrypts the details of a room event, returning an encrypted payload to be sent in an * `m.room.encrypted` event to the room. If needed, this function will send decryption keys * to the appropriate devices in the room (this happens when the Megolm session rotates or * gets created). * @param {string} roomId The room ID to encrypt within. If the room is not encrypted, an * error is thrown. * @param {string} eventType The event type being encrypted. * @param {any} content The event content being encrypted. * @returns {Promise} Resolves to the encrypted content for an `m.room.encrypted` event. */ encryptRoomEvent(roomId: string, eventType: string, content: any): Promise; /** * Decrypts a room event. Currently only supports Megolm-encrypted events (default for this SDK). * * If decryption fails due to a missing key and key backup is enabled, this method will * automatically attempt to fetch the missing key from the backup and retry decryption. * * @param {EncryptedRoomEvent} event The encrypted event. * @param {string} roomId The room ID where the event was sent. * @returns {Promise>} Resolves to a decrypted room event, or rejects/throws with * an error if the event is undecryptable. */ decryptRoomEvent(event: EncryptedRoomEvent, roomId: string): Promise>; /** * Internal method to perform the actual decryption. */ private doDecryptRoomEvent; /** * Encrypts a file for uploading in a room, returning the encrypted data and information * to include in a message event (except media URL) for sending. * @param {Buffer} file The file to encrypt. * @returns {{buffer: Buffer, file: Omit}} Resolves to the encrypted * contents and file information. */ encryptMedia(file: Buffer): Promise<{ buffer: Buffer; file: Omit; }>; /** * Decrypts a previously-uploaded encrypted file, validating the fields along the way. * @param {EncryptedFile} file The file to decrypt. * @returns {Promise} Resolves to the decrypted file contents. */ decryptMedia(file: EncryptedFile): Promise; /** * Ensures the client's user has a cross-signing identity published, restoring * it from Secret Storage when possible and bootstrapping a new one otherwise. * Sharing room history (MSC4268) requires this: key bundles are only ever * distributed identity-based, and the crypto layer refuses to send them when * our own cross-signing is not set up. * * When a recovery key is configured, the cross-signing private keys are kept * in Secret Storage (encrypted with a key derived from the recovery key), so * that a crypto store reset restores the SAME identity instead of minting a * new one — recipients would otherwise see the bot's identity change. * * The initial upload of cross-signing keys requires no user-interactive auth * when the account has no existing keys (MSC3967), so this works for bots and * appservice users. */ ensureCrossSigningBootstrapped(): Promise; /** * Make sure our own device carries a signature from our self-signing key, * signing and uploading one if needed. Recipients only trust key bundles * (and other identity-bound messages) from cross-signed devices. */ private ensureOwnDeviceCrossSigned; /** * Make sure the cross-signing private keys are stored in Secret Storage, * exporting them if they are not there yet. */ private ensureCrossSigningPersisted; /** * Fetch the default Secret Storage key described in account data, unlocked * with the configured recovery key. Returns null when no key is set up. */ private getSecretStorageKey; /** * Fetch the default Secret Storage key, creating (and publishing) one derived * from the recovery key if none exists yet. */ private getOrCreateSecretStorageKey; /** * Attempt to import the cross-signing private keys from Secret Storage. * Importing also self-signs this device; the resultant signature is uploaded. * @returns True when the identity was restored. */ private tryRestoreCrossSigningFromSecretStorage; /** * Encrypt the cross-signing private keys with the Secret Storage key and * publish them to account data. */ private persistCrossSigningToSecretStorage; /** * Record that we have accepted an invite for the given room, so that an * MSC4268 room key bundle arriving from the inviter soon should be accepted. * @param {string} roomId The room we were invited to. * @param {string} inviter The user who invited us. */ markRoomAsPendingKeyBundle(roomId: string, inviter: string): Promise; /** * Having accepted an invite for the given room from the given user, attempt * to find information about a room key bundle and, if found, download the * bundle and import the room keys, as per * [MSC4268](https://github.com/matrix-org/matrix-spec-proposals/pull/4268). * * The bundle is only imported when the crypto layer can attribute it to the * inviter with sufficient trust (the sending device must be cross-signed by * the inviter). * @param {string} roomId The room we were invited to. * @param {string} inviter The user who invited us and is expected to have sent the bundle. * @returns {Promise} True if a bundle was found, downloaded and imported. */ maybeAcceptKeyBundle(roomId: string, inviter: string): Promise; /** * Shares any shareable encrypted room history with the given user, as per * [MSC4268](https://github.com/matrix-org/matrix-spec-proposals/pull/4268). * Call this immediately before inviting the user to the room, so that the * key bundle is waiting for them when they accept. * * No-ops when the room is unencrypted, when its *current* history visibility * does not permit sharing (`joined`/`invited`), or when there are no * shareable keys. Note that only megolm sessions flagged with * `shared_history` (created by clients with MSC4268 support while the room * visibility allowed it) are included; the recipient's devices must be * cross-signed by the recipient to receive the bundle. * @param {string} roomId The room to share history for. * @param {string} userId The user to share history with. */ shareRoomHistoryWithUser(roomId: string, userId: string): Promise; /** * Check if key backup is enabled. * @returns True if key backup is enabled and active. */ isKeyBackupEnabled(): Promise; /** * Get the current backup version info from the server. * @returns The backup info or null if no backup exists. */ getKeyBackupInfo(): Promise; /** * Get the currently active backup version. * @returns The backup version string or null if backup is not active. */ getActiveBackupVersion(): Promise; /** * Get the current room key backup progress. * @returns The total and backed up key counts. */ getKeyBackupProgress(): Promise<{ total: number; backedUp: number; } | null>; /** * Manually trigger a check for key backup on the server and enable if trusted. * This is automatically called during prepare() if a recovery key is configured. * @returns The backup info and trust status, or null if no usable backup. */ checkKeyBackupAndEnable(): Promise<{ backupInfo: KeyBackupInfo; trustInfo: BackupTrustInfo; } | null>; /** * Get the backup manager instance for advanced operations. * @returns The BackupManager or null if not configured. */ getBackupManager(): BackupManager | null; }