# Expo (https://docs.open-e2ee.dev/start/expo.md)

- Status: stable
- Applies to: 15.0.0
- Platforms: Expo (development build) · React Native
- Prereqs: Quickstart, plus an Expo project you can make a development build of
- Reading time: 12 min

The SDK runs 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 device-local storage.

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

> **SQLCipher requires a native build**
>
> Use an Expo development or release build with SQLCipher enabled. Expo Go does not include SQLCipher. This page contains the native configuration and storage setup.

## Install [#install]

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

The SDK reads random bytes only from the global `crypto.getRandomValues`. Load `react-native-get-random-values` 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`.

## Two storage boundaries, never blurred [#two-storage-boundaries-never-blurred]

The Expo setup has two distinct places secrets live, and conflating them is the most consequential mistake you can make here.

| | Holds | Size | Facility |
|---|---|---|---|
| **Vault** | One database encryption key | 32 bytes | `expo-secure-store` → iOS Keychain / Android Keystore |
| **Store** | Identity keys, prekeys, sessions, ratchet state, contact trust, message records | Kilobytes to megabytes | SQLCipher-encrypted SQLite |

Platform secret managers hold tiny bootstrap values, not a session database that changes on every message. So the vault holds exactly one thing, the key that unlocks the database, and the database holds everything else.

## Open the store [#open-the-store]

The SDK owns the database: its file, its key, and its migrations. Enable SQLCipher in the `expo-sqlite` config plugin, then open the store with one call and pass it to the client:

```json
{
  "expo": {
    "plugins": [["expo-sqlite", { "useSQLCipher": true }], "expo-secure-store"]
  }
}
```

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

const signal = await createHostedSignalProtocolClient({
  adapters: { storage: await expoStore() },
  // relayUrl: the Relay connection URL. Use a Sandbox URL during development.
  hosted: { relayUrl, getIdentityAssertion },
});

signal.registerHook('onMessageDecrypted', (envelope) => {
  appendToConversation(envelope.conversationId, envelope.content);
});

signal.startRelaySubscription();
```

`getIdentityAssertion` is your code. For application-bound accounts, it calls your backend over HTTPS with the app's session credential. See the [native identity callback](https://docs.open-e2ee.dev/signal-relay/custom-token.md#native-apps-react-native-and-expo). In a Sandbox environment configured for device-owned identity, open the `expoStore()` store once. Pass it to `hostedSignalProtocolRelaySandboxIdentity()` and as `adapters.storage`. See [identity and authentication](https://docs.open-e2ee.dev/signal-relay/identity.md#sandbox-first).

`await expoStore()` opens the database in the `expo-sqlite` default directory. On first use it creates the 32-byte database key in the vault, then the database file. Each open applies the SDK migrations before it returns the store. The options are `name` (the file name, default `open-e2ee-signal-protocol.db`), `vault` (default `ExpoSecureStoreSignalProtocolSecretVault`), `encryptionAtRest`, and `logger`. Keep your application tables in a separate database file. The SDK database holds only SDK tables.

A store holds its name until `close()`. A second open of the same name in the process rejects with `INVALID_STATE`. A build without SQLCipher rejects with `KEY_STORAGE_ERROR`, because the store refuses a database that reports no cipher.

## Bind the relay to the app state [#bind-the-relay-to-the-app-state]

Stop the relay subscription when the app goes to the background, and start it again when the app becomes active. `useSignalProtocolRelayLifecycle` from `/hooks` makes both calls from React Native's `AppState`:

```tsx
import { useSignalProtocolRelayLifecycle } from '@open-e2ee/signal-protocol-sdk/hooks';

function SignalProtocolRelayLifecycle({ signal }) {
  useSignalProtocolRelayLifecycle({ signal });
  return null;
}
```

- **`background`** calls `stopRelaySubscription()`, which closes the socket with code `1000`. The Relay records a client close.
- **`active`** calls `startRelaySubscription()`, but only after a stop that the binding made. The Relay replays retained messages over the new socket.
- **`inactive`** changes nothing. There is no grace delay.

A stop that your app made stays in effect. Set `keepOpenInBackground: true` to keep the socket open in the background, for example while an Android foreground service runs.

Outside React, call `bindSignalProtocolRelayLifecycle(signal, AppState)` from `/client`. It returns a function that removes the binding. Call that function before `signal.stop()`:

```ts
import { AppState } from 'react-native';
import { bindSignalProtocolRelayLifecycle } from '@open-e2ee/signal-protocol-sdk/client';

const unbind = bindSignalProtocolRelayLifecycle(signal, AppState);

// At sign-out:
unbind();
await signal.stop();
```

For an indicator of this device's connection, use `useSignalProtocolRelayConnectionState({ signal })`. It returns the `SignalProtocolRelayConnectionState`, and the component renders again on each transition. The state is local to this device. It is not presence and tells you nothing about other users. For other users, read [presence](https://docs.open-e2ee.dev/signal-relay/presence.md).

---

## The seven questions [#the-seven-questions]

These come up in every integration. Direct answers, from the SDK's actual behavior, with the boundary marked wherever the SDK leaves the decision to you.

### 1. Where are the keys stored? [#1-where-are-the-keys-stored]

The database key is a random 32-byte AES-256 key held under the identifier `signal_protocol_sqlite_key.<name>`, by default `signal_protocol_sqlite_key.open-e2ee-signal-protocol.db`, by `ExpoSecureStoreSignalProtocolSecretVault`, which is a thin wrapper over `expo-secure-store`. That resolves to the **iOS Keychain** and the **Android Keystore**-backed secure storage.

The code sets the accessibility class deliberately:

```ts
keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY
```

`AFTER_FIRST_UNLOCK` lets background message delivery and recovery work during a screen lock. `THIS_DEVICE_ONLY` excludes the value from encrypted device backups and transfer to a new device. This exclusion is a security property, and it also explains the answer to question 5.

The SQLCipher database contains all other protocol data. This data includes identity keys, prekeys, sessions, ratchet state, contact trust decisions, and message records.

### 2. How long are they retained? [#2-how-long-are-they-retained]

Different lifetimes for different material, and none of it is on a session timer:

| Material | Retention |
|---|---|
| Identity key pair | Indefinite. It *is* the identity; rotating it is an identity change your contacts will see. |
| Signed prekey / Kyber prekey | Rotated on `keyRefreshIntervalMs`, default `172800000` — **2 days**. Old keys are kept briefly so in-flight messages still decrypt. |
| One-time prekeys | Until consumed by an incoming session, or until `maxPreKeyAgeMs` (14 days) makes them replaceable. |
| Session and ratchet state | Indefinite, until the session is archived or deleted. |
| Skipped message keys | `maxMessageKeysStored` 2000 for each receiver chain, and `keyExpirationMs` 7 days. |
| Unacknowledged sessions | `MAX_UNACKNOWLEDGED_SESSION_AGE_MS`, 30 days. |

> **Ignore the stale weekly comment**
>
> Two JSDoc comments in the SDK still say to rotate signed prekeys "weekly". They are stale, and the TypeDoc generator carries that stale text into its output. The `keyRefreshIntervalMs` default of `172800000`, two days, is authoritative.

### 3. How do I keep keys away from my own backend? [#3-how-do-i-keep-keys-away-from-my-own-backend]

The SDK does not contain a code path that sends a private key. `syncToServer()` uploads only public material. This material includes the identity public key, signed prekey and signature, Kyber prekeys, and the one-time prekey batch. The SDK writes the private keys to the local store and reads them from that store.

The realistic leak is not the SDK, it is your app. Named concretely, because this is the question people actually ask about Supabase, Firebase, and every analytics SDK in a React Native project:

- **Do not put protocol state in a synced table.** Do not add a key column to a synced `profiles` or `devices` row. The relay handles public keys and envelopes. The `SignalProtocolRelayServer` interface does not accept private material.
- **Do not log envelopes or store handles.** Crash reporters and session-replay tools serialize objects aggressively. Add protocol objects to the redaction list.
- **Avoid syncing filesystems.** A provider could receive both the encrypted database and its escaped keychain value.
- **Do not send plaintext to your backend "for search".** Server-side message search can break end-to-end encryption. Build the index on the device.

> **Tradeoff — Your backend still sees a great deal**
>
> Keeping private keys local does not make your backend blind. It sees who registered, which devices exist, who fetched whose prekey bundle, who sent an envelope to whom, when, and how big it was. If your product promise is stronger than that, read [what the relay can still see](https://docs.open-e2ee.dev/learn/limits-and-metadata.md) and adjust the promise, not the documentation.

### 4. How many prekeys, and when do they refill? [#4-how-many-prekeys-and-when-do-they-refill]

You do not choose the batch size. The SDK generates **100** one-time prekeys at registration and on replenishment. The numbers that matter to you:

| Setting | Default | Meaning |
|---|---|---|
| One-time prekey batch | 100 | Generated per replenishment round. |
| `preKeyLowThreshold` | 50 | When `checkPreKeyStatus()` reports `needsReplenishment` and `onPreKeyLow` fires. |
| Internal replenishment threshold | 10 | The hard floor the client replenishes at on its own. |
| `preKeyCheckThrottleMs` | 12 hours | How often a check will actually run. |

Wire it to something that runs when the app foregrounds:

```ts
const status = await signal.checkPreKeyStatus();
// { oneTimePreKeysRemaining, needsReplenishment }
```

> **Failure mode — Prekey exhaustion can be silent**
>
> Other people consume your one-time prekeys when they start sessions with you. A popular user can exhaust them during app closure. When the relay has none left, a sender gets `PREKEY_NOT_FOUND`. Last-resort keys can still establish sessions, but they provide weaker forward secrecy for the initial message. The sender sees the failure, but you do not. Replenish when the app enters the foreground and receives a push, not only when it starts.

### 5. What happens when the user reinstalls the app? [#5-what-happens-when-the-user-reinstalls-the-app]

**They lose everything, and this is not recoverable by the SDK.**

Uninstalling removes the app's SQLCipher database. The vault entry is `THIS_DEVICE_ONLY` and excluded from backups. On iOS, keychain items can sometimes survive an app uninstall. Do not depend on this behavior because a surviving key cannot decrypt a deleted database.

So after a reinstall the user is, cryptographically, a new device:

- New identity key pair, new registration ID, new prekeys.
- Every existing session is dead. Message history encrypted locally is gone.
- Every existing contact sees an **identity change**. The next message produces `UntrustedIdentityError` or a safety-number change in the UI.
- The new identity cannot decrypt messages that peers sent to the old identity while it was still current.

This is the correct behavior for a protocol with forward secrecy and no key escrow, and it is also the moment your support burden appears. Decide the product response deliberately: [recovery, backup, and migration](https://docs.open-e2ee.dev/build/recovery-backup-migration.md) sets out three named profiles with different tradeoffs and no default. Whatever you pick, handle the contact-side experience in [identity change and safety numbers](https://docs.open-e2ee.dev/build/identity-change-safety-numbers.md) rather than letting a raw error reach the UI.

### 6. What does the relay store? [#6-what-does-the-relay-store]

Public material and opaque envelopes. Nothing that decrypts anything.

**Opacity ledger**

| Artifact | Stays on device | Sent to relay | In object store | Visible as metadata |
|---|---|---|---|---|
| `identityKeyPair` (private) | yes | never | never | no |
| Identity public key | yes | yes | no | yes — it is the pinned identity |
| Signed prekey + signature | yes | yes (public) | no | yes |
| Kyber prekeys | yes (private) | yes (public) | no | yes |
| One-time prekeys | yes (private) | yes (public) | no | count and consumption are observable |
| Session / ratchet state | yes | never | never | no |
| Message plaintext | yes | never | never | no |
| Message ciphertext | yes | yes | no | size and timing |
| `senderUserId`, `targetUserId`, device IDs | yes | yes | no | **yes — the social graph** |
| `timestamp`, `messageType`, `clientMessageId` | yes | yes | no | yes |
| Attachment bytes | encrypted first | no | yes, opaque | size, count, timing |
| Attachment media key | yes | in the encrypted message | never | no |

The database key and the SQLCipher database never appear in the "sent to relay" column under any configuration. There is no mode that changes that.

### 7. What should I do about backups? [#7-what-should-i-do-about-backups]

The SDK does not include a backup mechanism, and the keychain entry is deliberately excluded from device backups. Without a backup, an uninstall or lost phone means lost history and a new identity. This product choice is defensible and resembles the Signal Messenger approach, but you must make it deliberately.

The three positions, all legitimate, all with something given up:

- **No backup.** Strongest confidentiality, worst user experience on device loss. Users will lose history and blame you.
- **User-held key backup.** The user holds a recovery secret that you cannot reproduce. History restores if they kept it. Signal Messenger uses a 64-character recovery key that "Signal cannot recover, reset, or bypass" and therefore protects the key at the cost of more complex support.
- **Provider-assisted escrow.** This option gives the best recovery experience. You then hold data that can decrypt user content. That responsibility changes your threat model, compliance surface, and product claims.

> **Tradeoff — Recovery creates a weak point**
>
> 1Password states it plainly: "Recovery mechanisms are inherently weak points in maintaining the secrecy of data." A mechanism that restores access after total loss can also restore access to the wrong person. Choose where that weakness belongs and document it for your users.

Device-to-device **transfer** is different from backup. It moves cryptographic state directly between two user-controlled devices, with no third-party storage.

The **managed device link** adds a device to the account. In the two-device link, a new device with an empty store joins, and device 1 approves it. The one-process link joins a store that already holds the account identity. Neither link moves sessions or message history. See [multi-device](https://docs.open-e2ee.dev/build/multi-device.md) and [device lifecycle](https://docs.open-e2ee.dev/build/device-lifecycle.md).

Full treatment, with three named profiles you can adopt as-is: [recovery, backup, and migration](https://docs.open-e2ee.dev/build/recovery-backup-migration.md).

---

## Production caveats [#production-caveats]

> **Not covered**
>
> This page gives you a working client. It does not cover production identity setup. For the [OpenE2EE Signal Protocol Relay](https://docs.open-e2ee.dev/signal-relay.md), continue with [identity and authentication](https://docs.open-e2ee.dev/signal-relay/identity.md), then connect the [native identity callback](https://docs.open-e2ee.dev/signal-relay/custom-token.md#native-apps-react-native-and-expo). Read [relay and prekeys](https://docs.open-e2ee.dev/build/relay-and-prekeys.md) if you implement `SignalProtocolRelayServer` yourself.

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

> Reviewed continuously by adversarial AI agents; not audited by any independent firm.

 Verify behavior on both iOS and Android **release** builds, not just in development: secure-storage and background-delivery behavior differ.

## Next [#next]

- [Build an encrypted Expo conversation from scratch](https://docs.open-e2ee.dev/guides/expo-encrypted-chat.md): the complete build, end to end.
- [Local encrypted storage](https://docs.open-e2ee.dev/build/local-storage.md): the store and vault boundary in full.
- [Choosing adapters](https://docs.open-e2ee.dev/start/choosing-adapters.md): if Expo is not the only runtime you ship.
- [Production checklist](https://docs.open-e2ee.dev/operate/production-checklist.md): before you ship.
