Skip to Content
OpenE2EEDocs

Build an encrypted Expo conversation from scratch

A complete Expo development build that establishes a Signal Protocol session, sends an encrypted message, and decrypts it locally, with every key custody decision stated.

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 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.

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 lists what it records.

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.

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, local-first architecture, and E2EE is not TLS first.

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

What this guide builds

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 metadataExpo deviceExpoSignalProtocolStore · SQLCipherrelaysealwrapping key · identityKeyPair private half
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

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

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:

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.

Stage 2: the store and the client

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. 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. For application-bound accounts, connect the native identity callback. 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 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

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:

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

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

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.

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

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.

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

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

Opacity ledger

ArtifactStays on deviceSent to relayIn object storeVisible as metadata
Database key (signal_protocol_sqlite_key.<name>, in the vault)yesnon/ano
identityKeyPair private halfyesnon/ano
identityKeyPair public half / CompositeIdentityV1yesyesn/ayes
EcSignedPreKey public half + signatureyesyesn/ayes
EcOneTimePreKey public halvesyesyesn/acount
KemOneTimePreKey public halves + signaturesyesyesn/acount
KemLastResortPreKey public halfyesyesn/ayes
All prekey private halvesyesnon/ano
SessionRecord (version: 4) and ratchet stateyesnon/ano
Message plaintext / envelope.contentyesnon/ano
Envelope ciphertextyesyesn/asize
targetUserId, targetDeviceId, senderDeviceIdyesyesn/ayes
messageType, timestamp, clientMessageIdyesyesn/ayes
encryptedDeviceNameyesyesn/aciphertext length
Plaintext device nameyesnon/ano
registrationIdyesyesn/ayes

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. 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.

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.

Failure and recovery behavior

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.

Next

On this page