# Build a browser E2EE demo with two local identities (https://docs.open-e2ee.dev/guides/browser-two-identities.md)

- Status: stable
- Applies to: 15.0.0
- Platforms: Browser
- Prereqs: Node 22.18+, any bundler that serves ES modules, and a browser with IndexedDB
- Reading time: 14 min

This example shows two identities and an encrypted round trip in one page. It lists the envelope fields that the relay can read and shows the plaintext that the app renders. The cryptography is real. A Sandbox environment of the OpenE2EE Signal Protocol Relay carries the envelopes.

[Run the playground](https://open-e2ee.dev/playground/) to see a message and reply with real console output. This guide adds IndexedDB storage for Alice.

> **A supported store inside a demo stack**
>
> `IndexedDbSignalProtocolStore` / `indexedDbStore()` from `/local/store/web` is a supported adapter: it implements the full `SignalProtocolLocalStore` contract, and its graduation gates (real-browser contract suites, multi-tab, interruption, storage-pressure, and soak) run on every change to the source repository. The rest of this page's stack is not production material. Bob's store is in memory. The Sandbox identity helper works only in a Sandbox environment. The Sandbox environment has test limits and no production roots. The browser threat model needs its own review. Do not ship this page's stack to production users without reading [Production caveats](https://docs.open-e2ee.dev/guides/browser-two-identities.md#production-caveats) at the bottom, twice.

## Intended audience [#intended-audience]

Use this guide to evaluate the SDK with a short feedback loop or build a browser-only internal tool. Browser E2EE has a structural limitation that no library fixes.

## Prerequisites [#prerequisites]

- Node 22.18 or newer and any bundler serving ES modules (Vite is fine). The SDK needs Node 22.12 or newer. The `oe` command needs Node 22.18 or newer.
- A Relay project from the [Sandbox quickstart](https://docs.open-e2ee.dev/signal-relay.md#sandbox-quickstart). `oe new` writes its Sandbox connection URL to `.env.local`. In a Vite app, the variable is `VITE_OPEN_E2EE_SIGNAL_RELAY_URL`, and the app reads it as `import.meta.env.VITE_OPEN_E2EE_SIGNAL_RELAY_URL`.
- No identity provider. In the Sandbox environment, `hostedSignalProtocolRelaySandboxIdentity(storage)` from the SDK creates the identity assertion callback of each identity. The helper works only in a Sandbox environment.
  Every environment, Production included, starts device-owned.
  Use your application identity integration for application-bound accounts.
  Select the custom-token profile before the first device registers.
  See [identity and authentication](https://docs.open-e2ee.dev/signal-relay/identity.md).
- A browser with IndexedDB. No native modules, no build plugins, and no WASM. Only the optional persistent store for Bob in Stage 1 uses WASM.
- [E2EE is not TLS](https://docs.open-e2ee.dev/learn/e2ee-vs-tls.md) and [Threat model](https://docs.open-e2ee.dev/learn/threat-model.md). The second one matters more here than on any other page.

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

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

**Figure:** Two identities inside one browser page, each with its own local store, exchanging a sealed envelope across a trust boundary through a Sandbox environment of the Signal Protocol Relay. Both identities run in one page, and the boundary is real. Left of the dotted gutter, the content is readable. Right of it, the envelope is a solid sheared slab with metadata ticks along its top edge. The demo shows both sides at once.

## Install [#install]

```bash
npm install @open-e2ee/signal-protocol-sdk@latest idb
```

The browser store uses IndexedDB through the peer `idb`, and Web Crypto.

## Stage 1: two identities, one Sandbox environment [#stage-1-two-identities-one-sandbox-environment]

The browser adapter opens a fixed IndexedDB database named `signal-protocol-storage`. There is no per-instance database name, so two `indexedDbStore()` instances in one origin share one database and one identity. For the second identity in this demo, use `inMemoryStore()`: in-memory, development only, and honest about it.

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

// The Sandbox connection URL that `oe new` wrote to .env.local.
const relayUrl = import.meta.env.VITE_OPEN_E2EE_SIGNAL_RELAY_URL;

const aliceStorage = await indexedDbStore();
const alice = await createHostedSignalProtocolClient({
  adapters: { storage: aliceStorage },
  // Sandbox only. Select the Production identity mode explicitly.
  hosted: { relayUrl, getIdentityAssertion: hostedSignalProtocolRelaySandboxIdentity(aliceStorage) },
});

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

`hostedSignalProtocolRelaySandboxIdentity` keeps the account key of each identity in the store that you pass to it, so pass the same store as `adapters.storage`. Alice's key stays in IndexedDB, and Alice keeps her Sandbox account across page loads.

> **An in-memory store makes a new Sandbox test account on each page load**
>
> Bob's in-memory store loses his account key when the page unloads. So each page load creates a new Sandbox test account for Bob. The [Sandbox boundary](https://docs.open-e2ee.dev/signal-relay.md#sandbox-boundary) gives the number of test accounts that the environment includes.

To keep Bob's account across page loads, open his store with the web SQLite store. It keeps a database file in the origin private file system, separate from Alice's IndexedDB database:

```ts
import { webSqliteStore } from '@open-e2ee/signal-protocol-sdk/local/store/web-sqlite';

const bobStorage = await webSqliteStore({ name: 'bob.db' });
```

That store runs WebAssembly in a worker and needs a CSP that allows `'wasm-unsafe-eval'`. [Browser setup](https://docs.open-e2ee.dev/start/browser.md) gives its requirements.

`indexedDbStore()` is async because it calls `initialize()` for you: it opens the database, creates the object stores, and generates or loads a 32-byte database key. On first run it prints a warning to the console, verbatim:

```
[IndexedDbSignalProtocolStore] Database encryption key stored in IndexedDB. Ensure Content Security Policy (CSP) is configured to mitigate XSS risks.
```

That warning is not decoration. Come back to it after the round trip.

`createHostedSignalProtocolClient()` creates or loads each identity and its prekeys, registers the device with the Relay, and uploads only public halves and signatures. The Relay assigns each account ID, and `userId` returns it. Post-quantum policy is `postQuantum: 'required'` and `braid: 'required'` by default. Both identities here satisfy it, so session establishment is PQXDH end to end.

## Stage 2: send, then look at what left the device [#stage-2-send-then-look-at-what-left-the-device]

This is the moment the demo exists for. Send first, and look at what `send()` returns:

```ts
const result = await alice.send(bob.userId, 'the auditor asks what the server can read');

console.log({
  messageId: result.messageId,                // assigned by the Relay
  clientMessageId: result.clientMessageId,
  timestamp: result.timestamp,                // when the Relay accepted it
  recipientDeviceCount: result.recipientDeviceCount,
});
```

The result holds no plaintext. The Relay holds the message as an `Envelope`, the type that `/remote/signal-relay` exports. It has the `ciphertext` and these routing fields: `targetUserId`, `targetDeviceId`, `senderUserId`, `senderDeviceId`, `messageType`, `deliveryClass`, `timestamp`, `serverTimestamp`, `id`, `clientMessageId`, `operationEpochMilliseconds`, `recipientRegistrationId`, `contentHint`, and `contentKind`. The last seven are optional. `contentKind` tells the relay whether the envelope is a `message` or a `receipt`.

The ciphertext is base64 or bytes. It is not searchable, summarizable, or readable without the recipient's session state. Every other field remains readable: participants, target device, time, size, and envelope type. The first message has the `messageType` `prekey_bundle`, so the relay can see whether this is a first contact or an established conversation.

Now open the other side:

```ts
bob.registerHook('onMessageDecrypted', async (message) => {
  renderBubble({ from: message.senderId, body: message.content });
});

bob.startRelaySubscription(); // delivery and local decryption start here
```

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

The `DecryptedEnvelope` includes `messageId`, `sessionId`, `senderId`, `senderDeviceId`, `conversationId`, `content`, `timestamp`, `serverTimestamp`, `receivedAt`, `isGroup`, and `arrivedSealed`. Put the two panels side by side. The relay panel shows the `SendResult` values and lists the `Envelope` fields that the Relay can read. The app panel shows the decrypted content. Only the app panel holds the plaintext, while both panels show its metadata.

## Stage 3: inspect the store itself [#stage-3-inspect-the-store-itself]

Open DevTools → Application → IndexedDB → `signal-protocol-storage`. The object stores are `metadata`, `identity`, `contacts`, `prekeys`, `sessions`, `securityEvents`, `sesameUsers`, `senderKeyRecords`, `skippedSenderKeys`, and `messageRecords`. Record values are AES-256-GCM ciphertext with a 12-byte IV.

Then open `metadata` and find the key `databaseKey`. Those are the raw 32 bytes that decrypt everything else, sitting in the same database as the records they protect.

## Browser-specific honesty [#browser-specific-honesty]

This section is longer than the build. That ratio is deliberate: this is where web E2EE claims usually overreach.

### The code-delivery problem is not solved [#the-code-delivery-problem-is-not-solved]

The server in this threat model also ships the JavaScript that encrypts data. It can serve a different bundle to one user. Client-side cryptography inside that bundle cannot detect the change. The state of the art is honest about this: "these mechanisms for trusting web apps are still pretty early and there's no blessed path." Subresource integrity binds a bundle to a hash from the same server. Code-transparency schemes exist but lack broad deployment. If your threat model includes your origin, use an installed application with a signed update channel.

### Non-extractable keys would be a signing oracle anyway: and here they are not even that [#non-extractable-keys-would-be-a-signing-oracle-anyway-and-here-they-are-not-even-that]

A common browser mitigation is a non-extractable `CryptoKey` handle in IndexedDB. XSS on your origin can read the handle from IndexedDB. The malicious code can then call `sign()` or `decrypt()` with chosen input while the page remains open. "The attacker never touches the raw key bytes" and does not need to.

Be precise about what this adapter does, because it is not even that. It generates 32 random bytes with `crypto.getRandomValues` and persists them in the `metadata` store. Each operation re-imports them with `crypto.subtle.importKey('raw', …, extractable: false, …)`, so the *imported handle* is non-extractable, but the raw bytes are already sitting in the database. The SDK's own README states the boundary: this "protects record contents from a copy that does not also contain the metadata key. It does not protect against JavaScript running with the application's origin, because that code can access both the encrypted records and their encryption key… Encryption at rest is therefore not an XSS defense."

Use a restrictive Content Security Policy in response headers. Prohibit inline and evaluated scripts, and minimize third-party scripts. Escape untrusted content through the framework. Review dependency and service-worker updates. Provide an account-reset path that deletes IndexedDB and other same-origin state.

### WebCrypto has no streaming API [#webcrypto-has-no-streaming-api]

Issue w3c/webcrypto#73 opened in May 2016 and still tracks this gap. `crypto.subtle.encrypt` takes and returns a complete buffer. A tab must either hold a 2 GB file in memory or implement chunked AEAD framing. The second option requires custom nonce rules and integrity chaining. See [encrypted attachments and object storage](https://docs.open-e2ee.dev/build/attachments-object-storage.md).

### X25519 in WebCrypto still is not everywhere [#x25519-in-webcrypto-still-is-not-everywhere]

X25519 has 84.45% global support: Chrome and Edge 133+, Firefox 130+, and Safari 17.0+. About 15% of browser traffic cannot use it natively. A library that uses WebCrypto key agreement would not run for those users. This SDK instead implements the protocol in TypeScript with `@noble/curves` and `@noble/post-quantum`. The demo therefore runs in browsers where WebCrypto cannot exchange keys. Pure TypeScript lets the demo support this browser set.

## 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 |
|---|---|---|---|---|
| `databaseKey` (IndexedDB `metadata`) | yes | no | n/a | no |
| `identityKeyPair` private half (`identity`) | 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 |
| All prekey private halves (`prekeys`) | yes | no | n/a | no |
| `SessionRecord` (`version: 4`), `sessions` store | yes | no | n/a | no |
| Contact trust records (`contacts`) | yes | no | n/a | no |
| `messageRecords`, `skippedSenderKeys`, `sesameUsers` | 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 |

## Review questions [#review-questions]

**Where do the keys live?** In IndexedDB, database `signal-protocol-storage`, via `IndexedDbSignalProtocolStore`. Private key material sits in the `identity` and `prekeys` object stores as AES-256-GCM ciphertext. The key that decrypts it sits in `metadata` under `databaseKey`. There is no OS keychain involved and no browser API that would provide one.

**How long is anything retained?** Data remains until the browser clears the origin's storage or you delete it. Sessions persist until `deleteSession`, `archiveSession`, or `clearAllData`. `MAX_UNACKNOWLEDGED_SESSION_AGE_MS` is 30 days. Skipped message keys expire after `keyExpirationMs`, which defaults to 7 days. The limits are `maxMessageKeysStored` 2000 for each receiver chain and `maxSkip` 25000. Browser eviction under storage pressure remains outside your control.

**How do I keep this away from my backend?** The SDK does not give private keys to a network adapter. Your application code creates the primary risk. Do not log `envelope.content`, send decrypted bodies to analytics, or include plaintext in server-rendered data. Remember that your backend ships code that could complete all three actions.

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

Each batch contains **100** one-time prekeys for both EC and Kyber.

`ONE_TIME_PREKEY_BATCH_SIZE` defines this batch, and the maximum is **200** EC prekeys.

`preKeyLowThreshold` defaults to **50**, while the internal replenishment threshold is **10**.

`keyRefreshIntervalMs` is **172800000** (2 days). `maxPreKeyAgeMs` is **1209600000** (14 days). `syncToServer()` replenishes keys. `checkPreKeyStatus()` returns `{ oneTimePreKeysRemaining, needsReplenishment }`.

**What happens when the user clears site data?**

This action is the browser equivalent of a reinstall. Users can trigger it by accident, and some browsers remove data under storage pressure or after inactivity. The browser removes the identity key, sessions, and private prekeys. The device then needs a new identity, so every peer sees an identity change.

Handle `UntrustedIdentityError` through `.untrustedAddress` and `.identity`. Use `acceptIdentityRotation(userId, identity, identityType?)`. The method `trustIdentity()` does not exist. See [identity change and safety numbers](https://docs.open-e2ee.dev/build/identity-change-safety-numbers.md).

**What does the relay store?** Public prekey bundles, device records, and envelopes: ciphertext plus routing metadata. A relay that you build keeps what its schema keeps. The relay never needs message plaintext or device private keys.

**What about backups?** There are none, and there is no browser API that would give you a durable, device-bound key store to build one on. A browser-only deployment means device loss is history loss unless you design an explicit encrypted export. [Recovery, backup, migration](https://docs.open-e2ee.dev/build/recovery-backup-migration.md) covers what the SDK does offer.

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

> **Failure mode — Two tabs, one database, one ratchet**
>
> Two tabs on the same origin open the same `signal-protocol-storage` database and the same session records. The store's multi-tab gate validates its compare-and-set contract in real browsers on every change: conflicting writes resolve to one winner, and the loser is told instead of silently overwriting, so two tabs cannot silently corrupt a record. What no store contract can do is merge two ratchets. A decrypt mutates session state, so concurrent decrypts across tabs still contend for one ratchet, and the losing tab's advance is lost. The symptoms are `SESSION_CORRUPTED`, or `DECRYPTION_FAILED` on messages that were valid at send time. Run one client per origin: a leader-elected tab or a single shared worker.

> **Failure mode — Undecryptable messages are hard to triage, by construction**
>
> There is no `BadMacError` class. Tampering and mismatch produce `DECRYPTION_FAILED` on an `EncryptionError`. Inspect its `.code`, `.context`, and `.originalError`.
>
> Matrix's undecryptable-message meta-issue lists more than 70 causes. Its maintainers state the constraint directly: "we need logs from the receiver of the message and those from the sender. We generally can't debug issues without logs from both sides." Correlate `clientMessageId` and `sessionId`, retain breadcrumbs from both parties, and never log key material.
>
> Element shipped a bug where "the private part of the backup key pair [was] logged to application debug logs… 156 unique Matrix IDs have been affected." Debug logs are a separate vulnerability class. See [observability](https://docs.open-e2ee.dev/operate/observability.md).

> **Not covered — Making this an actual product**
>
> This page stops at the round trip. A real browser deployment needs production identity setup, a CSP, an account-reset path, and a decision about multi-tab. For the [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). The Relay is not browser-specific. If you build your own relay, the contract is in [Relay and prekeys](https://docs.open-e2ee.dev/build/relay-and-prekeys.md).

## Production caveats [#production-caveats]

- **The demo stack is not a product.** `inMemoryStore()` and the Sandbox environment are development only. A real deployment needs the origin-security review in [browser setup](https://docs.open-e2ee.dev/start/browser.md). Nothing on this page should reach production users unchanged.
- 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.
- Not wire-compatible with Signal Messenger and not affiliated with it: public keys and ciphertexts require exactly `0x0A || raw ML-KEM-1024 bytes`, and "the `0x0A` encoding is distinct from Signal Messenger deployments that use round-3 Kyber1024 tagged `0x08`."
- Pure-JS crypto is not FIPS 140-validated. The "FIPS 203 ML-KEM-1024 behavior" quote describes 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.
- E2EE is not anonymity and it is not compliance. The relay still sees who talks to whom, when, and how much: see [Limits and metadata](https://docs.open-e2ee.dev/learn/limits-and-metadata.md).

## Next [#next]

- [Build an encrypted Expo conversation from scratch](https://docs.open-e2ee.dev/guides/expo-encrypted-chat.md): the primary supported adapter
- [Choosing adapters](https://docs.open-e2ee.dev/start/choosing-adapters.md): what each store is and is not validated for
- [Threat model](https://docs.open-e2ee.dev/learn/threat-model.md): where a browser deployment lands in it
- [Error handling](https://docs.open-e2ee.dev/operate/error-handling.md): the full dispatch table for `EncryptionErrorCode`
