UNPKG

tiny-crypto-suite

Version:

Tiny tools, big crypto β€” seamless encryption and certificate handling for modern web and Node apps.

293 lines (186 loc) β€’ 7.41 kB
### πŸ“₯ `importSession(key, pickled, password?)` Imports and restores a **1:1 Olm session** from a pickled string and stores it in the internal session map. #### πŸ” Returns - **Promise<void>** #### 🧼 Behavior - Creates a new `Olm.Session` and unpickles it using the provided `password`. - Saves the session to `this.sessions` using the provided `key`. - Persists the session in IndexedDB under `sessions`. - Emits `TinyOlmEvents.ImportSession`. #### πŸ“Œ Note This is typically used when syncing session state between devices or restoring it after reinitialization. #### πŸ§‘β€πŸ’» Example ```javascript await tinyOlmInstance.importSession(userId, pickledSession); ``` --- ### πŸ”„ `getAllSessions()` Retrieves all active sessions. #### πŸ” Returns - **Map<string, Olm.Session>**: A map of all active sessions, where the key is the userId. #### πŸ§‘β€πŸ’» Example ```javascript const allSessions = tinyOlmInstance.getAllSessions(); console.log(allSessions); ``` --- ### πŸ§‘β€πŸ’» `getSession(userId)` Retrieves the session for a specific **userId**. #### πŸ“₯ Parameters | Name | Type | Description | |----------|----------|---------------------------------------------------| | `userId` | `string` | The userId whose session is to be retrieved. | #### πŸ” Returns - **Olm.Session**: The session for the specified **userId**, or `null` if no session exists. #### 🧠 Throws - **Error**: If no session exists for the specified **userId**. #### πŸ§‘β€πŸ’» Example ```javascript const session = tinyOlmInstance.getSession('@user:domain.com'); console.log(session); ``` --- ### ❌ `removeSession(userId)` Removes the session for a specific **userId**. #### πŸ“₯ Parameters | Name | Type | Description | |----------|----------|---------------------------------------------------| | `userId` | `string` | The userId whose session is to be removed. | #### πŸ” Returns - **boolean**: Returns `true` if the session was removed, otherwise `false`. #### 🧠 Throws - **Error**: If no session exists for the specified **userId**. #### πŸ§‘β€πŸ’» Example ```javascript const wasRemoved = await tinyOlmInstance.removeSession('@user:domain.com'); console.log(wasRemoved); // true if session was removed ``` --- ### 🧹 `clearSessions()` Clears all active sessions. #### πŸ” Returns - **void** #### πŸ§‘β€πŸ’» Example ```javascript await tinyOlmInstance.clearSessions(); ``` --- ### πŸ§ͺ `hasSession(userId)` Checks whether there is an active Olm session with a specific user. #### πŸ“₯ Parameters - `userId` *(string)*: The user ID to check for an existing session. #### πŸ” Returns - **boolean**: `true` if a session exists, `false` otherwise. #### πŸ§‘β€πŸ’» Example ```javascript if (tinyOlmInstance.hasSession('@alice')) { console.log('Session with Alice exists!'); } ``` --- ### πŸ› οΈ `exportSession(userId, password = this.password)` Exports a specific **Olm.Session** with a given user. #### πŸ“₯ Parameters | Name | Type | Description | |-------------|----------|--------------------------------------------------| | `userId` | `string` | The user ID of the remote device. | | `password` | `string` | The password used to encrypt the pickle. Default is the current instance password. | #### πŸ” Returns - `string`: The pickled Olm session. #### ⚠️ Throws - `Error`: If the session is not found. #### 🧠 What it does - Exports the session with the specified user as a pickled string, encrypted with the specified password. #### πŸ§‘β€πŸ’» Example ```javascript const pickledSession = tinyOlmInstance.exportSession('@user:domain.com', 'mySecurePassword'); ``` --- ### πŸ“€ `createOutboundSession(theirIdentityKey, theirOneTimeKey, theirUsername)` Creates an outbound Olm session with another user using their identity and one-time keys. #### πŸ“₯ Parameters - `theirIdentityKey` *(string)*: Identity key of the target user. - `theirOneTimeKey` *(string)*: One-time key of the target user. - `theirUsername` *(string)*: User ID of the target user. #### πŸ” Returns - **void** #### πŸ›‘ Throws - **Error**: If the account is not initialized or no one-time key is available. #### πŸ§‘β€πŸ’» Example ```javascript await tinyOlmInstance.createOutboundSession(theirIdentityKey, theirOneTimeKey, '@alice'); ``` --- ### πŸ“₯ `createInboundSession(senderIdentityKey, ciphertext, senderUsername)` Creates an inbound Olm session based on a received ciphertext and sender's identity key. #### πŸ“₯ Parameters - `senderIdentityKey` *(string)*: Identity key of the sender. - `ciphertext` *(string)*: Encrypted message received. - `senderUsername` *(string)*: User ID of the sender. #### πŸ” Returns - **void** #### πŸ›‘ Throws - **Error**: If the account is not initialized. #### πŸ§‘β€πŸ’» Example ```javascript await tinyOlmInstance.createInboundSession(senderIdentityKey, ciphertext, '@bob'); ``` --- ### πŸ” `encryptMessage(toUsername, plaintext)` Encrypts a raw plaintext message using an existing session with the recipient. #### πŸ“₯ Parameters - `toUsername: string` – The user ID of the recipient. - `plaintext: string` – The message content in plaintext. #### πŸ“€ Returns - `EncryptedMessage`: The encrypted message object (`{ type, body }`). #### ⚠️ Throws - If no session exists with the given user. #### πŸ§‘β€πŸ’» Example ```js const encrypted = tinyOlmInstance.encryptMessage('alice', 'Hello!'); ``` --- ### πŸ”“ `decryptMessage(fromUsername, messageType, ciphertext)` Decrypts a ciphertext message from a known session. #### πŸ“₯ Parameters - `fromUsername: string` – The sender's user ID. - `messageType: 0 | 1` – The message type (0 = pre-key, 1 = message). - `ciphertext: string` – The received encrypted content. #### πŸ“€ Returns - `string`: The decrypted plaintext. #### ⚠️ Throws - If no session exists with the sender. #### πŸ§‘β€πŸ’» Example ```js const plaintext = tinyOlmInstance.decryptMessage('alice', 1, encrypted.body); ``` --- ### πŸ§ͺ `encrypt(toUsername, data)` Serializes and encrypts any data structure using the appropriate serializer (`TinyCryptoParser`). #### πŸ“₯ Parameters - `toUsername: string` – The recipient’s user ID. - `data: *` – The data to serialize and encrypt. #### πŸ“€ Returns - `EncryptedMessage`: The encrypted result of the serialized content. #### πŸ”§ Behavior - Uses `serializeDeep()` if `isDeep === true`, otherwise `serialize()`. #### πŸ§‘β€πŸ’» Example ```js const encrypted = tinyOlmInstance.encrypt('bob', { hello: 'world' }); ``` --- ### πŸ” `decrypt(fromUsername, messageType, plaintext, expectedType = null)` Decrypts and deserializes a message received from another user. #### πŸ“₯ Parameters - `fromUsername: string` – The sender’s user ID. - `messageType: 0 | 1` – The type of Olm message. - `plaintext: string` – The encrypted message. - `expectedType?: string | null` – Optional: expected data type to validate deserialization. #### πŸ“€ Returns - `*`: The deserialized content (any JS object or value). #### πŸ”§ Behavior - Uses `deserializeDeep()` if `isDeep === true`, otherwise `deserialize()`. #### πŸ§‘β€πŸ’» Example ```js const object = tinyOlmInstance.decrypt('bob', 1, ciphertext, 'object'); ```