tiny-crypto-suite
Version:
Tiny tools, big crypto β seamless encryption and certificate handling for modern web and Node apps.
262 lines (168 loc) β’ 8.51 kB
Markdown
## π Constructor: `new TinyOlm.Instance(userId, deviceId, password?)`
Creates a new **TinyOlmInstance** instance bound to a specific user and device.
### π§° Parameters
| Name | Type | Description |
|------------|----------|-----------------------------------------------------------------------------|
| `userId` | `string` | The user ID to associate with this account and its cryptographic sessions. |
| `deviceId` | `string` | The device ID representing this instance of the user. |
| `password` | `string` | *(Optional)* A password linked to this account and its sessions. |
### π¦ Properties
| Property | Type | Description |
|-----------------------|--------------------------------------|--------------------------------------------------|
| `this.userId` | `string` | The user's unique identifier. |
| `this.deviceId` | `string` | The identifier for this specific device. |
| `this.password` | `string` | Password used in this session (optional). |
| `this.account` | `Olm.Account \| null` | The associated Olm account (or `null` if unset). |
| `this.sessions` | `Map<string, Olm.Session>` | Direct peer-to-peer sessions by user/device. |
| `this.groupSessions` | `Map<string, Olm.OutboundGroupSession>` | Group encryption sessions (outbound). |
| `this.groupInboundSessions` | `Map<string, Olm.InboundGroupSession>` | Group decryption sessions (inbound). |
### π οΈ `init()`
Initializes the Olm library and creates a new account.
#### π Returns
- **Promise<void>**: Resolves when the Olm library is initialized and the account is created.
#### π§βπ» Example
```javascript
await tinyOlmInstance.init();
console.log('Olm library initialized and account created.');
```
### ποΈ `initIndexedDb(dbName?)`
Initializes the **IndexedDB** database for this TinyOlmInstance and attempts to restore all saved cryptographic state (account, sessions, group sessions).
#### π₯ Parameters
| Name | Type | Default | Description |
|-----------|----------|----------------------|----------------------------------------------|
| `dbName` | `string` | `'TinyOlmInstance'` | *(Optional)* The name of the database. |
#### π Returns
- `Promise<IDBDatabase>`: Resolves once the database is fully initialized and restored.
#### β οΈ Throws
- `Error`:
- If not running in a browser.
- If `dbName` is not a string.
- If the database has already been initialized.
#### π§ What it does
1. Ensures the environment is a browser and that Olm is loaded.
2. Opens or upgrades the IndexedDB database with object stores:
- `account`
- `sessions`
- `groupSessions`
- `groupInboundSessions`
3. Emits internal setup events for password, userId, and deviceId.
4. Loads and restores:
- Your account from storage.
- All direct sessions.
- All group sessions (outbound and inbound).
5. Starts watching for any future pickle updates.
### π `validateIsBrowser()`
Checks whether the current environment supports **IndexedDB** β meaning it's running in a web browser.
#### β οΈ Throws
- `Error`: If not running in a browser or if `indexedDB` is unavailable.
#### π§ Purpose
This method ensures that the TinyOlm instance is being used in an environment compatible with browser-based storage.
### ποΈ `getDbName()`
Returns the name of the **IndexedDB** database used by the TinyOlmInstance.
#### π Returns
- `string`: The name of the current IndexedDB database.
#### β οΈ Throws
- `Error`: If the internal database name (`#dbName`) is not set correctly (i.e., not a string).
#### π§ Note
This method relies on an internal private field `#dbName` and is used to access the database identifier safely.
### π οΈ `getDb()`
Returns the active **IndexedDB** database instance currently used by TinyOlmInstance.
#### π Returns
- `IDBDatabase`: The open and initialized IndexedDB database instance.
#### β οΈ Throws
- `Error`: If the database hasn't been initialized yet.
_(Hint: Make sure to call `initIndexedDb()` before using this method.)_
#### π§ Note
This method accesses the internal private field `#db` and ensures that the database is ready before continuing.
### π§ͺ `_testIndexedDb()`
*(Internal method)*
Used for debugging purposes: logs all entries currently stored in the database's object stores.
#### π Returns
- `Promise<void>` β Logs the contents of:
- `account`
- `sessions`
- `groupSessions`
- `groupInboundSessions`
### ποΈ `exportInstance(password = this.password)`
Exports the entire **TinyOlmInstance** as a serial structure.
#### π₯ Parameters
| Name | Type | Description |
|-------------|----------|------------------------------------------------|
| `password` | `string` | The password used to pickle the instance. Default is the current instance password. |
#### π Returns
- `ExportedOlmInstance`: A serial structure containing the pickled account, sessions, group sessions, and inbound group sessions.
#### π§ What it does
- Exports the full instance, including account, sessions, group sessions, and inbound group sessions, all pickled with the specified password.
#### π§βπ» Example
```javascript
const exportedInstance = tinyOlmInstance.exportInstance('mySecurePassword');
```
### π¦ `importInstance(data, password?)`
Restores a full exported `TinyOlmInstance`, including account, sessions, and group sessions.
#### π Returns
- **Promise<void>**
#### π§Ό Behavior
- Restores the account via `importAccount()`.
- Iterates over `data.sessions`, calling `importSession()` on each.
- Iterates over `data.groupSessions`, calling `importGroupSession()` on each.
- Iterates over `data.groupInboundSessions`, calling `importInboundGroupSession()` on each.
#### π Note
This is the high-level method used to restore the entire cryptographic state, e.g., after logging in from another device.
#### π§βπ» Example
```javascript
await tinyOlmInstance.importInstance(exportedData, 'secure-password');
```
### π§Ή `dispose()`
Disposes the TinyOlmInstance by clearing all Olm sessions (both individual and group) and releasing the account from memory.
#### π Returns
- **Promise<void>**
#### π§Ό Behavior
- Clears all **1:1 Olm sessions** via `clearSessions()`.
- Frees and nullifies the **Olm account**, emitting `TinyOlmEvents.ResetAccount`.
- Clears all **outbound group sessions**.
- Clears all **inbound group sessions**.
#### π Note
This should be called when the instance is no longer needed, to ensure that memory is properly released and cryptographic material is not kept in memory unnecessarily.
#### π§βπ» Example
```javascript
await tinyOlmInstance.dispose();
```
### ποΈ `existsDb()`
Checks whether the internal IndexedDB instance has been initialized and is currently available.
#### π Returns
- **boolean**: `true` if the database instance exists and is ready for use, otherwise `false`.
#### π§Ό Behavior
- Verifies if the private `#db` property has been set (i.e., the database has been opened).
- Returns `true` if an active `IDBDatabase` instance is present.
#### π Note
This is a lightweight check that does not open or interact with the databaseβonly verifies internal state.
#### π§βπ» Example
```javascript
if (tinyOlmInstance.existsDb()) {
console.log('Database is ready!');
} else {
console.warn('Database is not initialized.');
}
```
### π§΅ `getQueue()`
Returns the internal `TinyPromiseQueue` (from tiny-essentials module) used to manage asynchronous task queuing and execution order.
This queue ensures that encryption and decryption operations β or any session-related activities β are executed sequentially, avoiding race conditions.
#### Returns:
- `TinyPromiseQueue`: A queue manager instance that controls promise execution order.
#### π§βπ» Example:
```js
const queue = tinyOlm.getQueue();
queue.enqueue(() => someAsyncTask());
queue.enqueuePoint(() => someAsyncTask());
```