# Local encrypted storage (https://docs.open-e2ee.dev/build/local-storage.md)

- Status: stable
- Applies to: 15.0.0
- Platforms: Expo · Browser · Node · React Native
- Prereqs: A working client from Start → Quickstart
- Reading time: 11 min

You must configure `adapters.storage`. You can omit `adapters.relay`. This
asymmetry defines the SDK architecture.

A relay provides delivery, and you can replace it. The local test path encrypts
and decrypts without a relay. You cannot replace the local store because it holds
the ratchet. It also holds identity keys, contact trust decisions, prekeys, session
records, and retry message records. If you lose this store, no server copy can
recover it.

```ts
import { createSignalProtocolClient } from '@open-e2ee/signal-protocol-sdk';
import { expoStore } from '@open-e2ee/signal-protocol-sdk/local/store/expo';

const client = await createSignalProtocolClient({
  identity: { userId },
  adapters: { storage: await expoStore() },
});
```

**Figure:** A device outline with its encrypted local store attached to the device edge. The store shares an edge with the device. It belongs to that hardware and is not a reachable service.

## The shipped adapters, with their real status [#the-shipped-adapters-with-their-real-status]

```bash
npm install @open-e2ee/signal-protocol-sdk@latest expo-secure-store expo-sqlite
```

| Adapter | Subpath | Exports | Status |
|---|---|---|---|
| Expo | `/local/store/expo` | `ExpoSignalProtocolStore`, `expoStore()` | Primary supported adapter |
| React Native (bare) | `/local/store/react-native` | `ReactNativeSignalProtocolStore`, `reactNativeStore()` | Supported; requires the op-sqlite SQLCipher build and a native build |
| Node and Electron | `/local/store/node` | `NodeSignalProtocolStore`, `nodeStore()` | Supported; one owner process |
| Browser, SQLite | `/local/store/web-sqlite` | `WebSqliteSignalProtocolStore`, `webSqliteStore()` | Supported; requires the origin private file system and `'wasm-unsafe-eval'` |
| Browser | `/local/store/web` | `IndexedDbSignalProtocolStore`, `indexedDbStore()` | Supported where the origin private file system is not available; requires the browser threat-model review |
| Key-value | `/local/store/key-value` | `KeyValueSignalProtocolStore`, `keyValueStore()` | Supported. You supply and verify the key-value backend |
| In-memory | `/local/store/memory` | `InMemorySignalProtocolStore`, `inMemoryStore()` | Development only |

**Expo** is the primary supported adapter and has the most deployment evidence.
It requires a development build and is not available in Expo Go. The SDK
owns the database file, its key, and its migrations. The `/local/store/expo`
subpath also exports `resetExpoStore`, which deletes the database and opens an
empty one, and `createPreKeyMaintenanceStore`, which takes an open store.

**React Native (bare)**, **Node and Electron**, and **Browser, SQLite** are the
same SDK-owned SQLite store on other engines. The SDK owns each database file,
its key, and its migrations, and keeps the key in a secret vault. Each subpath
exports a reset function, `resetReactNativeStore`, `resetNodeStore`, or
`resetWebSqliteStore`, and `createPreKeyMaintenanceStore`. When the database
file exists and the vault holds no key for it, the open fails with
`LOCAL_STORE_KEY_LOST` and changes nothing. Restore the vault entry, or call the
reset function.

- The bare React Native store runs on op-sqlite with SQLCipher. Its key is in
  the react-native-keychain vault by default.
- The Node store runs on `better-sqlite3-multiple-ciphers` in Node and in the
  Electron main process. You pass the vault. In Electron, use
  `ElectronSafeStorageSignalProtocolSecretVault`.
- The web SQLite store runs SQLite3 Multiple Ciphers in a Wasm worker, with the
  file in the origin private file system. Its key is in IndexedDB in the same
  origin by default, so it is not an XSS defense. Its graduation gates, a
  soak among them, run in CI.

**Browser** and **Key-value** implement the full core store contract.
This contract includes SESAME records, sender-key state, retry message records,
and recovery helpers. Each one's graduation gates run on every change to the
source repository. The browser store's gates are contract
suites in real Chromium, Firefox, and WebKit, multi-tab, interruption,
storage-pressure, and soak, and deployment requires the origin-security review
in [browser setup](https://docs.open-e2ee.dev/start/browser.md). The key-value store is for an app that
chooses its own storage engine, for example Realm on bare React Native. Its
gates are the exported backend-conformance kit, interruption and
storage-pressure suites, and a CI run of the kit over the SDK's reference
backend on Hermes. The store's durability is only as good as the
key-value backend you supply, so run the exported kit,
`assertBackendConformance`, against your backend from your own tests:

```ts
import { KeyValueSignalProtocolStore } from '@open-e2ee/signal-protocol-sdk/local/store/key-value';
import { ReactNativeKeychainSignalProtocolSecretVault } from '@open-e2ee/signal-protocol-sdk/local/vault/react-native-keychain';

const storage = await KeyValueSignalProtocolStore.create({
  storage: yourKeyValueBackend,
  vault: new ReactNativeKeychainSignalProtocolSecretVault(),
});
```

The store keeps the key that encrypts each stored value in the vault, never in
the key-value backend. Without a vault, `create` throws an `EncryptionError`
with code `SECRET_VAULT_REQUIRED`.

If the backend holds store data and the vault holds no key, `create` rejects
with `LOCAL_STORE_KEY_LOST` and changes nothing, because a new key cannot read
the old data. Restore the vault entry, or call
`KeyValueSignalProtocolStore.reset({ storage, vault })`. A reset deletes the
store's records and writes a new key, so the device then needs a new identity.

You do not have to write the backend from the start.
`createTransactionalKeyValueBackend(engine)` builds one over an engine's own
transaction, and `/local/store/key-value/realm` exports
`createRealmKeyValueBackend` for a Realm that your app opens.

**Node** supports test harnesses, service-side clients, and CLI tools.
**In-memory** keeps state in memory for development only. It discards
all data at process exit. Use it for the two-client [Quickstart](https://docs.open-e2ee.dev/start/quickstart.md)
sample, but not for user data.

Adapter selection affects more than convenience. See
[Choosing adapters](https://docs.open-e2ee.dev/start/choosing-adapters.md).

## Encryption at rest [#encryption-at-rest]

The four SQLite stores, `expoStore()`, `reactNativeStore()`, `nodeStore()`,
and `webSqliteStore()`, take the same `encryptionAtRest` option. The default is
`true`.

- **`true`**: the store asks the SQLite binding for its cipher after each keyed
  open. A binding without a cipher accepts a key and writes plaintext with no
  error, so the store refuses it. The open fails with
  `SqliteEncryptionUnavailableError` (`KEY_STORAGE_ERROR`) and writes nothing to
  the database file.
  An Expo build without SQLCipher and an op-sqlite build without the SQLCipher
  flag fail this way.
- **`false`**: the store opens on a binding without a cipher, for example
  `expo-sqlite` on the web. It does not use the vault, and it logs a warning
  through `logger` at every open.

The store records the setting in `PRAGMA application_id` in the database
header. Without `convertPlaintext: true`, a database created with one setting
does not open with the other. The open fails with `SqliteKeyMismatchError`
(`KEY_STORAGE_ERROR`) and does not change the file. So an encrypted open of a
plaintext database fails as a mismatch, not as `LOCAL_STORE_KEY_LOST`. The
error message names the `convertPlaintext` option. After a conversion that
stopped, an open can fail with `INVALID_STATE` instead. See
[convert a plaintext store](https://docs.open-e2ee.dev/build/local-storage.md#convert-a-plaintext-store). A reset function
deletes the file and creates a new database with the setting that you pass to
it.

With `encryptionAtRest: false`, every row, including the group sender-key rows,
is plaintext in the database file. Use it only where the platform gives you no
cipher.

The checks that run this contract:

- **Node store job** (Linux, macOS, and Windows, each with Node 22 and Node 26)
  refuses a binding without a cipher and a file with the other setting, on real
  files.
- **Default automated checks** (Linux, Node 26) refuse an op-sqlite build
  without SQLCipher and a plaintext file opened with encryption, on test
  doubles of op-sqlite and `react-native-keychain`.

The published checks do not name the opt-out on the Expo or web SQLite store.
Those stores run the same SQLite core.

### Convert a plaintext store [#convert-a-plaintext-store]

To keep the data of a plaintext database, open it with encryption and
`convertPlaintext: true`. The four SQLite stores take this option. When the
vault holds no key for the store name, the open converts the plaintext database
to an encrypted one. It keeps every row and the schema version, and it writes a
new key to the vault.

```ts
const storage = await expoStore({ convertPlaintext: true });
```

The conversion writes the encrypted copy in one transaction, and then it
removes the plaintext file. It does not change the plaintext file before that
removal. The removal of the plaintext file is the commit point. An open that
fails with an error before the removal deletes the copy and its key, and it
leaves the plaintext file. The next conversion starts again. When the process
stops during a conversion, the result depends on the step:

- **Before the copy is complete**: the open leaves the plaintext file, and the
  next conversion starts again with a new key.
- **After the copy is complete and before the removal**: the next encrypted
  open, with or without the option, fails with `INVALID_STATE` and changes
  nothing. The error message names both files. Remove the plaintext file to
  finish the conversion from the copy, or reset the store to delete all data.
- **After the removal**: the next encrypted open finishes the conversion, with
  or without the option.

The conversion has these limits:

- The conversion refuses a database that holds tables that the SDK does not
  own. It also refuses BLOB values and integers outside the safe JavaScript
  range. It fails with `INVALID_STATE` before it writes anything.
- The option does nothing on an encrypted database or when no database exists.
- A reset with `encryptionAtRest: false` deletes the file. When the vault holds
  a key for the store name, the reset keeps it. An encrypted open of the new
  plaintext database uses that key and fails with `SqliteKeyMismatchError`
  (`KEY_STORAGE_ERROR`). The conversion does not run.
- `convertPlaintext: true` with `encryptionAtRest: false` fails with
  `INVALID_STATE`.
- The disk blocks of the removed plaintext file can keep its data until the
  file system uses them again.

The conversion writes a temporary file whose name is the store name plus
`.oe2e-convert`. Each SQLite store refuses a store name that ends in
`.oe2e-convert` with `INVALID_STATE`. While the temporary file exists, an open
or a reset with `encryptionAtRest: false` fails with `INVALID_STATE` and
changes nothing. On the web SQLite store, a conversion needs a store name of at
most 51 characters.

## The SDK versions session records and resets old records [#the-sdk-versions-session-records-and-resets-old-records]

The persisted session record is version `4`:

```ts
interface SessionRecord {
  currentSession: SessionState | null;
  archivedSessions: Record<string, SessionState>;
  version: 4;
  metadata?: SessionRecordMetadata;
}
```

Version 4 binds each endpoint's composite identity and explicit identity type to
the live session. **The SDK rejects and resets older formats. It does not migrate
them.**

When the SDK encounters an earlier format, it does not reconstruct unverifiable
ratchet state. It discards the session. The next message to that peer creates a
new session from a fresh prekey bundle. Users do not receive an error. They can
see a conversation safety-number change. They also cannot decrypt in-flight
ciphertext that used the discarded session.

This conservative choice avoids a later, silent ratchet failure caused by an
incorrect migration. Plan upgrades for this behavior. The SDK is `15.0.x`.
Public APIs and persisted formats follow semantic versioning.
[Upgrades](https://docs.open-e2ee.dev/operate/upgrades.md) covers the rollout mechanics.

## Store schema steps are forward-only [#store-schema-steps-are-forward-only]

The SQLite stores use schema version 7, and the IndexedDB store uses database
version 12. The 14.0.0 steps change no table. After a 14.0.0 client opens a
store, an earlier SDK cannot open it. An earlier SDK refuses the SQLite file with
`SqliteSchemaTooNewError`, code `INVALID_STATE`. The browser refuses its
IndexedDB open with a `VersionError`. The key-value store has no version guard.
Stop each earlier SDK process on it before the first 14.0.0 open. The IndexedDB
and key-value stores also encrypt each metadata value with their record cipher at
the first open. The metadata key names stay in the clear. A downgrade is not
supported.

A 14.0.0 IndexedDB connection closes when another connection opens a newer
version. An SDK 13.x connection does not close itself. When an open connection
of an older tab blocks the open, the store logs one warning with the code
`INDEXEDDB_OPEN_BLOCKED` and the field `version`. The open completes when that
connection closes.

At each open, the IndexedDB, SQLite, and key-value stores delete every SDK 11
received-content row. They also delete every converted record that waits for
its envelope. An open that deletes at least one logs one warning with the code
`LEGACY_RECEIVED_CONTENT_DELETED`. The field `count` holds the deleted rows and
records. The field `readable` holds the deleted rows that parse. The line holds
no key and no value. An open that finds nothing logs nothing. The memory store
keeps no data across a restart and has no sweep.

Each local store declares its `protection`. The SQLite stores report `file-cipher`,
or `none` when `encryptionAtRest` is `false`. The key-value and IndexedDB stores
report `record-cipher`. The memory store reports `none`. The declaration adds no
encryption. `protocol.contentRecovery` reads it to decide whether the store may keep
resendable content. See [API reference](https://docs.open-e2ee.dev/reference/api.md).

## Atomicity is a security property, not a performance one [#atomicity-is-a-security-property-not-a-performance-one]

A decrypt operation changes ratchet state. The store advances the chain key,
derives and consumes message keys, and writes the record. It must complete this
write before it gives plaintext to your application. Two concurrent decrypt
operations or a partial write can corrupt that state. No server copy exists for
reconciliation.

The store contract therefore defines two atomic boundaries. One transaction
commits contact trust, session creation or advancement, and responder one-time-prekey
consumption. Another transaction accepts identity rotation and deletes every bound
device session. An adapter must not publish only part of either transition.

For the key-value store, the backend's `atomicWrite` is a security boundary, not a batching optimization. It must commit `check`, `set`, `remove`, `pruneSkippedSenderKeys`, `removeSessionsForUser`, and `removeSenderKeyHandoffs` in one crash-durable transaction, and the final operation must enumerate exact plaintext session metadata *inside* that transaction. Enumerating before the transaction can leave a concurrently created session trusted under a rotated identity.

> **Failure mode — Bad MAC and corrupted session state**
>
> There is no `BadMacError` class in this SDK. The classic `libsignal` "Bad MAC"
> failure produces `DECRYPTION_FAILED`, whose message names the MAC mismatch. A
> readable record that the protocol cannot use produces `SESSION_CORRUPTED`. Both
> codes arrive in an `EncryptionError` with `.code`, `.context`, and
> `.originalError`.
>
> Production incidents show the effect of this failure. In February 2026, a report
> described 479 Bad MAC exceptions from libsignal. WhatsApp inbound delivery stopped
> without a visible gateway disconnection. A related project logged more than
> 168,000 errors in two hours across 400+ sessions. The errors exhausted the Node
> heap and continued after the project deleted session files.
>
> Export the decrypt failure rate as a health metric. No other metric identifies this
> condition. See [Observability](https://docs.open-e2ee.dev/operate/observability.md).
>
> Do not use store-file deletion as the only remediation. Both endpoints hold the
> state that causes the error. Only an explicit session teardown on both endpoints
> converges. `deleteSession(remoteAddress)` and `archiveSession(remoteAddress)` are
> the local operations. [Error handling](https://docs.open-e2ee.dev/operate/error-handling.md) covers triage.

## The vault is not the store [#the-vault-is-not-the-store]

These are two different things and blurring them is the most common architectural mistake on this page.

The **store** owns the protocol database, including each session, prekey, and trust
decision. The **vault** owns small bootstrap secrets through `getSecret(key)`,
`setSecret(key, value)`, and `deleteSecret(key)`.

```ts
import { ExpoSecureStoreSignalProtocolSecretVault } from '@open-e2ee/signal-protocol-sdk/local/vault/expo-secure-store';

const vault = new ExpoSecureStoreSignalProtocolSecretVault();

await vault.setSecret('signal-store-wrapping-key', wrappingKey);
const restored = await vault.getSecret('signal-store-wrapping-key');
```

The SDK states the reason directly:

> **"platform secret managers are appropriate for tiny keys and bootstrap values,
> but not full session databases."**

Keychain and Keystore entries have size limits, latency characteristics, and access-prompt behavior.
A session-record database cannot tolerate these constraints. The vault therefore
holds a wrapping key. The wrapping key protects the store, and the store holds the
session database.

Vault secret names are application-wide storage keys. Add a namespace to prevent
collisions with other application data. Delete the secrets and encrypted store in
the same account-reset transaction. See
[Device registration and lifecycle](https://docs.open-e2ee.dev/build/device-lifecycle.md). Your application
still controls platform backup, biometric access, and device-migration behavior.

> **Not covered — Key custody, host security, and device backups**
>
> Your threat model must define the effect of automatic cloud backup and rooted or
> jailbroken devices. It must also identify who can demand access to the vault.
> These are not adapter decisions. See [Threat model](https://docs.open-e2ee.dev/learn/threat-model.md) and
> [Security review](https://docs.open-e2ee.dev/operate/security-review.md).

**Opacity ledger**

| Artifact | Local owner | Stays on device | Sent to relay | In object store | Visible as metadata |
|---|---|---|---|---|---|
| `identityKeyPair` private half | store | yes | no | no | no |
| `identityKeyPair` public half | store | yes | yes | no | yes |
| `SessionRecord.currentSession` | store | yes | no | no | no |
| `SessionRecord.archivedSessions` | store | yes | no | no | no |
| `SessionRecord.version` | store | yes | no | no | no |
| EC one-time prekey private halves | store | yes | no | no | no |
| EC one-time prekey public halves | store | yes | yes | no | yes |
| Signed prekey private half | store | yes | no | no | no |
| Kyber prekey private halves | store | yes | no | no | no |
| Contact identity trust / TOFU decisions | store | yes | no | no | no |
| Sender-key state (`hasGroupSenderKey`) | store | yes | no | no | no |
| Retry message records | store | yes | no | no | no |
| `"signal-store-wrapping-key"` | vault | yes | no | no | no |
| Message plaintext after `onMessageDecrypted` | your app | yes | no | no | no |

The last row is the one to read twice. Your app owns decrypted message rows and local files after the Signal Protocol client decrypts or stages them. The store does not keep your message history for you.

## Next [#next]

- [Choosing adapters](https://docs.open-e2ee.dev/start/choosing-adapters.md): select a store for your runtime
- [Device registration and lifecycle](https://docs.open-e2ee.dev/build/device-lifecycle.md): clear the store, vault, and device ID as one reset
- [Error handling](https://docs.open-e2ee.dev/operate/error-handling.md): use the complete `EncryptionErrorCode` triage path
- [Recovery, backup, and migration](https://docs.open-e2ee.dev/build/recovery-backup-migration.md): move a store to new hardware
