### Install matrix-sdk-crypto-wasm with npm Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/README.md Install the library using npm. This is the first step to integrate E2EE into your project. ```bash npm install --save @matrix-org/matrix-sdk-crypto-wasm ``` -------------------------------- ### Install matrix-sdk-crypto-wasm with pnpm Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/README.md Install the library using pnpm. This is an alternative package manager for project integration. ```bash pnpm add @matrix-org/matrix-sdk-crypto-wasm ``` -------------------------------- ### Initialize matrix-sdk-crypto-wasm in JavaScript Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/README.md Import and initialize the library asynchronously before use. This example shows how to set up tracing and create an OlmMachine with an in-memory store. ```javascript import { initAsync, Tracing, LoggerLevel, OlmMachine, UserId, DeviceId } from "@matrix-org/matrix-sdk-crypto-wasm"; async function loadCrypto(userId, deviceId) { // Do this before any other calls to the library await initAsync(); // Optional: enable tracing in the rust-sdk new Tracing(LoggerLevel.Trace).turnOn(); // Create a new OlmMachine // // The following will use an in-memory store. It is recommended to use // indexedDB where that is available. // See https://matrix.org/github.io/matrix-sdk-crypto-wasm/classes/OlmMachine.html#initialize const olmMachine = await OlmMachine.initialize(new UserId(userId), new DeviceId(deviceId)); return olmMachine; } ``` -------------------------------- ### Enable and Configure Debug Logging Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/configuration.md Example of enabling debug logging by creating a Tracing instance with LoggerLevel.Debug, turning it on, and then initializing the OlmMachine. ```javascript import { Tracing, LoggerLevel } from "@matrix-org/matrix-sdk-crypto-wasm"; // Create and activate tracing const tracing = new Tracing(LoggerLevel.Debug); tracing.turnOn(); // Now initialize OlmMachine (will log debug info) const machine = await OlmMachine.initialize(userId, deviceId); // Later: change log level tracing.setMinLogLevel(LoggerLevel.Info); // Or disable entirely tracing.turnOff(); ``` -------------------------------- ### EncryptionSettings Example Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/encryption-and-requests.md Demonstrates how to instantiate and configure EncryptionSettings. Adjust algorithm, rotation period, and message limits to control session management and key distribution. ```javascript const settings = new EncryptionSettings(); settings.algorithm = EncryptionAlgorithm.MegolmV1AesSha2; settings.rotationPeriod = 604800000000; // 7 days in microseconds settings.rotationPeriodMessages = 100; ``` -------------------------------- ### MegolmDecryptionError Example Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/errors.md Demonstrates how to catch and handle MegolmDecryptionError, including checking for withheld information. ```javascript try { const decrypted = await machine.decryptRoomEvent(event, roomId, settings); } catch (error) { if (error instanceof MegolmDecryptionError) { console.log(`Error: ${error.code} - ${error.description}`); if (error.maybeWithheld) { console.log(`Withheld: ${error.maybeWithheld}`); } } } ``` -------------------------------- ### Build matrix-sdk-crypto-wasm Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/README.md Build the WebAssembly bindings using pnpm after installing Rust and Node.js. The output is generated in the 'pkg/' directory. ```bash pnpm install pnpm build # or 'pnpm build:dev' to make an unoptimised build pnpm test ``` -------------------------------- ### Initialize OlmMachine Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/types.md Initializes a new OlmMachine instance, either from scratch or by loading from a store. Use this to start E2EE operations. ```typescript class OlmMachine { static initialize( userId: UserId, deviceId: DeviceId, storeName?: string, storePassphrase?: string, logger?: JsLogger ): Promise; static initFromStore( userId: UserId, deviceId: DeviceId, storeHandle: StoreHandle, logger?: JsLogger ): Promise; } ``` -------------------------------- ### Enable Room Key Forwarding Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/configuration.md Example of enabling room key forwarding to allow sharing keys with verified devices. ```javascript // Enable to allow sharing keys with verified devices machine.roomKeyForwardingEnabled = true; // Devices we trust will now receive keys they request ``` -------------------------------- ### Async/Promise-Based Encryption Example Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/README.md Illustrates the asynchronous nature of encryption operations using Promises. It shows how to encrypt a room event and retrieve device information. ```javascript const encrypted = await machine.encryptRoomEvent(roomId, eventType, content); const device = await machine.getDevice(userId, deviceId); ``` -------------------------------- ### Get Library Versions Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/README.md Use `getVersions()` to retrieve build information about the cryptography library, core crypto, and build details. ```javascript const versions = getVersions(); console.log(versions.vodozemac); // Cryptography library version console.log(versions.matrix_sdk_crypto); // Core crypto version console.log(versions.git_sha); // Build commit console.log(versions.git_description); // Build description ``` -------------------------------- ### Signature Verification Example Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/vodozemac.md Shows how to create an Ed25519 signature object and retrieve the base64 representation of a public key for verification purposes. ```javascript // Verify a signature from a device const signature = new Ed25519Signature(signatureBase64); const pubKey = device.getRawEd25519Key(); // The actual verification is done by OlmMachine // These types are primarily for inspection and serialization console.log(signature.toBase64()); console.log(pubKey.toBase64()); ``` -------------------------------- ### Get User Devices Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/device-and-verification.md Retrieves an iterator for all devices belonging to a user. ```typescript devices(): Device[] ``` -------------------------------- ### Get DeviceKeyAlgorithm name Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/identifiers.md Retrieve the name of the key algorithm from a DeviceKeyAlgorithm object. ```typescript get name(): DeviceKeyAlgorithmName ``` -------------------------------- ### Check and Disable Room Key Requests Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/configuration.md Example of checking the current status of room key requests and disabling them if necessary. ```javascript // Check if enabled if (machine.roomKeyRequestsEnabled) { console.log("Devices will request room keys for missed messages"); } // Disable if needed machine.roomKeyRequestsEnabled = false; ``` -------------------------------- ### Registering Callbacks for Streams Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/README.md Example of registering a callback function to receive updates for specific events, such as room key updates. The callback is executed asynchronously when new data is available. ```javascript machine.registerRoomKeyUpdatedCallback(async (roomKeyInfos) => { console.log(`Received ${roomKeyInfos.length} new room keys`); }); ``` -------------------------------- ### Implement File Logging with JsLogger Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/configuration.md Example implementation of the JsLogger interface for writing log messages to a file or IndexedDB, including timestamping and formatting. ```javascript class FileLogger { async debug(data) { await this.write('DEBUG', data); } async info(data) { await this.write('INFO', data); } async warn(data) { await this.write('WARN', data); } async error(data) { await this.write('ERROR', data); } async write(level, data) { const timestamp = new Date().toISOString(); const message = typeof data === 'object' ? JSON.stringify(data) : String(data); // Write to file or IndexedDB log } } const machine = await OlmMachine.initialize( userId, deviceId, "store", "passphrase", new FileLogger() ); ``` -------------------------------- ### Get Backup Keys Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Retrieves the backup decryption key and version stored in the crypto store. ```typescript getBackupKeys(): Promise ``` -------------------------------- ### EncryptionSettings Constructor Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/encryption-and-requests.md Creates a new EncryptionSettings object with default values. This is the starting point for configuring encryption for a Matrix room. ```typescript constructor(): EncryptionSettings ``` -------------------------------- ### Get Algorithm from Megolm V1 Backup Key Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/backup-and-store.md Retrieves the full name of the backup algorithm, such as 'm.megolm_backup.v1.curve25519-aes-sha2'. ```typescript get algorithm(): string ``` -------------------------------- ### Initiate Device Verification Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/README.md Starts the process of verifying another device. This involves requesting verification, sending a ToDevice request, and then displaying verification details to the user. ```javascript const verification = await device.requestVerification(); await sendToServer(verification.to_device_request); const sas = verification.getSas(); // or getQr() ``` -------------------------------- ### Get Public Key Base64 from Megolm V1 Backup Key Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/backup-and-store.md Retrieves the base64-encoded public key from a Megolm V1 backup key. ```typescript get publicKeyBase64(): string ``` -------------------------------- ### Invalidating Input Objects Example Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/README.md Demonstrates how certain SDK methods invalidate their input objects after execution. It shows the safe practice of creating new instances for subsequent operations. ```javascript // After calling this, don't reuse the userId objects await machine.updateTrackedUsers(userIds); // Safe way: create new instances for subsequent use const clone = userId.clone(); ``` -------------------------------- ### Get Decryption Key Base64 (Deprecated) Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/backup-and-store.md Deprecated method to get the base64-encoded decryption key. Use `decryptionKey.toBase64()` instead. ```typescript get decryptionKeyBase64(): string | undefined ``` -------------------------------- ### Initialize OlmMachine from Existing Store Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/configuration.md Use this method when you need more control over store opening, providing a pre-opened StoreHandle. A custom logger can also be supplied. ```javascript // Open store with custom key (32 bytes) const storeKey = new Uint8Array(32); crypto.getRandomValues(storeKey); const store = await StoreHandle.openWithKey("my_store", storeKey); const machine = await OlmMachine.initFromStore(userId, deviceId, store); ``` -------------------------------- ### Get Device ID from OlmMachine Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Retrieves the unique device ID that identifies the OlmMachine instance. Use the toString() method to get the string representation. ```javascript const deviceId = machine.deviceId; console.log(deviceId.toString()); // "ALICEID" ``` -------------------------------- ### Get User ID from OlmMachine Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Retrieves the unique user ID associated with the OlmMachine instance. Use the toString() method to get the string representation. ```javascript const userId = machine.userId; console.log(userId.toString()); // "@alice:example.com" ``` -------------------------------- ### Get All Devices for a User Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Fetches all devices associated with a user ID. An optional timeout can be provided for key queries if the device list is stale. ```typescript getUserDevices( userId: UserId, timeoutSecs?: number ): Promise ``` -------------------------------- ### Generate Documentation Locally Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/README.md Run this command to generate the project's documentation locally. The output will be placed in the './docs' directory. ```sh pnpm doc ``` -------------------------------- ### Get RoomId localpart Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/identifiers.md Retrieve the localpart of a RoomId (the part between '!' and ':'). ```typescript get localpart(): string ``` -------------------------------- ### Initialize with Persistent Storage Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/README.md Demonstrates how to initialize the crypto module with persistent IndexedDB storage for production environments. This ensures trust state is maintained across sessions. ```javascript const cryptostore = await IndexedDb.new("my_store_name", "my_passphrase"); const machine = await RustCrypto.new(cryptostore); // ... use machine ``` -------------------------------- ### Get DeviceKeyId deviceId Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/identifiers.md Retrieve the device ID from a DeviceKeyId object. ```typescript get deviceId(): DeviceId ``` -------------------------------- ### OlmMachine.initFromStore Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Creates a new OlmMachine instance backed by an existing crypto store. This is useful for resuming a session with previously stored cryptographic data. ```APIDOC ## OlmMachine.initFromStore ### Description Create a new `OlmMachine` backed by an existing store. ### Method `static initFromStore(userId: UserId, deviceId: DeviceId, storeHandle: StoreHandle, logger?: JsLogger): Promise` ### Parameters #### Path Parameters - **userId** (UserId) - Required - Unique ID of the user that owns this machine - **deviceId** (DeviceId) - Required - Unique ID of the device that owns this machine - **storeHandle** (StoreHandle) - Required - Connection to an existing crypto store - **logger** (JsLogger) - Optional - Optional logger instance ### Returns Promise resolving to an `OlmMachine` instance ``` -------------------------------- ### Get DeviceKeyId algorithm Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/identifiers.md Retrieve the key algorithm from a DeviceKeyId object. ```typescript get algorithm(): DeviceKeyAlgorithm ``` -------------------------------- ### Handle Store Initialization Errors Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/errors.md Illustrates a pattern for initializing the OlmMachine, catching specific store-related errors like incorrect passphrase or key size, and providing user-friendly messages. ```javascript async function initMachine(userId, deviceId, storeName, passphrase) { try { const machine = await OlmMachine.initialize( userId, deviceId, storeName, passphrase ); return machine; } catch (error) { if (error.message.includes("passphrase")) { console.error("Incorrect passphrase"); } else if (error.message.includes("key of length 32")) { console.error("Invalid store key size"); } else { console.error("Store initialization failed:", error.message); } return null; } } ``` -------------------------------- ### Convert UserId to string Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/identifiers.md Get the string representation of a UserId object. ```typescript toString(): string ``` -------------------------------- ### Get UserId localpart Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/identifiers.md Retrieve the localpart of a UserId (the part before the colon). ```javascript const user = new UserId("@alice:example.com"); console.log(user.localpart); // "alice" ``` -------------------------------- ### OlmMachine.initialize Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Creates a new OlmMachine instance. It can optionally use a persistent IndexedDB store if a storeName is provided, otherwise it defaults to an in-memory store. ```APIDOC ## OlmMachine.initialize ### Description Create a new `OlmMachine` instance. ### Method `static initialize(userId: UserId, deviceId: DeviceId, storeName?: string, storePassphrase?: string, logger?: JsLogger): Promise` ### Parameters #### Path Parameters - **userId** (UserId) - Required - Unique ID of the user that owns this machine - **deviceId** (DeviceId) - Required - Unique ID of the device that owns this machine - **storeName** (string) - Optional - Name for IndexedDB-based store. If not provided, uses in-memory store - **storePassphrase** (string) - Optional - Passphrase to encrypt the IndexedDB-based store - **logger** (JsLogger) - Optional - Optional logger instance for tracing operations ### Returns Promise resolving to an `OlmMachine` instance ### Example ```javascript import { OlmMachine, UserId, DeviceId, initAsync } from "@matrix-org/matrix-sdk-crypto-wasm"; async function createMachine() { await initAsync(); const machine = await OlmMachine.initialize( new UserId("@alice:example.com"), new DeviceId("ALICEID"), "crypto_store", "my-passphrase" ); return machine; } ``` ``` -------------------------------- ### Get Cross-Signing Status Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Retrieves the current status of the private cross-signing keys. ```typescript crossSigningStatus(): Promise ``` -------------------------------- ### Set Up Cross-Signing Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/README.md Generates the necessary cross-signing keys for a user. This typically involves bootstrapping the keys and then uploading them to the Matrix server. ```javascript await machine.bootstrapCrossSigning(); // Send upload requests to the server ``` -------------------------------- ### Initialize OlmMachine (Persistent with Encryption) Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/configuration.md Configure a persistent store using IndexedDB with encryption. Provide a store name and a passphrase to protect the stored keys. ```javascript const machine = await OlmMachine.initialize( new UserId("@alice:example.com"), new DeviceId("ALICEID"), "crypto_store_v1", "user-provided-passphrase" ); ``` -------------------------------- ### Get Verification Request State Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/device-and-verification.md Retrieves the current state of the verification request. ```typescript get state(): VerificationRequestState ``` -------------------------------- ### Get RoomId serverName Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/identifiers.md Retrieve the server name (homeserver) from a RoomId object. ```typescript get serverName(): ServerName ``` -------------------------------- ### Recommended Production Initialization Pattern Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/configuration.md A comprehensive asynchronous function for initializing the crypto module in production, handling WASM loading, logging configuration, and store initialization with options for key or passphrase. ```javascript import { initAsync, OlmMachine, UserId, DeviceId, Tracing, LoggerLevel, StoreHandle } from "@matrix-org/matrix-sdk-crypto-wasm"; async function initializeCrypto(userId, deviceId, options = {}) { const { storeName = null, storePassphrase = null, storeKey = null, logLevel = LoggerLevel.Info, enableDebug = false } = options; // Step 1: Load WASM module (must be first) await initAsync(); // Step 2: Configure logging if needed if (enableDebug) { const tracing = new Tracing(logLevel); tracing.turnOn(); } // Step 3: Open or create store let machine; if (storeKey) { // Use explicit key const store = await StoreHandle.openWithKey( storeName || "default", storeKey ); machine = await OlmMachine.initFromStore( new UserId(userId), new DeviceId(deviceId), store ); } else { // Use passphrase or memory machine = await OlmMachine.initialize( new UserId(userId), new DeviceId(deviceId), storeName, storePassphrase ); } // Step 4: Verify initialization console.log("Crypto ready for:", machine.userId.toString()); return machine; } // Usage: const machine = await initializeCrypto( "@alice:example.com", "ALICEID", { storeName: "alice_crypto_v1", storePassphrase: "user_password", logLevel: LoggerLevel.Debug, enableDebug: true } ); ``` -------------------------------- ### Initialize Store with Generated Key Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/configuration.md Demonstrates generating a 32-byte encryption key using `crypto.getRandomValues()` and then opening an IndexedDB store with this key. Remember to save the key securely. ```javascript // Generate or retrieve 32-byte key const storeKey = new Uint8Array(32); crypto.getRandomValues(storeKey); // Open store with explicit key const store = await StoreHandle.openWithKey("my_store", storeKey); // Save key securely (pseudo-code) // await secureStorage.save("crypto_key", storeKey); ``` -------------------------------- ### Get UserId serverName Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/identifiers.md Retrieve the server name (homeserver) from a UserId object. ```javascript const user = new UserId("@alice:example.com"); const server = user.serverName.toString(); // "example.com" ``` -------------------------------- ### Get Self-Signing Key Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/device-and-verification.md Retrieves the JSON representation of the self-signing key for a user identity. ```typescript get selfSigningKey(): string ``` -------------------------------- ### Initialize OlmMachine (In-Memory) Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/configuration.md Use this for development or temporary sessions when persistence is not required. No store name or passphrase is provided, resulting in an in-memory store. ```javascript const machine = await OlmMachine.initialize( new UserId("@alice:example.com"), new DeviceId("ALICEID") // Memory store, no encryption ); ``` -------------------------------- ### Get Master Key Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/device-and-verification.md Retrieves the JSON representation of the master key for a user identity. ```typescript get masterKey(): string ``` -------------------------------- ### Get Verification Request Other Device ID Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/device-and-verification.md Retrieves the device ID of the other party, if known. ```typescript get otherDeviceId(): DeviceId | undefined ``` -------------------------------- ### Get Ed25519PublicKey Length Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/vodozemac.md Returns the fixed byte length of an Ed25519 public key. ```typescript get length(): number ``` -------------------------------- ### Handle Store Opening Errors Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/errors.md Demonstrates how to catch and log errors that occur when opening a store, such as those with incorrect key sizes. ```javascript try { const store = await StoreHandle.openWithKey("name", wrongSizeKey); } catch (error) { console.error("Store error:", error.message); } ``` -------------------------------- ### enableBackupV1 Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Activates a backup key for a specific backup version. Ensure the key is trusted before enabling. ```APIDOC ## enableBackupV1(publicKeyBase64, version) ### Description Activate a backup key for the given backup version. ### Method ```typescript enableBackupV1(publicKeyBase64: string, version: string): Promise ``` ### Parameters #### Path Parameters - **publicKeyBase64** (string) - Required - Public backup key as base64 - **version** (string) - Required - Backup version identifier ### Returns Promise **Warning:** Ensure the backup key is trusted before calling this method. ``` -------------------------------- ### Get Verification Request User ID Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/device-and-verification.md Retrieves the user ID of the other party in the verification request. ```typescript get userId(): UserId ``` -------------------------------- ### StoreHandle.open Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/backup-and-store.md Opens a connection to a cryptographic storage backend, either persistent (IndexedDB) or in-memory. This is crucial for initializing the crypto store. ```APIDOC ## StoreHandle.open ### Description Open a crypto store. ### Method Static method of `StoreHandle`. ### Parameters #### Path Parameters - **storeName** (string) - Optional - IndexedDB store name; if not provided, uses in-memory store - **storePassphrase** (string) - Optional - Passphrase to encrypt IndexedDB store - **logger** (JsLogger) - Optional - Optional logger instance ### Returns - Promise: A promise that resolves to the opened StoreHandle. ### Note Memory stores lose all keys when dropped. Provide a storeName for persistent storage. ### Example ```javascript const store = await StoreHandle.open( "my_crypto_store", "encryption_passphrase" ); const machine = await OlmMachine.initFromStore(userId, deviceId, store); ``` ``` -------------------------------- ### Get SAS Flow ID Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/device-and-verification.md Retrieves the unique ID for the current SAS verification flow. ```typescript get flowId(): string ``` -------------------------------- ### Initialize OlmMachine (Persistent with Custom Logger) Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/configuration.md Initialize the OlmMachine with persistent storage and a custom logger. The logger must implement the JsLogger interface. ```javascript class ConsoleLogger { debug(data) { console.debug(data); } info(data) { console.info(data); } warn(data) { console.warn(data); } error(data) { console.error(data); } } const machine = await OlmMachine.initialize( userId, deviceId, "crypto_store", "passphrase", new ConsoleLogger() ); ``` -------------------------------- ### Get Verification Object Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Retrieves a verification object for a user and flow ID. This function does not return a Promise. ```typescript getVerification( userId: UserId, flowId: string ): Sas | Qr | undefined ``` -------------------------------- ### Get QR Code Matrix URI Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/device-and-verification.md Retrieves the Matrix URI encoded within the QR code. ```typescript getMatrixUri(): string ``` -------------------------------- ### Initialize and Use OlmMachine for E2EE Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/README.md Initializes the WASM module and creates an OlmMachine instance for managing end-to-end encryption. Demonstrates sharing room keys and encrypting/decrypting messages. ```javascript import { initAsync, OlmMachine, UserId, DeviceId, EncryptionSettings, DecryptionSettings, TrustRequirement } from "@matrix-org/matrix-sdk-crypto-wasm"; // Initialize WASM module (required once at startup) await initAsync(); // Create OlmMachine with persistent storage const machine = await OlmMachine.initialize( new UserId("@alice:example.com"), new DeviceId("ALICEID"), "crypto_store", // IndexedDB store name "passphrase" // Optional: encryption passphrase ); // Configure encryption for a room const encSettings = new EncryptionSettings(); encSettings.algorithm = EncryptionAlgorithm.MegolmV1AesSha2; // Share room key with members const shareRequests = await machine.shareRoomKey( new RoomId("!room:example.com"), [new UserId("@bob:example.com")], encSettings ); // Encrypt a message const encrypted = await machine.encryptRoomEvent( new RoomId("!room:example.com"), "m.room.message", JSON.stringify({ body: "Hello!", msgtype: "m.text" }) ); // Decrypt received message const decSettings = new DecryptionSettings(TrustRequirement.Verified); try { const decrypted = await machine.decryptRoomEvent( JSON.stringify(encryptedEvent), new RoomId("!room:example.com"), decSettings ); console.log("Decrypted:", decrypted.content); } catch (error) { console.error("Decryption failed:", error.code, error.description); } ``` -------------------------------- ### Enable Backup Version 1 Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Activates a backup key for a specific backup version. Ensure the backup key is trusted before enabling. ```typescript enableBackupV1(publicKeyBase64: string, version: string): Promise ``` -------------------------------- ### Get SAS Decimal Representation Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/device-and-verification.md Retrieves the decimal representation of the SAS. This is available after both parties have committed to the verification. ```typescript getDecimal(): string | undefined ``` -------------------------------- ### Get SAS Emoji Representation Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/device-and-verification.md Retrieves the emoji representation of the SAS. This is available after both parties have committed to the verification. ```typescript getEmojiIndex(): SasEmoji | undefined ``` -------------------------------- ### Get SAS Room ID Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/device-and-verification.md Retrieves the room ID if the SAS verification is occurring within a room. ```typescript get roomId(): RoomId | undefined ``` -------------------------------- ### OlmMachine.deviceCreationTimeMs Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Retrieves the creation time of the account backing this OlmMachine in milliseconds since the Unix epoch. ```APIDOC ## OlmMachine.deviceCreationTimeMs ### Description Get the time in milliseconds since the Unix epoch when the `Account` backing this `OlmMachine` was created. ### Method `get deviceCreationTimeMs(): number` ### Returns number ``` -------------------------------- ### Accept All Devices for Decryption (Default) Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/configuration.md Initializes `DecryptionSettings` with `TrustRequirement.Untrusted`, allowing messages to be decrypted from any device, including unverified ones. This is the default behavior. ```javascript const settings = new DecryptionSettings(TrustRequirement.Untrusted); const events = await machine.receiveSyncChanges( toDeviceEvents, deviceLists, keysCounts, undefined, settings ); ``` -------------------------------- ### Get Public Key from Secret Key Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/vodozemac.md Retrieves the public key associated with a given secret key. ```typescript get publicKey(): EciesPublicKey ``` -------------------------------- ### Configure Sharing Strategy for Room Keys Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/configuration.md Demonstrates different strategies for sharing room encryption keys with devices. Options include sharing with all devices, only trusted devices, or only cross-signing verified devices. ```typescript // Who receives the room key? // All devices (no verification required) settings.sharingStrategy = CollectStrategy.allDevices(); // Only devices we trust locally settings.sharingStrategy = CollectStrategy.trustedDevices(); // Only devices verified via cross-signing settings.sharingStrategy = CollectStrategy.verifiedDevices(); ``` -------------------------------- ### Check if SAS Verification Started from Request Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/device-and-verification.md Determines if the SAS verification process was initiated by a verification request. ```typescript startedFromRequest(): boolean ``` -------------------------------- ### Get User-Signing Key Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/device-and-verification.md Retrieves the JSON representation of the user-signing key. This is only applicable for the current user's identity. ```typescript get userSigningKey(): string ``` -------------------------------- ### Check Cross-Signing Status and Bootstrap Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/backup-and-store.md Checks the status of stored cross-signing keys and bootstraps them if necessary. Requires the machine object. ```javascript const status = await machine.crossSigningStatus(); if (!status.hasMasterKey) { console.log("Need to bootstrap cross-signing"); const requests = await machine.bootstrapCrossSigning(true); } ``` -------------------------------- ### Default Encryption Settings Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/configuration.md Creates an `EncryptionSettings` object using all default values. This includes the default MegolmV1 algorithm, no state event encryption, a 7-day session rotation period, and sharing keys with all devices. ```javascript const settings = new EncryptionSettings(); // Uses all defaults: MegolmV1, no state encryption, // 7-day rotation, share with all devices ``` -------------------------------- ### Get Active Verification Object Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/device-and-verification.md Retrieves the active verification object, which can be either a SAS or QR code verification. ```typescript getVerification(): Sas | Qr | undefined ``` -------------------------------- ### StoreHandle Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/types.md Manages the connection to the crypto store, with methods for opening the store. ```APIDOC ## StoreHandle ### Description Manages the connection to the crypto store, with methods for opening the store. ### Static Methods - **open(storeName?: string, storePassphrase?: string, logger?: JsLogger): Promise** - Opens the crypto store with the given name and passphrase. - **openWithKey(storeName: string, storeKey: Uint8Array, logger?: JsLogger): Promise** - Opens the crypto store with the given name and key. ``` -------------------------------- ### Get All Verification Requests for a User Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Retrieves all verification requests associated with a given user ID. This function does not return a Promise. ```typescript getVerificationRequests(userId: UserId): VerificationRequest[] ``` -------------------------------- ### StoreHandle.openWithKey() Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/configuration.md Opens an IndexedDB store using an explicit 32-byte encryption key. This method is crucial for initializing encrypted storage with a user-provided key. ```APIDOC ## StoreHandle.openWithKey() ### Description Open a store with explicit 32-byte encryption key. ### Method ```typescript static openWithKey( storeName: string, storeKey: Uint8Array, logger?: JsLogger ): Promise ``` ### Parameters #### Path Parameters - **storeName** (string) - Required - IndexedDB store name - **storeKey** (Uint8Array) - Required - Exactly 32 bytes of encryption key - **logger** (JsLogger) - Optional - Logger for store operations ### Key Management - Key must be exactly 32 bytes - Generate with `crypto.getRandomValues()` in browser - Store key securely (e.g., in secure storage, not in localStorage) - Never commit keys to version control ### Example ```javascript // Generate or retrieve 32-byte key const storeKey = new Uint8Array(32); crypto.getRandomValues(storeKey); // Open store with explicit key const store = await StoreHandle.openWithKey("my_store", storeKey); // Save key securely (pseudo-code) // await secureStorage.save("crypto_key", storeKey); ``` ``` -------------------------------- ### Versions Interface Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/types.md Contains version information for various components of the library, including vodozemac, matrix-sdk-crypto, and git details. ```typescript interface Versions { vodozemac: string; matrix_sdk_crypto: string; git_sha: string; git_description: string; } ``` -------------------------------- ### Get Specific Device by ID Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/device-and-verification.md Retrieves a specific device by its unique ID. Returns the device object or undefined if not found. ```typescript getDevice(deviceId: DeviceId): Device | undefined ``` -------------------------------- ### Import Backed-Up Room Keys Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Imports room keys from a backup. Supports an optional progress listener for updates. ```typescript importBackedUpRoomKeys( backedUpKeys: Map>, progressListener?: (progress: bigint, total: bigint, failures: bigint) => void, backupVersion: string ): Promise ``` -------------------------------- ### Get Megolm V1 Public Key from Backup Key Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/backup-and-store.md Retrieves the public part of this backup key, which is of type MegolmV1BackupKey. ```typescript get megolmV1PublicKey(): MegolmV1BackupKey ``` -------------------------------- ### Import Cross-Signing Keys Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Imports private cross-signing keys. Keys are provided as unpadded base64 strings. ```typescript importCrossSigningKeys( masterKey?: string, selfSigningKey?: string, userSigningKey?: string ): Promise ``` -------------------------------- ### Device Management and Verification Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/device-and-verification.md This section details the methods available on a `Device` object for managing and verifying cryptographic devices of a user. ```APIDOC ## Device Object Represents a cryptographic device of a user capable of End-to-End Encryption (E2EE). ### Properties - **userId** (UserId): The user ID of the device owner. - **deviceId** (DeviceId): The unique ID of the device. - **displayName** (string | undefined): The human-readable name of the device. ### Methods #### `requestVerification([methods])` Request an interactive verification with this device. - **Parameters**: - methods (VerificationMethod[]): Optional. Preferred verification methods (SAS, QR, etc.). - **Returns**: Array containing [VerificationRequest, ToDeviceRequest] #### `encryptToDeviceEvent(eventType, content, [shareStrategy])` Encrypt a to-device message to this device using Olm encryption. - **Parameters**: - eventType (string): Required. Type of the event. - content (any): Required. Event content (will be JSON-serialized). - shareStrategy (CollectStrategy): Optional. Strategy for collecting devices. - **Returns**: Promise resolving to JSON string of encrypted event content. #### `isVerified()` Check if the device is verified (locally or via cross-signing). - **Returns**: boolean #### `isCrossSigningTrusted()` Check if the device is verified using cross-signing. - **Returns**: boolean #### `isCrossSignedByOwner()` Check if the device is cross-signed by its owner. - **Returns**: boolean #### `setLocalTrust(trustState)` Set the local trust state of the device. - **Parameters**: - trustState (LocalTrust): Required. New trust state. - **Returns**: Promise #### `getRawCurve25519Key()` Get the Curve25519 public key. - **Returns**: Curve25519PublicKey #### `getRawEd25519Key()` Get the Ed25519 public key. - **Returns**: Ed25519PublicKey ``` -------------------------------- ### Create a DeviceKeyId Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/identifiers.md Instantiate a DeviceKeyId object from a string. The string must be in the format 'algorithm:device_id'. ```typescript constructor(id: string): DeviceKeyId ``` -------------------------------- ### Bootstrap Cross-Signing Keys and Signatures Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/backup-and-store.md Initiates the cross-signing bootstrap process by uploading public keys and creating device signatures. Requires the machine object and a sendRequest function. ```javascript const requests = await machine.bootstrapCrossSigning(false); // First upload the public keys const uploadResponse = await sendRequest( requests.uploadSigningKeysRequest ); await machine.markRequestAsSent( requests.uploadSigningKeysRequest.id, RequestType.UploadSigningKeys, uploadResponse ); // Then create and send signature uploads // (may need user interactive auth) const sigResponse = await sendRequest( requests.createSignaturesRequest ); ``` -------------------------------- ### Get User Cross-Signing Identity Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Retrieve the cross-signing identity for a given user ID. Returns the identity information or undefined if not found. ```typescript getIdentity(userId: UserId): Promise ``` -------------------------------- ### CollectStrategy.allDevices() Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/encryption-and-requests.md Returns a CollectStrategy that includes all devices, regardless of trust status. Use this when keys should be shared broadly. ```typescript static allDevices(): CollectStrategy ``` -------------------------------- ### importBackedUpRoomKeys Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Imports room keys that have been previously backed up. It takes a map of backed-up keys, an optional progress listener, and the backup version identifier. ```APIDOC ## importBackedUpRoomKeys(backedUpKeys, [progressListener], backupVersion) ### Description Import room keys retrieved from backup. ### Method (Not specified, likely a function call in an SDK) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters - **backedUpKeys** (Map) - Required - Map from RoomId to Map of session ID to session data - **progressListener** (function) - Optional - Optional callback for progress updates - **backupVersion** (string) - Required - Version identifier of the backup ### Response #### Success Response - Resolves to RoomKeyImportResult ### Response Example (Not specified) ``` -------------------------------- ### Get Room Key Counts Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Retrieves the total number of backed up room keys and the total number of available room keys. ```typescript roomKeyCounts(): Promise ``` -------------------------------- ### verifyBackup Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Verifies that a backup has been signed by a trusted device using the provided backup information. ```APIDOC ## verifyBackup(backupInfo) ### Description Verify that a backup has been signed by a trusted device. ### Method ```typescript verifyBackup(backupInfo: object): Promise ``` ### Parameters #### Path Parameters - **backupInfo** (object) - Required - Backup info with algorithm and auth_data ### Returns Promise resolving to SignatureVerification. ``` -------------------------------- ### Ed25519PublicKey Class Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/types.md Represents an Ed25519 public key used for signatures. Provides methods to get its length and convert it to a base64 string. ```typescript class Ed25519PublicKey { get length(): number; toBase64(): string; } ``` -------------------------------- ### CollectStrategy.verifiedDevices() Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/encryption-and-requests.md Returns a CollectStrategy that includes only devices verified via cross-signing. This is the most secure option for key sharing. ```typescript static verifiedDevices(): CollectStrategy ``` -------------------------------- ### Qr Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/types.md Handles QR code based device verification. ```APIDOC ## Class: Qr ### Description QR code verification. ### Methods #### `renderSvg(): string` Renders the QR code as an SVG string. #### `getMatrixUri(): string` Gets the Matrix URI for the QR code. #### `reciprocationNeeded(): boolean` Checks if reciprocation is needed. #### `reciprocate(): Promise<[VerificationRequest, OutgoingVerificationRequest] | undefined>` Reciprocates the QR code verification. #### `confirm(): Promise<[VerificationRequest, OutgoingVerificationRequest] | undefined>` Confirms the QR code verification. #### `cancel(): Promise` Cancels the QR code verification. ``` -------------------------------- ### Get Verification Request Object Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Fetches a verification request object using the user ID and flow ID. This function does not return a Promise. ```typescript getVerificationRequest( userId: UserId, flowId: string ): VerificationRequest | undefined ``` -------------------------------- ### StoreHandle Class Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/types.md Manages connections to the crypto store. Provides static methods to open the store with optional credentials or a key. ```typescript class StoreHandle { static open( storeName?: string, storePassphrase?: string, logger?: JsLogger ): Promise; static openWithKey( storeName: string, storeKey: Uint8Array, logger?: JsLogger ): Promise; } ``` -------------------------------- ### Get Room Event Encryption Info Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Retrieves encryption information for a decrypted timeline event, including the sender's verification status. ```typescript getRoomEventEncryptionInfo( event: string, roomId: RoomId ): Promise ``` -------------------------------- ### DeviceLists isEmpty Method Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/encryption-and-requests.md Checks if there are any device list updates. Returns true if no changes or left users are recorded. ```typescript isEmpty(): boolean ``` -------------------------------- ### Ed25519PublicKey Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/vodozemac.md Represents an Ed25519 public key used for verifying digital signatures. It provides methods to get its length and serialize it to a base64 string. ```APIDOC ## Ed25519PublicKey ### Description An Ed25519 public key used for verifying digital signatures. ### Properties #### `length` - **Type:** number - **Description:** Returns the number of bytes an Ed25519 public key has (always 32). ### Methods #### `toBase64()` - **Description:** Serialize the public key to an unpadded base64 representation. - **Returns:** string (unpadded base64) ``` -------------------------------- ### importCrossSigningKeys Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Imports private cross-signing keys. Keys are provided as unpadded base64 strings. ```APIDOC ## importCrossSigningKeys(masterKey, selfSigningKey, userSigningKey) ### Description Import private cross-signing keys. ### Method ```typescript importCrossSigningKeys( masterKey?: string, selfSigningKey?: string, userSigningKey?: string ): Promise ``` ### Parameters #### Path Parameters - **masterKey** (string) - Optional - Master key as unpadded base64 - **selfSigningKey** (string) - Optional - Self-signing key as unpadded base64 - **userSigningKey** (string) - Optional - User-signing key as unpadded base64 ### Returns Promise resolving to CrossSigningStatus. ``` -------------------------------- ### Recover Cross-Signing Keys Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/README.md Imports existing cross-signing keys when setting up the SDK on a new device. This allows the user to maintain their verified identity. ```javascript await machine.importCrossSigningKeys(privateKey, publicKey); ``` -------------------------------- ### openWithKey Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/backup-and-store.md Opens an IndexedDB store with an explicit encryption key. This method is useful for scenarios where you need to manage the encryption key directly. ```APIDOC ## `openWithKey(storeName, storeKey, [logger])` ### Description Open an IndexedDB store with an explicit encryption key. ### Method ```typescript static openWithKey( storeName: string, storeKey: Uint8Array, logger?: JsLogger ): Promise ``` ### Parameters #### Path Parameters - **storeName** (string) - Required - IndexedDB store name - **storeKey** (Uint8Array) - Required - 32-byte encryption key - **logger** (JsLogger) - Optional - Optional logger instance ### Returns Promise resolving to StoreHandle ### Throws JsError if key is not exactly 32 bytes ### Example ```javascript const key = new Uint8Array(32); // Replace with actual key crypto.getRandomValues(key); const store = await StoreHandle.openWithKey("store_name", key); ``` ``` -------------------------------- ### Get a Specific User Device Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/olm-machine.md Retrieves a specific device for a given user ID and device ID. An optional timeout can be specified for key queries. ```typescript getDevice( userId: UserId, deviceId: DeviceId, timeoutSecs?: number ): Promise ``` -------------------------------- ### BackupDecryptionKey.fromBase64 Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/backup-and-store.md Creates a backup decryption key instance from a base64-encoded string. This is useful for loading previously stored keys. ```APIDOC ## BackupDecryptionKey.fromBase64 ### Description Create a backup key from a base64-encoded string. ### Method Static method of `BackupDecryptionKey`. ### Parameters #### Path Parameters - **key** (string) - Required - Base64-encoded key string ### Returns - BackupDecryptionKey: The backup decryption key instance. ### Throws - JsError: If the provided key format is invalid. ### Example ```javascript const key = BackupDecryptionKey.fromBase64("stored_key_base64..."); ``` ``` -------------------------------- ### BackupDecryptionKey.megolmV1PublicKey Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/backup-and-store.md Retrieves the public part of the backup key, specifically formatted for Megolm v1 backup. ```APIDOC ## BackupDecryptionKey.megolmV1PublicKey ### Description Get the public part of this backup key. ### Method Instance method of `BackupDecryptionKey`. ### Returns - MegolmV1BackupKey: The public key component for Megolm v1 backups. ``` -------------------------------- ### ServerName Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/identifiers.md Represents a Matrix server name (homeserver domain). Provides methods to access its host and port, and convert it to a string. ```APIDOC ## ServerName A Matrix server name (homeserver domain). ### Methods #### `host()` ##### Description Returns the hostname portion of the server name. ##### Method `host()` ##### Returns - `string`: The hostname. #### `port()` ##### Description Returns the port number if specified in the server name. ##### Method `port()` ##### Returns - `number | undefined`: The port number, or undefined if not specified. #### `toString()` ##### Description Get the server name as a string. ##### Method `toString()` ##### Returns - `string`: The server name as a string. ``` -------------------------------- ### Handle Withheld Keys Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/README.md Processes situations where a sender has withheld keys, preventing decryption. The error object provides codes and explanations to guide the user on next steps. ```javascript if (error.withheldCode) { console.log(`Key withheld: ${error.description} (${error.withheldCode})`); } ``` -------------------------------- ### KeysQueryRequest Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/encryption-and-requests.md Represents a request to query device keys for specified users on the Matrix server. ```APIDOC ## KeysQueryRequest Request to query device keys for users. **Spec:** [POST /_matrix/client/v3/keys/query](https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3keysquery) #### Properties | Property | Type | Description | |----------|------|-------------| | id | string | Request ID | | body | string | JSON-encoded request body containing timeout, device_keys, token | | type | RequestType | Always RequestType.KeysQuery | ``` -------------------------------- ### MegolmV1BackupKey Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/types.md Represents the public part of a Megolm v1 backup key. ```APIDOC ## MegolmV1BackupKey ### Description Represents the public part of a Megolm v1 backup key. ### Properties - **publicKeyBase64** (string) - The base64 encoded public key. - **algorithm** (string) - The algorithm used for the backup key. ``` -------------------------------- ### Handle Withheld Codes During Decryption Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/errors.md This snippet shows how to check for specific withheld codes when decryption fails. It provides an example for handling the 'm.unverified' code, which indicates the sender's device is not verified. ```javascript try { const decrypted = await machine.decryptRoomEvent(event, roomId, settings); } catch (error) { if (error.withheldCode === "m.unverified") { console.log("Request verification from sender"); // Initiate device verification } } ``` -------------------------------- ### Open Memory Store Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/configuration.md Opens or creates an in-memory store. All keys are lost when the application exits. This is suitable for testing or temporary sessions. ```javascript const store = await StoreHandle.open(); // In-memory, all keys lost on exit ``` -------------------------------- ### BackupDecryptionKey.createRandomKey Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/backup-and-store.md Creates a new, random backup decryption key. This key is essential for decrypting backed-up room keys and should be stored securely for recovery purposes. ```APIDOC ## BackupDecryptionKey.createRandomKey ### Description Create a new random backup decryption key. ### Method Static method of `BackupDecryptionKey`. ### Returns - BackupDecryptionKey: A newly generated backup decryption key. ### Example ```javascript const key = BackupDecryptionKey.createRandomKey(); const base64 = key.toBase64(); // Store this safely for recovery ``` ``` -------------------------------- ### Create BackupDecryptionKey from Base64 Source: https://github.com/matrix-org/matrix-sdk-crypto-wasm/blob/main/_autodocs/api-reference/backup-and-store.md Creates a backup decryption key from a base64-encoded string. Throws a JsError if the key format is invalid. ```typescript static fromBase64(key: string): BackupDecryptionKey ``` ```javascript const key = BackupDecryptionKey.fromBase64("stored_key_base64..."); ```