Skip to Content
OpenE2EEDocs

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.

Status
stable
Applies to
15.0.0
Platforms
Node 22.12+
Prereqs
Quickstart
Reading time
12 min

The SDK is easiest to run on Node, but you must carefully consider why you use it. Node is suitable for integration tests, CLIs, and disclosed bots or bridges. It is not suitable for the "decrypt on the server so we can do X" pattern. That design can work, but the result is not end-to-end encrypted.

It is also, in practice, the runtime you develop your relay on, which is a different job from running a client. That distinction runs through this page, and the last section is about it specifically.

What the Node store covers

NodeSignalProtocolStore implements the complete store contract. It covers identity keys, EC and Kyber prekeys, sessions, trust decisions, Sesame devices, sender keys, and message records. It declares implements SignalProtocolLocalStore, so the compiler checks that coverage on every SDK build.

Multi-device linking and both group APIs are therefore available on this adapter. Use inMemoryStore() for tests where data must not survive a restart.

The same store serves the Electron main process. See Electron.

Install

npm install @open-e2ee/signal-protocol-sdk@latest better-sqlite3-multiple-ciphers

The store needs the peer better-sqlite3-multiple-ciphers 13.0.3 or later and uses its SQLCipher cipher. Other entries do not load it. The package is ESM-only and requires Node 22.12 or later.

Setup

import { createHostedSignalProtocolClient } from '@open-e2ee/signal-protocol-sdk';
import { nodeStore } from '@open-e2ee/signal-protocol-sdk/local/store/node';

// Async. The directory and the vault are required.
const storage = await nodeStore({
  directory: '/var/lib/my-app/signal-protocol',
  vault,
});

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

nodeStore(options) returns a promise. It opens an SDK-owned SQLCipher database in directory. On first use, it creates the directory, readable only by the owner. Then it creates a 32-byte database key, writes it to the vault, and creates the database file. Each open applies the SDK migrations before it returns the store. The SDK owns the database: its file, its key, and its migrations. Keep application tables in a separate database file.

  • directory: the directory of the database file. Use a private directory on a local file system. Do not use a network file system.
  • vault: the SignalProtocolLocalSecretVault that holds the database key. Required. The SDK ships no vault for a plain Node process, so implement getSecret, setSecret, and deleteSecret over the secret store of your deployment. In Electron, use the safeStorage vault.
  • name: the database file name in directory. Default: open-e2ee-signal-protocol.db.
  • 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.
  • convertPlaintext: pass true to convert a database file that encryptionAtRest: false created. The encrypted open converts the file when the vault holds no key for the store name. With encryptionAtRest: false, an open or a reset with this option fails with INVALID_STATE. Default: false.

Choose the directory deliberately. A service that opens a different directory, or reads a different vault, starts a second identity and causes identity-change warnings for every contact.

Two more calls you will want in a long-lived process:

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

signal.startRelaySubscription();

// On shutdown.
await signal.stop();

startRelaySubscription() logs a warning and returns without doing anything if no relay adapter or onMessageDecrypted hook exists. It does not throw. Register the hook first. If messages silently fail to arrive, check that order first.

Electron

Open the store in the main process, with the vault over Electron's safeStorage:

import { join } from 'node:path';
import { app, safeStorage } from 'electron';
import { nodeStore } from '@open-e2ee/signal-protocol-sdk/local/store/node';
import { ElectronSafeStorageSignalProtocolSecretVault } from '@open-e2ee/signal-protocol-sdk/local/vault/electron-safe-storage';

await app.whenReady();
const directory = join(app.getPath('userData'), 'signal-protocol');
const vault = new ElectronSafeStorageSignalProtocolSecretVault({
  safeStorage,
  file: join(app.getPath('userData'), 'signal-protocol-secrets.json'),
});
const storage = await nodeStore({ directory, vault });

Use an Electron major that the Electron team still supports. CI tests the latest major, Electron 44, on Linux, macOS, and Windows, and the oldest supported major, Electron 42, on Linux. The binding uses Node-API, so its prebuild loads in each supported major without a rebuild.

On Linux, the vault needs a secret service. CI passes the store contract with GNOME Keyring through libsecret, with KWallet 5 on kwallet5, and with KWallet 6 on kwallet6. The vault fails with KEY_STORAGE_ERROR, and the store does not open, in these cases:

  • The backend is basic_text.
  • No secret service answers, and safeStorage uses its fixed fallback key.
  • safeStorage uses the key of the Secret portal, with the Chromium feature SecretPortalKeyProviderUseForEncryption. That feature is off by default.

No check ran the kwallet backend (KWallet 4) or Electron in a Flatpak or Snap sandbox. No check opened a KWallet wallet at a password prompt.

  • Renderer. Do not open the store or the vault in a renderer or a preload script. Keep contextIsolation: true, sandbox: true, and nodeIntegration: false. In the preload script, expose one function for each operation with contextBridge, and do not expose ipcRenderer. In the main process, check the senderFrame of each IPC message before it reaches the client.
  • Utility process. The store can run in a utilityProcess child. safeStorage is a main-process API, so the vault stays in the main process and answers the child over a MessageChannelMain port. Only one process opens a database file.
  • Unpack the binding. Unpack the .node binding from the ASAR archive, with @electron-forge/plugin-auto-unpack-natives or asar pack app app.asar --unpack *.node.
  • Fuses. Turn off the RunAsNode, EnableNodeOptionsEnvironmentVariable, and EnableNodeCliInspectArguments fuses. When they are on, a process of the same user can run code as the app and decrypt the vault with safeStorage.
  • macOS signature. Sign the app after the fuses are flipped and the package is complete. In an app whose signature is not valid, safeStorage fails, and the store fails with KEY_STORAGE_ERROR. Check the app with codesign --verify --deep --strict.
  • Updates on macOS. Sign every build with the same Developer ID identity, and notarize it. A build with a different signature can make the Keychain ask the user again. An ad-hoc signature changes with each build.

CI packages an app with Electron Forge on Linux x64, macOS arm64, and Windows x64. The app uses ASAR, the auto-unpack-natives plugin, and these fuses. The store opens in the main process and in a utility process, and a value reads back after a relaunch. On macOS, the job signs the app ad hoc and requires codesign --verify --deep --strict to pass. The job uses Electron Forge 7.11.2.

A manual check on macOS 15.7 arm64 notarized version 1.0.0 and version 1.0.1 of that app. After the check copied version 1.0.1 over version 1.0.0, each process read its value back with no Keychain prompt. An ad-hoc signed copy of version 1.0.1 made the Keychain prompt at each read. No check installed an update through Squirrel.Mac or another updater, or ran a notarized build on an Intel Mac.

The Node store guide and the vault guide give the details.

Before the seven questions: what a server-side identity means

A Node client is a full participant with a real identity key. If it can read a conversation, its machine is inside the encryption boundary. The boundary also includes anyone who can access the machine, disk, snapshots, process memory, or logs.

This design is suitable for a user-run CLI, test harness, or disclosed bot. Do not use it to bypass end-to-end encryption while you continue to describe the product as end-to-end encrypted. If your server can decrypt conversations, users receive a different guarantee. Your documentation must state the actual guarantee.


The seven questions

1. Where are the keys stored?

In an SDK-owned SQLCipher database in directory. Identity keys, prekeys, sessions, trust decisions, and group sender keys all live there. SQLCipher encrypts the database file itself, so the rows are not encrypted one by one. The database key is therefore the only thing that protects them. That includes the sender-key tables, whose rows are enough to read and to forge a sender's group messages.

The database key is 32 bytes, held in the vault that you pass, not in the directory. Its vault slot is sqliteDatabaseKeySlot(path), where path is the real path of the database file. The boundary is therefore as strong as the vault. A copy of the directory without the vault secret cannot be read. Anyone who can read both the file and the vault secret can read all stored data.

The rest of the boundary is yours

The application still owns OS account isolation, backups, volume security, and process access. Use a dedicated service account, and choose a vault whose secret store your backups and your log agents do not reach.

2. How long are they retained?

Protocol lifetimes are identical on every runtime. Signed prekeys rotate after keyRefreshIntervalMs, which defaults to two days. maxPreKeyAgeMs is 14 days, maxMessageKeysStored is 2000 for each receiver chain, and keyExpirationMs is 7 days. Unacknowledged sessions expire after 30 days.

Storage lifetime differs from the browser runtime. Nothing evicts a Node store directory. It persists until you delete it. The primary failure mode is accumulation in unintended locations. Examples include container build contexts, machine snapshots, incorrect log-agent globs, and paths that a deployment tool synchronizes.

Decide where the directory lives before you deploy, not after.

3. How do I keep keys away from my own backend?

The protocol answer is the same everywhere: no code path in the SDK transmits a private key, and syncToServer() uploads public material only.

The Node-specific leak paths are the ones worth listing, because on a server they are all defaults somewhere:

  • Structured logging. Logging error context, or an envelope "for debugging," sends protocol material to the log aggregator. Configure logger redaction.
  • APM and error-reporting agents. They capture local variables in stack frames. Decrypted content in a frame becomes a payload to a third party.
  • Core dumps and heap snapshots. On by default in some container runtimes. Both contain key material.
  • Snapshots and backups of the volume that holds the directory, together with the vault secret. See question 1: the two together are the full identity.

If your backend is the relay, note that the relay never needs anything private. The SignalProtocolRelayServer interface contains no private fields. If you add a private-key column, stop.

4. How many prekeys, and when do they refill?

Unchanged from other runtimes: batch of 100 one-time prekeys, preKeyLowThreshold 50, internal replenishment floor 10, preKeyCheckThrottleMs 12 hours.

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

oneTimePreKeysRemaining is -1 when the relay cannot determine the count. It is not 0, so do not treat it as exhaustion.

A long-lived Node process can schedule this check, but nobody will notice if you omit it. Node has no app foreground event. Run the check on a timer and alert on needsReplenishment. Other people consume your prekeys at a rate that you do not control.

For rotation without a full client, the usual shape for a scheduled job, the SDK exports a headless path:

import { rotateKeysHeadless } from '@open-e2ee/signal-protocol-sdk/client/headless';

await rotateKeysHeadless(relay, userId, deviceId, { storage });

It requires a local store, and it throws if you do not pass one. signal.rotatePreKeys() is the equivalent on a live client, and both return the same PreKeyRotationResult.

5. What happens when the directory or its key is lost?

Losing the directory is equivalent to reinstalling an app. Common causes include an ephemeral container, a deployment that replaces the volume, or a cleanup job.

Losing the key is the other half. When the database file exists and the vault holds no key for it, nodeStore fails with LOCAL_STORE_KEY_LOST and changes nothing. A new key cannot read the old file. Restore the vault entry, or call resetNodeStore(), which deletes the file, writes a new key, and returns the open, empty store. A move or a rename of the directory changes the vault slot, so the next open also fails with LOCAL_STORE_KEY_LOST. Move the secret to the slot of the new path before that open.

The consequences are the same as everywhere: identity key gone, sessions gone, and every contact sees an identity change on next contact. There is no recovery path in the SDK, because no server holds a copy.

This loss can be difficult to notice on Node. A phone reinstall is a user action, but a container restart can be routine. A bot or verified bridge usually needs a durable identity. Mount its directory on persistent storage, keep its vault secret with it, and manage both as stateful infrastructure.

6. What does the relay store?

Opacity ledger

ArtifactStays on deviceSent to relayIn object storeVisible as metadata
identityKeyPair (private)yes, in the SQLCipher databaseneverneverno
Identity public keyyesyesnoyes — the pinned identity
Signed prekey + signatureprivate half localpublic halfnoyes
Kyber prekeysprivate half localpublic halfnoyes
One-time prekeysprivate half localpublic halfnocount and consumption observable
Database keyyes, in the vaultneverneverno
Session / ratchet stateyesneverneverno
Message plaintextyesneverneverno
Message ciphertextyesyesnosize and timing
Sender / recipient IDs, device IDsyesyesnoyes — the social graph
timestamp, messageType, clientMessageIdyesyesnoyes
Attachment bytesencrypted firstnoyes, opaquesize, count, timing

If you write both the relay and client, use this table for schema review. You choose to retain everything in the "sent to relay" column. You also choose not to retain the other data, so you cannot produce it under subpoena.

7. What should I do about backups?

The SDK does not include a backup mechanism. Do not back up the database file to a server or sync it between devices.

A copy of the database file together with its vault secret is a full, usable identity. A copy without the secret cannot be read, and a restore without the secret fails with LOCAL_STORE_KEY_LOST.

Realistic positions:

  • Ephemeral by design. The service has no durable identity. It re-registers on deploy. Simplest, and correct for short-lived workers and test harnesses. Contacts see identity changes, so it is wrong for anything a human verifies.
  • Durable volume, no backups. The directory on a persistent volume, explicitly excluded from snapshotting. The identity survives restarts. Losing the volume means starting over. A defensible default for most bots.
  • Secret backup. A backup of the file and its vault secret is a conversation decryption key. Encrypt it with a separately stored key, log access, and include it in security reviews. Do not store it with application-log backups.

See recovery, backup, and migration for three named threat-model profiles with explicit tradeoffs.


The other Node job: building the relay

Most Node code in an end-to-end encrypted system is not a client at all. It is the relay: the service that stores prekey bundles, hands them out, accepts opaque envelopes, and delivers them. That service holds no keys and decrypts nothing, which is why it is the part you can operate normally.

The published SDK contains no relay server implementation. It has one hosted path, the OpenE2EE Signal Protocol Relay. If you do not use it, implement SignalProtocolRelayServer yourself:

import type { SignalProtocolRelayServer } from '@open-e2ee/signal-protocol-sdk/remote/signal-relay/types';

The type signature does not express all correctness requirements. In particular, the relay must consume one-time prekeys atomically under concurrent requests. Incorrect consumption causes intermittent session failures under load, not an immediate error. Read relay and prekey infrastructure before you start.

You can also test this behavior by running a Node client against your relay. Two clients and an application-owned SignalProtocolRelayServer provide an end-to-end assertion in CI without infrastructure. See testing encrypted flows.

Operational notes

  • Do not assume that you can scrub process memory. JavaScript engines copy and move buffers, so zeroing is best-effort. Heap dumps, core dumps, and swap can expose server data.
  • Test the published artifact on every Node line you support. Do not infer from one version.
  • Secure pre-created directories. The store creates its directory readable only by the owner. You must secure a directory or volume that already exists with permissive modes.

Good uses

  • Integration tests. Two Node clients and an application-owned SignalProtocolRelayServer in CI, with no infrastructure.
  • CLIs the user runs themselves. The user's machine is already inside their trust boundary.
  • Disclosed bots and bridges. A bot can read its conversations. This design is honest when all participants know about the bot.
  • Relay development. Exercising an SignalProtocolRelayServer implementation against a real client.

Next

On this page