# Build an encrypted Expo conversation from scratch (https://docs.open-e2ee.dev/guides/expo-encrypted-chat.md)

- Status: stable
- Applies to: 15.0.0
- Platforms: Expo
- Prereqs: Node 22.18+, an Expo project, and the ability to run a development build on a device or simulator
- Reading time: 16 min

The SDK runs encrypted exchanges on Expo and Hermes. Its protocol code is Pure TypeScript. `react-native-get-random-values` gives the SDK its global random source, and Expo modules provide encrypted storage.

SQLCipher requires a native development or release build. Expo Go does not include it. [Expo setup](https://docs.open-e2ee.dev/start/expo.md) has the native configuration and the build commands for iOS and Android.

To try the message flow without a native build, [open the browser playground](https://open-e2ee.dev/playground/).

## Runtime cryptography [#runtime-cryptography]

Hermes does not provide Web Crypto’s `SubtleCrypto` API. For AES-CBC and AES-GCM, the SDK uses Noble AES when that API is absent.

On React Native and Expo, the SDK reads random bytes only from the global `crypto.getRandomValues`. Install `react-native-get-random-values` with the other packages below, and load it before the first SDK call, with `import 'react-native-get-random-values';` at the top of the app entry. Without a global source, the SDK throws `SecureRandomUnavailableError`. The SDK’s Hermes gate runs each public flow on Hermes with only the globals of a bare React Native app, not with Expo modules. [Hermes gate results](https://docs.open-e2ee.dev/reference/runtime-support.md#hermes-gate-results) lists what it records.

## Intended audience [#intended-audience]

Use this guide to add encrypted messaging to an Expo application. For separate devices, supply an authenticated relay adapter or use the [OpenE2EE Signal Protocol Relay](https://docs.open-e2ee.dev/signal-relay.md).

## Prerequisites [#prerequisites]

- **A development build.** The Expo store "requires a development build and is not available in Expo Go." That is the single most important expectation on this page. Everything below assumes `npx expo run:ios` / `run:android` or an EAS development build, not the Expo Go client.
- Node 22.18 or newer, and an Expo app you can add native config to. The SDK needs Node 22.12 or newer. The `oe` command of the Sandbox quickstart needs Node 22.18 or newer.
- SQLCipher enabled through the `expo-sqlite` config plugin (`useSQLCipher`). The SDK owns the database file, its key, and its migrations.
- Read [keys, identity, and sessions](https://docs.open-e2ee.dev/learn/keys-identity-sessions.md), [local-first architecture](https://docs.open-e2ee.dev/learn/local-first.md), and [E2EE is not TLS](https://docs.open-e2ee.dev/learn/e2ee-vs-tls.md) first.

The SDK is `15.0.x`. Public APIs and persisted formats follow semantic versioning.

## What this guide builds [#what-this-guide-builds]

**Figure:** An Expo device holding private key material and an attached encrypted local store, separated by a trust boundary from a relay that carries a sealed envelope with visible metadata. The vault-held wrapping key and identity private half stay on the device. The local store is not a service and is not remotely reachable. The sealed envelope crosses the boundary, where the relay can read its metadata.

## Install [#install]

```bash
npm install @open-e2ee/signal-protocol-sdk@latest expo-secure-store expo-sqlite react-native-get-random-values
```

Adapters declare their runtime requirements as optional peer dependencies. The Expo store and vault need `expo-secure-store` and `expo-sqlite`. `react-native-get-random-values` is the global random source. Add `expo-device` and `react-native-device-info` only if you later use `DeviceLifecycleManager`.

## Stage 1: the database key, held in the vault [#stage-1-the-database-key-held-in-the-vault]

Two things are deliberately separate, and blurring them is the most common design mistake here.

The **vault** (`SignalProtocolLocalSecretVault`) holds tiny bootstrap secrets: `getSecret` / `setSecret` / `deleteSecret`, nothing else. The **store** (`SignalProtocolLocalStore`) holds the protocol state: identity keys, contact trust records, prekeys, sessions, sender keys, message records. The SDK states the reason for the split plainly: "Platform secret managers are appropriate for tiny keys and bootstrap values, but not full session databases."

So the vault holds one 32-byte database key. The store holds everything else, inside a database that key encrypts.

`expoStore()` defaults its vault to `ExpoSecureStoreSignalProtocolSecretVault`, so on a stock Expo app you get the vault for free. On first use it creates the database key in the vault, then the database file, and each open applies the SDK migrations. Pass the vault explicitly when you want to see it or supply your own:

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

const storage = await expoStore({ vault: new ExpoSecureStoreSignalProtocolSecretVault() });
```

The key sits in the vault under `signal_protocol_sqlite_key.<name>`, where `name` is the database file name, by default `open-e2ee-signal-protocol.db`. Keep your application tables in a separate database file. The SDK database holds only SDK tables.

> **Failure mode — The database exists, but its key does not**
>
> When the database file exists and the vault holds no key for it, `expoStore()` rejects with `LOCAL_STORE_KEY_LOST` and changes nothing. A new key cannot read the old file. Restore the vault entry, or call `resetExpoStore()`: it deletes the file, writes a new key, and returns the open, empty store. Close the open store of that name first. `clearAllKeys()` on an open store empties every SDK table and keeps the file and its key.

## Stage 2: the store and the client [#stage-2-the-store-and-the-client]

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

// relayUrl: the Relay connection URL. Use a Sandbox URL during development.
// getIdentityAssertion() is your code. It returns a short-lived signed
// identity assertion for the signed-in user.
const signal = await createHostedSignalProtocolClient({
  adapters: { storage: await expoStore() },
  hosted: {
    relayUrl,
    getIdentityAssertion,
    onProgress: ({ phase }) => setSetupProgress(phase),
  },
});
```

`createHostedSignalProtocolClient()` connects to the OpenE2EE Signal Protocol Relay. Start on a Sandbox environment from the [Sandbox quickstart](https://docs.open-e2ee.dev/signal-relay.md#sandbox-quickstart). In an Expo app, `oe new` writes the Sandbox connection URL to `.env.local` as `EXPO_PUBLIC_OPEN_E2EE_SIGNAL_RELAY_URL`.

Set up `getIdentityAssertion` with [identity and authentication](https://docs.open-e2ee.dev/signal-relay/identity.md). For application-bound accounts, connect the [native identity callback](https://docs.open-e2ee.dev/signal-relay/custom-token.md#native-apps-react-native-and-expo). The Relay assigns the account ID, and `signal.userId` returns it. For a backend that you build, pass an application-owned `SignalProtocolRelayServer` to `createSignalProtocolClient()`. [Relay and prekeys](https://docs.open-e2ee.dev/build/relay-and-prekeys.md) states the contract.

Post-quantum policy defaults to `postQuantum: 'required'` and `braid: 'required'`. Sessions with peers that have no post-quantum material fail closed. `'required'` is the only `postQuantum` value, and no setting allows a classical session.

## Stage 3: publish public key material [#stage-3-publish-public-key-material]

The factory creates or loads the identity and prekeys, registers the device, and publishes the **public** keys and signatures. `hosted.onProgress` reports the `phase` as `preparing-local-state`, `requesting-assertion`, `submitting`, or `complete`. Show this progress, because key generation on a mid-range Android device can make a spinner appear stalled.

Run `syncToServer()` to retry a failed sync or to replenish one-time prekeys:

```ts
await signal.syncToServer(({ stage, percent, message }) => {
  setSyncProgress({ stage, percent, message });
});
```

Its progress callback reports `stage` as `generating-keys`, `generating-kyber`, `uploading`, or `complete`. It also reports `percent`, `message`, and optional `detail` values for `current` and `total`.

`client.syncStatus` afterwards is `'synced' | 'failed' | 'none'`.

## Stage 4: receive, then send [#stage-4-receive-then-send]

Register the hook before the subscription. `startRelaySubscription()` logs a warning and returns without subscribing if no `onMessageDecrypted` hook exists.

```ts
signal.registerHook('onMessageDecrypted', async (envelope) => {
  // Decrypted content reaches your app here, and nowhere else.
  await appDb.insertMessage({
    messageId: envelope.messageId,
    conversationId: envelope.conversationId,
    senderId: envelope.senderId,
    body: envelope.content,
    sentAt: envelope.timestamp,
  });
});

signal.startRelaySubscription();

const result = await signal.send(recipientUserId, 'hello');
// result.messageId, result.timestamp, result.recipientDeviceCount
```

Call `useSignalProtocolRelayLifecycle({ signal })` from `/hooks` in a component that lives as long as the client. It stops the subscription when the app goes to the background and starts it again when the app becomes active. See [binding the relay to the app state](https://docs.open-e2ee.dev/start/expo.md#bind-the-relay-to-the-app-state).

The `DecryptedEnvelope` your hook receives carries `messageId`, `sessionId`, `senderId`, `senderDeviceId`, `conversationId`, `content`, `timestamp`, `serverTimestamp`, `receivedAt`, `isGroup`, and `arrivedSealed`. From that moment the plaintext is yours: "Your app owns decrypted message rows and local files after the Signal Protocol client decrypts or stages them." The SDK does not keep a copy of the plaintext for you.

## Stage 5: two identities, one app [#stage-5-two-identities-one-app]

To test a round trip before you have a second device, pair the Expo client with a second client in the same app. Use `inMemoryStore()` for the peer, not a second `expoStore()`. A store holds its database name until `close()`, so a second open of the same name in one process rejects with `INVALID_STATE`.

```ts
import { inMemoryStore } from '@open-e2ee/signal-protocol-sdk/local/store/memory';

const bob = await createHostedSignalProtocolClient({
  adapters: { storage: inMemoryStore() },
  hosted: { relayUrl, getIdentityAssertion: getTestPeerAssertion },
});

bob.registerHook('onMessageDecrypted', async (m) => console.log(m.senderId, m.content));
bob.startRelaySubscription();

await signal.send(bob.userId, 'hello');
```

`getTestPeerAssertion` is a `GetIdentityAssertion` callback for a second test user. Your authentication integration supplies it. `inMemoryStore()` is development only. It does not belong in a shipped build, and it holds everything in memory, so nothing survives a reload.

Call `signal.stop()` when tearing down: it stops subscriptions and background work. If you called `bindSignalProtocolRelayLifecycle`, call the function it returned before `signal.stop()`.

## Trust boundaries [#trust-boundaries]

Three lines matter, and they are not the same line.

**Device ↔ OS.** The wrapping key uses `expo-secure-store` with `keychainAccessible: AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY`. The app can read it after the user first accesses the device, which supports background delivery. It is not eligible for iCloud Keychain sync. On Android, the platform keystore backs `expo-secure-store`. Sessions, prekeys, and message records remain in the SDK-owned SQLCipher database. A device compromise while the app is accessible exposes this data.

**Device ↔ relay.** The relay never needs message plaintext or device private keys. It does need public prekey bundles, device records, and envelopes with routing metadata. That is the line the dotted gutter marks in the diagram, and everything below the Opacity Ledger's "Sent to relay" column crosses it.

**App ↔ SDK.** "The client owns protocol coordination; the host application owns persistence, authentication, authorization, and product policy." Your database of decrypted messages, your auth, your retention rules.

## What the backend can see [#what-the-backend-can-see]

**Opacity ledger**

| Artifact | Stays on device | Sent to relay | In object store | Visible as metadata |
|---|---|---|---|---|
| Database key (`signal_protocol_sqlite_key.<name>`, in the vault) | yes | no | n/a | no |
| `identityKeyPair` private half | yes | no | n/a | no |
| `identityKeyPair` public half / `CompositeIdentityV1` | yes | yes | n/a | yes |
| `EcSignedPreKey` public half + signature | yes | yes | n/a | yes |
| `EcOneTimePreKey` public halves | yes | yes | n/a | count |
| `KemOneTimePreKey` public halves + signatures | yes | yes | n/a | count |
| `KemLastResortPreKey` public half | yes | yes | n/a | yes |
| All prekey private halves | yes | no | n/a | no |
| `SessionRecord` (`version: 4`) and ratchet state | yes | no | n/a | no |
| Message plaintext / `envelope.content` | yes | no | n/a | no |
| Envelope `ciphertext` | yes | yes | n/a | size |
| `targetUserId`, `targetDeviceId`, `senderDeviceId` | yes | yes | n/a | yes |
| `messageType`, `timestamp`, `clientMessageId` | yes | yes | n/a | yes |
| `encryptedDeviceName` | yes | yes | n/a | ciphertext length |
| Plaintext device name | yes | no | n/a | no |
| `registrationId` | yes | yes | n/a | yes |

## Review questions [#review-questions]

**Where do the keys live?** The 32-byte database key lives in `expo-secure-store` under `signal_protocol_sqlite_key.<name>`, iOS Keychain with `AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY`, Android keystore-backed. Everything else lives in the SDK-owned SQLCipher database via `ExpoSignalProtocolStore`. The device ID and a local identity public-key copy also sit in secure storage under `signal_device_id` and `signal_identity_public_key`.

**How long is anything retained?** Sessions persist until you call `deleteSession`, `archiveSession`, or `clearAllData`. `MAX_UNACKNOWLEDGED_SESSION_AGE_MS` is 30 days. Skipped message keys expire at `keyExpirationMs`: 7 days by default, capped by `maxMessageKeysStored` of 2000 for each receiver chain and `maxSkip` of 25000. Prekeys age out at `maxPreKeyAgeMs`, 14 days by default.

**How do I keep this away from my backend?** The SDK never gives private keys to a network adapter. You must keep plaintext out of backend services. For example, Supabase can hold application rows, authentication, and profile data. Keep the relay separate and limit it to envelopes and public key material.

The SDK does not provide a Supabase adapter. Implement `SignalProtocolRelayServer` from `/remote/signal-relay/types` with the responsibilities in [relay and prekeys](https://docs.open-e2ee.dev/build/relay-and-prekeys.md). Do not store `envelope.content` in Supabase and describe the result as end-to-end encrypted.

**How many prekeys, and when do they refill?**

`ONE_TIME_PREKEY_BATCH_SIZE` generates **100** EC and Kyber one-time prekeys. The store can hold at most **200** EC prekeys. The product low-water mark, `preKeyLowThreshold`, defaults to **50**. The internal replenishment threshold is **10**.

`keyRefreshIntervalMs` defaults to **172800000** (2 days). `maxPreKeyAgeMs` defaults to **1209600000** (14 days). `syncToServer()` replenishes keys. `checkPreKeyStatus()` returns `{ oneTimePreKeysRemaining, needsReplenishment }`. `onPreKeyLow(remaining)` fires at your configured threshold.

**What happens on reinstall?** iOS Keychain items can survive an uninstall, but the app sandbox and SQLCipher database do not. The SDK therefore writes a `.device-owner` sentinel into the sandbox. "A missing ownership sentinel means retained secure-storage data must not be trusted as belonging to the current installation."

`DeviceLifecycleManager` from `/device/lifecycle` models `reclaim_reinstall`, `key_mismatch`, and `orphaned_linked_device` states. It provides `handleReinstallReclaim()` and `handleKeyMismatchReset()` transitions. Its `DeviceLifecycleApi` is Convex-shaped, so connect it in the relay guide. Without recovery, a reinstall creates a new identity key and every peer sees an identity change. See [recovery, backup, migration](https://docs.open-e2ee.dev/build/recovery-backup-migration.md).

**What does the relay store?** Public prekey bundles, device records with encrypted device names, and envelopes: ciphertext plus routing metadata. Not plaintext, not private keys.

**What about backups?** The SDK has no automatic backup. `AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY` deliberately keeps the wrapping key out of iCloud Keychain, and a device-to-device path exists via `/device` (`prepareNewDeviceTransfer()`, `prepareOldDeviceTransferWithBackup()`). The managed device link, `linkHostedSignalProtocolRelayDevice()`, joins a device that already holds the account identity. It moves **no** sessions or history. Transfer and the link are two distinct operations on purpose.

> **Tradeoff — Recoverable history vs. coercion resistance**
>
> Encrypting a message archive to a key the user can restore from anywhere makes device loss survivable and makes compelled disclosure easier. Keeping the wrapping key device-only makes a lost phone a lost history. The SDK provides a device-only wrapping key by default and an explicit encrypted transfer path. Your product must choose the archive policy.

## Failure and recovery behavior [#failure-and-recovery-behavior]

> **Failure mode — Bad MAC has no class of its own, and it fails quietly**
>
> This SDK has no `BadMacError`. The `libsignal` "Bad MAC" failure appears as `EncryptionErrorCode.DECRYPTION_FAILED`, whose message names the MAC mismatch. The `EncryptionError` also contains `.code`, `.context`, and `.originalError`.
>
> In February 2026, 479 Bad MAC exceptions caused WhatsApp inbound delivery to stop without a connection error. A related project logged more than 168,000 errors across over 400 sessions in two hours. The errors exhausted the Node heap and continued after operators deleted session files. Register `onDecryptionError` and alert on the rate, not individual events. The JSDoc marks `forceCompleteKeyReset()` for development and debugging only. Treat it as a break-glass tool, not a shipped recovery step.

> **Failure mode — Prekey exhaustion is silent, and it is measured**
>
> When the relay has no unused one-time prekey, session setup uses the last-resort Kyber prekey and signed prekey. This fallback does not throw, but it weakens forward secrecy for the first message. A 2025 WhatsApp study found that 13% of companion devices lacked a one-time prekey during the scan. `PREKEY_NOT_FOUND` occurs when the relay cannot assemble a bundle. Measure `checkPreKeyStatus().oneTimePreKeysRemaining` when the app enters the foreground. Alert below `preKeyLowThreshold`.

> **Failure mode — A decrypt mutates state, so a partial write corrupts it**
>
> Every successful decrypt advances the ratchet and must persist atomically. Use SQLite transactions, and treat `KEY_STORAGE_ERROR` and `STORAGE_QUOTA_EXCEEDED` as correctness signals. Do not hide them with retries. A failed write can produce `SESSION_CORRUPTED`. Session records use `version: 4`, and "older session formats are rejected and reset instead of migrated" during an upgrade. Your UI must explain the possible reset.

> **Not covered — Attachments, groups, and linked devices**
>
> Images and files go through `client.media` and the brokered object stores: see [Encrypted attachments and object storage](https://docs.open-e2ee.dev/build/attachments-object-storage.md). Group messaging has two coexisting APIs and its own page, [Groups](https://docs.open-e2ee.dev/build/groups.md). A second device joins with the two-device link. It starts with an empty store, and device 1 approves it: [Multi-device](https://docs.open-e2ee.dev/build/multi-device.md).

## Production caveats [#production-caveats]

- The Expo store is the **primary supported adapter**, and it still requires a development build. If your distribution plan depends on Expo Go, this SDK does not fit it.
- We publish the package on npm as `15.0.x`: MIT OR Apache-2.0, reviewed continuously by adversarial AI agents, and not audited by any independent firm. Public APIs and persisted formats follow semantic versioning.
- The SDK requires `0x0A || raw ML-KEM-1024 bytes`. This encoding "is distinct from Signal Messenger deployments that use round-3 Kyber1024 tagged `0x08`." The projects are not wire-compatible or affiliated.
- Pure-JS crypto is not FIPS 140-validated. The phrase "PQXDH uses standardized FIPS 203 ML-KEM-1024 behavior" is about algorithm behavior, not validation. The default braid mode runs ML-KEM-768 with a modified encapsulation-key commitment, and the SDK makes no FIPS 203 conformance claim for that path.
- Assurance today: 384 modules, 6,893 assertions, 2 skipped, 0 failed, 330 s, with public CI running `npm ci`, build, typecheck, and `npm audit --omit=dev`.
- Plan verification UX carefully. One study found that 21 of 28 CS students could not verify a public key. Only 13% completed the ceremony after researchers explained the risks. See [identity change and safety numbers](https://docs.open-e2ee.dev/build/identity-change-safety-numbers.md).

## Next [#next]

- [Signal Protocol Relay](https://docs.open-e2ee.dev/signal-relay.md): move from the Sandbox environment to production
- [Local storage and the store contract](https://docs.open-e2ee.dev/build/local-storage.md): what `SignalProtocolLocalStore` guarantees
- [Relay and prekeys](https://docs.open-e2ee.dev/build/relay-and-prekeys.md): the contract behind `syncToServer()`
- [Error handling](https://docs.open-e2ee.dev/operate/error-handling.md) and [Production checklist](https://docs.open-e2ee.dev/operate/production-checklist.md): before this carries real traffic
