Browser
Set up the web SQLite store, and the IndexedDB store where the origin private file system is not available, with direct answers on key storage, retention, prekeys, clearing site data, and backups — and an honest account of the browser threat model.
- 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. 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
npm install @open-e2ee/signal-protocol-sdk@latest idbBoth 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
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.
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
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.
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-srcmust allow the worker script, andconnect-srcmust allow the Wasm file.- Serve
sqlite3.wasmasapplication/wasm. - Emit the worker and
sqlite3mc/sqlite3.wasmnext to the module that creates the driver, as the package lays them out. Most bundlers resolve the default URLs. Otherwise passworkerUrlandwasmUrl.
Without 'wasm-unsafe-eval', the open fails with SQLITE_ENGINE_UNAVAILABLE.
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:
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
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."
The seven questions
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?
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?
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?
Unchanged from other runtimes: batch of 100, preKeyLowThreshold 50, internal replenishment floor 10, preKeyCheckThrottleMs 12 hours.
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?
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?
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?
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."
See recovery, backup, and migration for three named profiles with explicit tradeoffs.
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: theSignalProtocolLocalSecretVaultthat holds the database key. Default: the SDK's IndexedDB vault in the same origin.encryptionAtRest: passfalseto store the database without encryption. The store then does not use the vault, and it logs a warning at each open. WithoutconvertPlaintext: true, a database created with one setting does not open with the other. Default:true. See encryption at rest.convertPlaintext: passtrueto convert a database thatencryptionAtRest: falsecreated. The encrypted open converts the database when the vault holds no key for the store name. The conversion needs anameof at most 51 characters. WithencryptionAtRest: false, an open or a reset with this option fails withINVALID_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 gives the lost-key reset, the tab errors, full storage, and the Tauri setup.
Other browser constraints worth knowing
- No streaming API. Issue w3c/webcrypto#73 opened in 2016 and still tracks the gap. Each
SubtleCryptocall needs one complete payload buffer. Large attachments therefore need chunked framing, and browser memory limits apply. See encrypted attachments. - 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
- Build a browser E2EE demo with two local identities: the full build, with the ciphertext-inspection step.
- Threat model: what E2EE does and does not defend against.
- Local encrypted storage: the storage boundary in full.
- Runtime support matrix: per-runtime status.
React Native
Set up the bare React Native store on op-sqlite and the keychain vault, and get direct answers on key storage, retention, prekeys, reinstall, and backups.
Node
Set up the Node SQLCipher store for services, integration tests, CLIs, Electron apps, and relay development — with direct answers on key storage, retention, prekeys, recovery, and what a server-side identity does to your threat model.