# Browser (https://docs.open-e2ee.dev/start/browser.md)

- Status: stable
- Applies to: 15.0.0
- Platforms: Browsers with Web Crypto, and the origin private file system or IndexedDB
- Prereqs: Quickstart
- Reading time: 14 min

[Run an encrypted exchange in your browser](https://open-e2ee.dev/playground/). The page and developer console show actual ciphertext, decrypted messages, and a reply. The example needs no account.

> **Browser storage and origin security**
>
> From 8.1.0, the web SQLite store is the browser store where the origin private file system works, and the IndexedDB store is the store where it is not available. Both stores pass storage contracts in Chromium, Firefox, and WebKit. Scripts on your origin can access stored records and their key. Use a restrictive CSP and review the browser threat model below.

## Install [#install]

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

Both stores need the peer `idb` 8.0.3 or later. The web SQLite store keeps its database key in IndexedDB through it, and the IndexedDB store opens its database through it.

## Setup [#setup]

`webSqliteStore` runs SQLite3 Multiple Ciphers, compiled to WebAssembly, in one dedicated module worker. It keeps an SDK-owned database file in the origin private file system, encrypted in the SQLCipher 4 format, with a 32-byte key in a secret vault. The default vault keeps the key in IndexedDB in the same origin.

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

// Async: it opens the database and applies the SDK migrations before returning.
const storage = await webSqliteStore();

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

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

signal.startRelaySubscription();
```

`webSqliteStore()` and `indexedDbStore()` return promises, unlike `inMemoryStore()`. That difference is easy to trip on when you replace the development store.

Keep the relay subscription running while the tab is hidden. Do not call `stopRelaySubscription()` from a `visibilitychange` handler. A hidden tab keeps its socket open, and `useSignalProtocolRelayLifecycle` does nothing on web. For a connection indicator, read `signal.relayConnectionState` and listen with `signal.subscribeRelayConnectionState(listener)`.

### Content Security Policy [#content-security-policy]

The engine compiles WebAssembly in its worker. A Content Security Policy that applies to the worker must allow it with `'wasm-unsafe-eval'` in `script-src`. The store needs no other relaxation: no `'unsafe-eval'`, no `blob:` worker, and no inline script.

```text
Content-Security-Policy: default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self'; connect-src 'self'
```

- Send the header on the worker script response. A module worker takes the policy of its own response, not the policy of the page. A site that sends one policy on every response adds `'wasm-unsafe-eval'` to that policy.
- `worker-src` must allow the worker script, and `connect-src` must allow the Wasm file.
- Serve `sqlite3.wasm` as `application/wasm`.
- Emit the worker and `sqlite3mc/sqlite3.wasm` next to the module that creates the driver, as the package lays them out. Most bundlers resolve the default URLs. Otherwise pass `workerUrl` and `wasmUrl`.

Without `'wasm-unsafe-eval'`, the open fails with `SQLITE_ENGINE_UNAVAILABLE`.

### Where the origin private file system is not available [#where-the-origin-private-file-system-is-not-available]

Some browser contexts cannot keep a file in the origin private file system: some private or ephemeral contexts, WebKit on Linux, and other runtimes without synchronous access handles in a worker. The open then fails with `OPFS_UNAVAILABLE` before it loads the engine. Use the IndexedDB store in that runtime:

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

async function openStorage() {
  try {
    return await webSqliteStore();
  } catch (error) {
    if (error instanceof EncryptionError && error.code === EncryptionErrorCode.OPFS_UNAVAILABLE) {
      return indexedDbStore();
    }
    throw error;
  }
}
```

The two stores do not share data. Choose one for each runtime, and do not move to the other after an error that is not `OPFS_UNAVAILABLE`.

## Before the seven questions: the browser problem [#before-the-seven-questions-the-browser-problem]

Two things are true about browser E2EE that do not apply to the Expo build, and neither is fixable by choosing a better storage adapter.

**The server in your threat model ships the code that encrypts.** Each page load downloads your JavaScript from your origin. A reviewer checks a native app. Its publisher signs it, and a user installs it on a device.

The server can deliver a web application differently for each user or load. Subresource integrity and code-transparency proposals exist. However, no generally accepted path establishes trust in web application code. This is a structural platform property.

**Non-extractable keys are not a safety guarantee.** Web Crypto can mark a key as non-extractable and store it in IndexedDB. An attacker then cannot extract the raw bytes. However, a script on your origin can read the handle from IndexedDB. It can call `sign()` or `decrypt()` with attacker-selected input while the page is open. The attacker does not need the raw key bytes. Under XSS, a non-extractable key is a signing and decryption oracle.

The SDK store guides state the same limit for encryption at rest. The web SQLite store's default vault keeps the database key in IndexedDB, in the same origin as the database file. "The key protects a copy of the database file that does not also include that IndexedDB record. It does not protect against script that runs in the origin (XSS), a browser extension with access to the site, malware that reads the browser profile, or a copy of the full profile." The IndexedDB store creates a random 32-byte database key in its IndexedDB metadata store. It "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."

> **Failure mode — Encryption at rest is not an XSS defense**
>
> A script injection or compromised dependency on your origin can observe plaintext and invoke the signed-in client. No storage adapter changes this. Use a restrictive Content Security Policy in response headers. Avoid inline and evaluated scripts, minimize third-party scripts, and control the dependency supply chain. These are the applicable controls. The storage layer is not one of them.

---

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

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

With the web SQLite store, in an SDK-owned SQLite database file in the **origin private file system**, via `WebSqliteSignalProtocolStore`. SQLite3 Multiple Ciphers encrypts the whole file in its worker. The 32-byte database key sits in the secret vault, which by default is IndexedDB in the same origin.

With the IndexedDB store, in **IndexedDB**, under your origin, via `IndexedDbSignalProtocolStore`. The adapter persists identity keys, contact trust decisions, prekeys, sessions, sender keys, device records, and retry metadata, with records encrypted using AES-256-GCM through Web Crypto. Its 32-byte database key sits in the same IndexedDB metadata store.

The browser has no equivalent of the iOS Keychain. No OS-level facility can hold either key outside page JavaScript because page JavaScript must use it.

This creates a narrow boundary. The key protects a copy of the stored data if the copy does not include the key. It does not protect against code on your origin.

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

The protocol lifetimes are identical to every other runtime: signed prekey rotation on `keyRefreshIntervalMs` (default `172800000`, two days), `maxPreKeyAgeMs` 14 days, `maxMessageKeysStored` 2000 for each receiver chain, `keyExpirationMs` 7 days, `MAX_UNACKNOWLEDGED_SESSION_AGE_MS` 30 days.

What differs is the *storage* lifetime, and the browser is the only runtime where it is out of your control:

- The user can clear site data at any time from browser UI, wiping everything instantly.
- Private and incognito windows discard the origin's storage when the session ends.
- Browsers apply **storage eviction** under disk pressure. They can evict origins without a persistence grant. Call `navigator.storage.persist()` and handle refusal. A granted persistence hint is not a durability guarantee.

Safari's Intelligent Tracking Prevention has historically capped script-writable storage lifetime for origins without user interaction. Assume browser storage is durable-ish, not durable.

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

Same protocol answer as everywhere: no code path in the SDK transmits a private key. `syncToServer()` uploads public material only.

The browser-specific leak paths are different and worth listing, because they are easy to create accidentally:

- **Session replay and analytics tools.** Products that record the DOM capture decrypted message text during rendering. This commonly defeats browser E2EE. A non-engineering team can install these tools without understanding the boundary.
- **Error reporting.** Serializing a caught error with attached context can ship envelope contents to a third party. Redact protocol objects.
- **Server-side rendering.** If plaintext is available in a server render path, it was on your server. Keep decryption strictly client-side.
- **Third-party scripts.** Every script on the origin has the same access your app does. A tag manager is a key-usage oracle.

If your backend is Supabase, Firebase, or similar: the relay only ever needs public keys and opaque envelopes. If you add a private-key column to a synced table, stop. The `SignalProtocolRelayServer` interface exposes no private fields.

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

Unchanged from other runtimes: batch of **100**, `preKeyLowThreshold` **50**, internal replenishment floor **10**, `preKeyCheckThrottleMs` 12 hours.

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

The browser wrinkle is *when* to run it. A closed tab is not a backgrounded app: there is no equivalent of a background fetch that quietly replenishes. Other people consume your users' prekeys while nobody has your site open. Check on load and on `visibilitychange`, and expect longer exhaustion windows than on mobile.

### 5. What happens when the user clears site data? [#5-what-happens-when-the-user-clears-site-data]

Clearing site data is the browser equivalent of a reinstall. A privacy sweep, closed incognito window, or storage eviction can cause it without user intent.

The consequences match a mobile reinstall. The identity key, sessions, and local history are gone. Each contact sees an identity change during the next contact. The SDK has no recovery path because no server holds a copy.

Do not treat a browser profile as a durable identity. Account survival across machines and browser resets requires a deliberate mechanism. See question 7. If the account does not survive, tell the user that clearing site data starts a new identity.

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

**Opacity ledger**

| Artifact | Stays on device | Sent to relay | In object store | Visible as metadata |
|---|---|---|---|---|
| `identityKeyPair` (private) | yes, in the store | never | never | no |
| Identity public key | yes | yes | no | yes — the pinned identity |
| Signed prekey + signature | private half local | public half | no | yes |
| Kyber prekeys | private half local | public half | no | yes |
| One-time prekeys | private half local | public half | no | count and consumption observable |
| Database key | yes, in IndexedDB: the web SQLite vault or the IndexedDB metadata store | never | never | no |
| Session / ratchet state | yes | never | never | no |
| Message plaintext | yes | never | never | no |
| Message ciphertext | yes | yes | no | size and timing |
| Sender / recipient IDs, 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 |

Worth doing once, in the console: log a `SendResult` next to the string you passed to `send()`. The gap between them is the product. Everything in the "sent to relay" column above is what a relay operator, or anyone who compels one, actually has.

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

The SDK ships no backup mechanism. Browsers provide no keychain, device transfer, or OS backup that your application can configure.

Realistic positions:

- **Ephemeral by design.** Treat the browser identity as scoped to that browser profile. Simplest and most honest. Users lose history on any reset. Good for demos, support chat, and anything where history is not the product.
- **User-held recovery secret.** Export an encrypted bundle the user stores themselves. Restores work. A lost secret is unrecoverable, and you cannot help. Signal Messenger's recovery key provides the reference example for this stance: deliberately something the operator "cannot recover, reset, or bypass."
- **Provider-assisted escrow.** Best experience, and you now hold something that can decrypt user data. Matthew Green's warning about how that capability spreads once it exists applies directly: "Once you have a hammer like SVR, you're going to want to use it to knock down other nails."

> **Tradeoff — The browser pushes you toward escrow, and that is the pressure to resist**
>
> Fragile browser storage creates pressure to hold recoverable key material on the server. Server-side recovery provides a user-experience benefit and changes the security property. If you select it, record the decision and update product claims. Do not add it incrementally.

See [recovery, backup, and migration](https://docs.open-e2ee.dev/build/recovery-backup-migration.md) for three named profiles with explicit tradeoffs.

---

## Web SQLite store options and gates [#web-sqlite-store-options-and-gates]

- `name`: the database name in the origin private file system. It also names the vault slot of the key. Default: `open-e2ee-signal-protocol.db`.
- `vault`: the `SignalProtocolLocalSecretVault` that holds the database key. Default: the SDK's IndexedDB vault in the same origin.
- `encryptionAtRest`: pass `false` to store the database without encryption. The store then does not use the vault, and it logs a warning at each open. Without `convertPlaintext: true`, a database created with one setting does not open with the other. Default: `true`. See [encryption at rest](https://docs.open-e2ee.dev/build/local-storage.md#encryption-at-rest).
- `convertPlaintext`: pass `true` to convert a database that `encryptionAtRest: false` created. The encrypted open converts the database when the vault holds no key for the store name. The conversion needs a `name` of at most 51 characters. With `encryptionAtRest: false`, an open or a reset with this option fails with `INVALID_STATE`. Default: `false`.

Each tab opens its own store, and the tabs of an origin share the database. One worker at a time holds the file, and each tab reads the writes of the other tabs. Close the store with `close()`: it closes the database and stops the worker.

The browser storage job runs the store contract in Chromium and Firefox on Linux. The WebKit store job runs it in WebKit on macOS, then in the Safari of the macOS runner through `safaridriver`. The browser storage job also runs a soak of the store in Chromium. The [web SQLite store guide](https://github.com/open-e2ee/signal-protocol-js/tree/v15.0.0/local/store/web-sqlite) gives the lost-key reset, the tab errors, full storage, and the Tauri setup.

---

## Other browser constraints worth knowing [#other-browser-constraints-worth-knowing]

- **No streaming API.** Issue w3c/webcrypto#73 opened in 2016 and still tracks the gap. Each `SubtleCrypto` call needs one complete payload buffer. Large attachments therefore need chunked framing, and browser memory limits apply. See [encrypted attachments](https://docs.open-e2ee.dev/guides/encrypted-attachments-r2-s3.md).
- **X25519 in Web Crypto has roughly 84% global support** (Chrome/Edge 133+, Firefox 130+, Safari 17.0+). This SDK does not depend on Web Crypto X25519. Every platform uses a pure-TypeScript key-agreement implementation. This browser gap explains the portable implementation.
- **Cross-tab coordination is your problem.** Two tabs on the same origin share one database, with either store, and can race on ratchet state. Coordinate with a lock or a single leader tab.

## Next [#next]

- [Build a browser E2EE demo with two local identities](https://docs.open-e2ee.dev/guides/browser-two-identities.md): the full build, with the ciphertext-inspection step.
- [Threat model](https://docs.open-e2ee.dev/learn/threat-model.md): what E2EE does and does not defend against.
- [Local encrypted storage](https://docs.open-e2ee.dev/build/local-storage.md): the storage boundary in full.
- [Runtime support matrix](https://docs.open-e2ee.dev/reference/runtime-support.md): per-runtime status.
