# Testing encrypted flows (https://docs.open-e2ee.dev/operate/testing.md)

- Status: stable
- Applies to: 15.0.0
- Platforms: Expo · Browser · Node
- Prereqs: A working client from Start → Quickstart
- Reading time: 11 min

Testing an encrypted application is unusual in one specific way: your test harness cannot inspect the thing under test from the outside. There is no assertion you can write against the relay's contents that proves correctness, because the relay never needs message plaintext or device private keys. Everything you verify, you verify by running both ends.

That constraint is what makes in-process adapters important rather than a shortcut.

## In-process adapters are development only, and they are the right substrate [#in-process-adapters-are-development-only-and-they-are-the-right-substrate]

The documentation limits `inMemoryStore()` from `/local/store/memory` to development. It holds state in memory and loses it on restart. The package contains no relay implementation, so a test relay is your code: an in-process object that implements `SignalProtocolRelayServer` from `/remote/signal-relay/types`. Do not include either one in a release bundle.

Neither adapter is a test double for the protocol. The protocol and the cryptography that the clients run are the ones you ship; only the infrastructure under them is simulated. An assertion that passes on these adapters is an assertion about real handshakes, real ratchets, and real ciphertext.

Most protocol tests belong on these adapters. A test with real clients and a real relay also tests the network and platform storage. A failure does not identify which of the four parts failed. The in-process pair removes transport and persistence so a failure identifies protocol or wiring behavior. Test persistence and transport separately with the adapters that you ship.

Use the in-process adapters for protocol behavior. Use `NodeSignalProtocolStore` (`/local/store/node`) in CI to test state across a process boundary. This includes device records, sender keys, and message records, so you can also test multi-device and group persistence. Use your production adapter on a real device for platform storage, background execution, and key material at rest.

## Two clients in one process [#two-clients-in-one-process]

This is the canonical test shape. `createSignalProtocolClient()` takes the test relay in `adapters.relay`.

```ts
import { createSignalProtocolClient } from "@open-e2ee/signal-protocol-sdk";
import { inMemoryStore } from "@open-e2ee/signal-protocol-sdk/local/store/memory";
import type { SignalProtocolRelayServer } from "@open-e2ee/signal-protocol-sdk/remote/signal-relay/types";

// testSignalProtocolRelay() is your test code. It returns an in-process object that
// implements SignalProtocolRelayServer. The SDK contains no relay.
const relay: SignalProtocolRelayServer = testSignalProtocolRelay();
await relay.registerDevice("alice", { encryptedDeviceName: new ArrayBuffer(0) });
await relay.registerDevice("bob", { encryptedDeviceName: new ArrayBuffer(0) });

const alice = await createSignalProtocolClient({
  identity: { userId: "alice" },
  adapters: { storage: inMemoryStore(), relay },
});
const bob = await createSignalProtocolClient({
  identity: { userId: "bob" },
  adapters: { storage: inMemoryStore(), relay },
});

await alice.syncToServer();
await bob.syncToServer();

// Decrypted content reaches your app here, and nowhere else.
bob.registerHook("onMessageDecrypted", async (message) => {
  console.log(`${message.senderId}: ${message.content}`); // alice: hello
});

await alice.send("bob", "hello");   // the relay now holds ciphertext and metadata
bob.startRelaySubscription();       // delivery and local decryption start here
```

Two properties of this shape matter. Each client gets its **own** `inMemoryStore()` instance: sharing one store between two identities produces a test that passes for the wrong reason. And the assertion lives inside `onMessageDecrypted`, because that hook is the only place decrypted content exists.

For advanced cases, `adapters.protocolManager` accepts an `SignalProtocolManager`. The documentation defines it as an advanced and test override, not an app-level extension point. Use it when you need to drive protocol internals deterministically. Do not build product features on it.

## The paths teams skip [#the-paths-teams-skip]

The order reflects how often teams omit each test.

**Out-of-order and skipped delivery.** The Double Ratchet tolerates a `maxSkip` of 25000 and stores up to `maxMessageKeysStored` 2000 skipped message keys in each receiver chain. The keys expire after `keyExpirationMs` of 604800000 (7 days). Test delivery of messages 1, 3, 2. Then test 1, 400, 2. Push past the bound and verify that you get `TOO_MANY_SKIPPED_MESSAGES`. Your app must surface the error instead of looping.

**Prekey exhaustion.** Drive one identity through more session establishments than it has one-time prekeys. The one-time batch is 100. Assert you see `PREKEY_NOT_FOUND` and that `checkPreKeyStatus()` reported `needsReplenishment` before you got there. This is not a hypothetical: a 2025 measurement study of WhatsApp found 13% of companion devices lacked a one-time prekey at scan time.

**Identity change mid-conversation.** Establish a session, exchange messages, then replace one side's identity. Assert `isUntrustedIdentityError()` fires with `.untrustedAddress` and `.identity`, that your UI blocks, and that nothing auto-accepts. Test the accept path separately through `acceptIdentityRotation(...)`.

**Session corruption and recovery.** Damage a persisted session record and verify that you get `SESSION_CORRUPTED`. Then verify that `deleteSession(remoteAddress)` and re-establishment recover. Bound the number of recovery attempts. `getSessionHealth(userId)` should report the problem before the user does.

**Offline queue and reconciliation.** Send while the relay is unreachable. Restore it, then verify ordering and idempotency. The `duplicate` receive outcome on redelivery is correct behavior, and your handler must accept it. See [offline and reconciliation](https://docs.open-e2ee.dev/build/offline-and-reconciliation.md).

**Multi-device fanout.** Two devices per user, minimum. The cost is multiplicative, `(nA−1)·nB` encryptions per message, so a fanout bug is a performance incident before it is a correctness one. Assert every device decrypts, and that a device added mid-conversation does **not** receive history: the managed device link moves no sessions or history.

**Group membership removal.** This is the security-critical one. Remove a member with `removeGroupMember(...)` and assert the sender key rotated and that the removed member's client can no longer decrypt subsequent messages. A test that only asserts the member disappeared from a list proves nothing. `getGroupSenderKeyStats(groupId, senderId, senderDeviceId)` returns `generation`, `chainIndex`, and `skippedKeysCount`: assert `generation` advanced.

**Attachment round trip.** `encryptFile(...)` / `uploadAttachment(...)` / `downloadAttachment(...)` / `decryptFile(...)` end to end, including an interrupted transfer. WebCrypto has no streaming API, an open bug since May 2016, so chunked framing is real code with real edge cases at chunk boundaries.

> **Failure mode — Controlled tests pass; real calls do not**
>
> Discord, describing its DAVE rollout: "The initial proof-of-concept worked well and DAVE's encryption functioned as expected in controlled tests. However, when we tried using DAVE in real Discord calls, it stopped working."
>
> Two in-process clients share a clock, scheduler, and reliable network. Real devices sleep, lose connectivity during handshakes, and stop between a decrypt and its state write. They also run different application versions. Plan a field-test phase with real hardware and networks. The in-process suite is necessary but does not cover these conditions.

> **Failure mode — You need logs from both ends, and you will not have them**
>
> Matrix's undecryptable-message meta-issue catalogs over 70 distinct causes, with this operational conclusion: "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."
>
> Make each test failure produce two correlated records. The sender records an outbound event, and the receiver records an inbound event. Join them with an identifier that does not contain message content. If tests cannot correlate both sides, production support cannot correlate them. See [observability](https://docs.open-e2ee.dev/operate/observability.md).

## The SDK's own posture, stated honestly [#the-sdks-own-posture-stated-honestly]

The public repository does not contain the automated checks. A reviewer can reasonably treat a cryptography package without visible checks as unchecked. The public repository is a mechanized export of a private engineering repository. An allowlist controls each published file. The checks use internal module paths and cross-implementation material that the allowlist does not publish.

Public CI provides clickable logs for each push and pull request. It runs `npm ci`, `npm run build`, and `npm run typecheck`. It also runs `npm audit --omit=dev` at moderate severity against production dependencies.

The engineering suite runs on each pull request that is ready for review and on each change to the main branch. The SDK's [assurance document](https://github.com/open-e2ee/signal-protocol-js/blob/main/docs/ASSURANCE.md) publishes the date and figures of the most recent full run. Release tooling writes those figures from a passing run, and a release cannot use figures older than three days. An export comes only from a revision where the checks pass.

Coverage includes conformance scenarios, published cryptographic vectors, protocol behavior, property checks, integrations, adapters, and the public API. Protocol checks include PQXDH establishment and skipped-key bounds. Public API checks run the documented calls against the packed package.

That is the honest shape: a genuine, independently reproducible public signal about compilation and dependency advisories, and a larger suite you cannot run yourself. Neither is an audit by a firm. The SDK is reviewed continuously by adversarial AI agents; it is not audited by any independent firm, and none is engaged.

**Opacity ledger**

| Artifact | Stays on device | Sent to relay | In object store | Visible as metadata |
|---|---|---|---|---|
| `inMemoryStore()` contents | in memory only | no | n/a | lost on process exit |
| Test relay envelopes | n/a | in memory only | n/a | test-visible by design |
| Test fixture plaintext | yes | no | n/a | no |
| `message.content` in `onMessageDecrypted` | yes | no | n/a | no |
| CI logs from a failing test | — | — | n/a | must not contain fixture keys |

> **Not covered — Load and soak testing**
>
> Throughput, memory behavior under sustained fanout, and relay capacity depend on your adapters and infrastructure. The published run figures exclude the SDK's longer performance and endurance checks. Separate commands run those checks.

## Next [#next]

- [Error handling and retries](https://docs.open-e2ee.dev/operate/error-handling.md)
- [Observability without plaintext](https://docs.open-e2ee.dev/operate/observability.md)
- [Production readiness checklist](https://docs.open-e2ee.dev/operate/production-checklist.md)
- [Offline and reconciliation](https://docs.open-e2ee.dev/build/offline-and-reconciliation.md)
