# Design offline, device recovery, and identity-change behavior safely (https://docs.open-e2ee.dev/guides/offline-recovery-identity-change.md)

- Status: stable
- Applies to: 15.0.0
- Platforms: Expo · Browser · Node
- Prereqs: A working client that already sends and receives messages
- Reading time: 18 min

**This is a design guide, not a copy-paste build.** The code here is real and verified,
but you cannot finish this page by pasting it. Every section ends in a decision that
belongs to your product, and the SDK deliberately does not make it for you.

Three questions meet here:

1. What happens to a message composed on a train?
2. What happens when the phone holding the keys goes into a canal?
3. What happens when a contact's identity key changes, which it will, routinely?

Teams often accept defaults instead of making decisions. Examples include an infinite
outbox, no recovery path, and a banner for every key change. Each default has costs.

## Intended audience [#intended-audience]

This guide is for engineers and product owners who make architecture decisions before
launch. Their product has working messages but has not yet faced device loss.

## Prerequisites [#prerequisites]

- A working client from [Quickstart](https://docs.open-e2ee.dev/start/quickstart.md) with a `storage` adapter and a
  relay configured.
- [Keys, identity, and sessions](https://docs.open-e2ee.dev/learn/keys-identity-sessions.md), read first: part three
  assumes you know what a session and a composite identity are.
- A threat model you can state in a sentence. See [Threat model](https://docs.open-e2ee.dev/learn/threat-model.md).
  Every decision below is undecidable without one.

**Figure:** A device with an attached local store holding its identity key, a seal gutter, a relay bracket holding three sheared envelopes as backlog, an open gutter, and an empty replacement device outline holding no keys. The original device holds the identity key and local store. The relay holds opaque backlog envelopes and exposes their metadata. The replacement device has no keys and cannot open those envelopes.

## Install [#install]

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

On Expo, the storage adapter and the bootstrap vault need peer packages:

```bash
npm install @open-e2ee/signal-protocol-sdk@latest expo-secure-store expo-sqlite
```

On Expo and React Native, the SDK reads random bytes only from the global `crypto.getRandomValues`. Install `react-native-get-random-values` and load it before the first SDK call.

The Expo store requires a development build and is not available in Expo Go.

## Part one: offline [#part-one-offline]

### What the SDK bounds, exactly [#what-the-sdk-bounds-exactly]

The Double Ratchet handles gaps by deriving and storing the message keys it skipped,
so a late message still decrypts. The bounds are not infinite:

| Bound | Value | What it means when you hit it |
|---|---|---|
| `maxSkip` | `25000` | A message more than 25000 ahead of the last received counter is refused |
| `maxMessageKeysStored` | `2000` | Each receiver chain keeps at most 2000 skipped keys. At the cap, the key with the lowest index leaves |
| `keyExpirationMs` | `604800000` (7 days) | A skipped key older than a week is dropped |
| `MAX_UNACKNOWLEDGED_SESSION_AGE_MS` | 30 days | A prekey session that never got a reply is stale past this |

These four numbers are your offline window. A device back after eight days finds its
skipped keys already deleted. The late counter is below the current receive counter, so
the SDK reports `MESSAGE_DUPLICATE` through `DuplicatedMessageError`. It cannot distinguish
an expired skipped key from one that it consumed before. A device that misses more than
25000 messages in a chain gets `TOO_MANY_SKIPPED_MESSAGES`. Retrying the same ciphertext
cannot recover either case.

Redelivery and post-crash replay are expected. `processIncomingEnvelope()` returns the
`duplicate` outcome for them.

### The outbox is your job [#the-outbox-is-your-job]

There is no send queue in the SDK. `send(recipientUserId, content)` attempts the operation
now and throws if it cannot complete. What you get instead is a bounded retry primitive:

```ts
import { withRetry } from '@open-e2ee/signal-protocol-sdk/utils/retry';

await withRetry(() => client.send(recipientUserId, body), {
  operationName: 'send',
  maxRetries: 2,
  baseDelay: 1000,
  maxDelay: 10000,
});
```

Those are the defaults: `maxRetries` 2 (three attempts total), `baseDelay` 1000 ms,
`maxDelay` 10000 ms, jitter on. `withRetry` consults `isRetryableError()`, which refuses a
fixed non-retryable set of nine codes: `INVALID_PREKEY_BUNDLE`, `ENCRYPTION_FAILED`,
`TOO_MANY_SKIPPED_MESSAGES`, `KEY_STORAGE_ERROR`, `UNTRUSTED_IDENTITY`,
`SIGNATURE_VERIFICATION_FAILED`, `RECIPIENT_NOT_REGISTERED`,
`PREKEY_FETCH_RATE_LIMITED`, and the OpenE2EE Signal Protocol Relay code `UPGRADE_REQUIRED`. Retrying an untrusted identity three times produces three
identical failures and a slower error.

`withRetry` covers one operation crossing a flaky network. It is not durable and does not
survive a process restart. Your outbox rows live in your database.

### Catching up [#catching-up]

```ts
client.startRelaySubscription();

// pullMailbox() and acknowledge() are your transport code.
const pendingEnvelopes = await pullMailbox();
const { processedMessageIds } = await client.receiveIncomingEnvelopes(pendingEnvelopes);
for (const id of processedMessageIds) await acknowledge(id);
```

`receiveIncomingEnvelopes()` gives each decrypted message to the `onMessageDecrypted`
hook. It throws an error if you did not register that hook. See
[catching up after reconnect](https://docs.open-e2ee.dev/build/offline-and-reconciliation.md#catching-up-after-reconnect).

`receiveIncomingEnvelopes()` processes each envelope instead of stopping at the first
failure. It returns the IDs that are ready for acknowledgment as `processedMessageIds`.
Do not acknowledge its `failedMessageIds`. A later pull gives them again.

It processes prekey messages before ordinary ciphertexts. A session
can therefore exist before the messages that depend on it arrive.

The relay subscription and `receiveIncomingEnvelopes()` also handle the retry path. A
peer that cannot decrypt something you sent puts a `retry_request` envelope in your
mailbox. The client resends the message only to the device that asked. Do not give a
pulled batch to `processIncomingEnvelopes()`. It returns an `INVALID_CIPHERTEXT` error
for a `retry_request` envelope and does not resend.

> **Tradeoff — How long your outbox keeps trying**
>
> A queue that retries indefinitely eventually delivers a message the user wrote three days
> ago after the conversation changed. Users experience that as the app speaking on
> their behalf. A queue that gives up after a bounded window produces an honest, visible
> failure, which arrives long after the moment mattered.
>
> The four bounds above set an upper limit worth respecting: retrying past
> `keyExpirationMs` cannot succeed on the receiving side anyway. Below that, the number is a
> decision about whether late delivery or visible failure is worse in your product.

> **Tradeoff — Gap markers in the thread, or silence**
>
> When an envelope fails permanently, you can render a placeholder or drop it. The
> placeholder is truthful and lets support ask useful questions. It is also unactionable,
> and a thread with six of them reads as a broken product. Dropping it keeps the thread
> clean and destroys your only evidence.
>
> Matrix's undecryptable-message meta-issue lists more than 70 causes. Its conclusion is:
>
> > "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."
>
> Always write a structured log entry. Show a marker only when the gap could make the user misread the conversation.

> **Failure mode — Session state must persist atomically**
>
> A decrypt changes ratchet state. A crash between decryption and persistence can corrupt
> that state. Two concurrent decrypts on one session can do the same. The corruption might
> remain hidden until the next message fails.
>
> One incident produced 479 Bad MAC exceptions and stopped WhatsApp inbound delivery. The
> report states:
>
> > "WhatsApp inbound message delivery silently stops. The gateway believes it is connected and listening, making this a silent failure."
>
> A related project logged more than 168,000 errors across over 400 sessions in two hours.
> The errors exhausted the Node heap.
>
> There is no class named `BadMacError` here. That failure surfaces as
> `DECRYPTION_FAILED`. Do not process the same session
> concurrently, and make your store's write path atomic. The SDK versions session records
> (`version: 4`). It rejects and resets older formats rather than migrating them.

## Part two: recovery [#part-two-recovery]

Device loss is certain over a long product lifetime. It might first appear as a support
ticket months after you set the architecture. Decide the recovery policy before launch.
[Recovery, backup, and migration](https://docs.open-e2ee.dev/build/recovery-backup-migration.md) defines three named
profiles. Pick one explicitly and write the name down.

- **`business-archive`**: history survives device loss, staff turnover, and hardware
  refresh. This profile gives up coercion resistance. An authority can compel a durable
  recovery path. A social engineer can exploit it, or an insider can misuse it. Suits regulated professional services.
- **`high-risk-messaging`**: a lost device means lost history, and that is the feature.
  Gives up continuity, and becomes your most common support category. Suits journalism
  and source protection.
- **`collaboration-default`**: an explicit compromise. Recovers recent working context
  within a stated retention horizon. Gives up being a system of record, and coercion
  resistance. Suits team tools where another system holds the durable record.

None is the correct default. If a product omits the choice, a backup selects `business-archive`
by accident. Without a backup, the product selects `high-risk-messaging` by accident.

### Why this is structurally hard [#why-this-is-structurally-hard]

1Password states the structural problem directly:

> "Recovery mechanisms are inherently weak points in maintaining the secrecy of data."

A recovery path for a user who lost everything can also become a path for another person.

Signal Messenger uses a 64-character recovery key that "Signal cannot recover, reset, or bypass".
If the user loses that key, Signal cannot restore it. Matthew Green describes the risk of the alternative:

> "Nobody is going to engineer something as complex as Signal's SVR just to store contact lists. Once you have a hammer like SVR, you're going to want to use it to knock down other nails."

### What the SDK actually moves [#what-the-sdk-actually-moves]

```ts
import {
  prepareNewDeviceTransfer,
  prepareOldDeviceTransferWithBackup,
} from '@open-e2ee/signal-protocol-sdk/device';

// New device: show the QR code that the old device scans.
const receiving = await prepareNewDeviceTransfer({ platform: 'android' });
await appQr.show(receiving.qrCode);

// Old device: read the account identity from its backup storage.
const sending = await prepareOldDeviceTransferWithBackup(backupStorage, { platform: 'ios' });
const backup = await sending.getBackup();
```

Transfer moves the long-lived account identity and the device metadata in an encrypted
backup, and requires **the old device**. The new device creates fresh prekeys and
sessions after the restore. It is an upgrade story. The managed device link needs device 1 to approve the two-device link or
run the one-process link, and it moves **no sessions or history**. The
phone in the canal participates in neither. Recovery: restoring to a device that never
held the state: is a system your application builds.

`clearAllData()` handles only the local half of an account reset. A complete reset must
clear the device-ID cache, platform secret storage, and protocol store in one lifecycle.

The SDK source limits `forceCompleteKeyReset()` to development and debugging.

> **Tradeoff — Deciding the profile now, or deferring it**
>
> Deferring feels responsible: you will know more later, and the decision is reversible in
> principle. In practice each profile implies different storage, onboarding copy, support
> scripts, and a promise already made to users. Moving `high-risk-messaging` users to
> `business-archive` means telling people that material they were told was unrecoverable is
> now recoverable: a security regression from their point of view.
>
> Deciding now costs a decision made with less information. It buys a written answer for the
> first person who proposes a feature that quietly moves you between profiles.

> **Tradeoff — Choose whether recovery is possible**
>
> Any mechanism that helps a legitimate user after total device loss can help an attacker.
> An attacker can also use it against a user under pressure. A design that prevents those
> uses also prevents legitimate recovery. There is no third option.
>
> Choose where the mechanism exists and which authentication protects it. Decide whether
> attempts are auditable and whether administrators can trigger recovery without a record.

## Part three: identity change [#part-three-identity-change]

### The one error [#the-one-error]

```ts
import { isUntrustedIdentityError } from '@open-e2ee/signal-protocol-sdk';

try {
  await client.send(remoteUserId, body);
} catch (error) {
  if (isUntrustedIdentityError(error)) {
    // error.untrustedAddress, error.identity
    await auditLog.recordIdentityChange(error);
    return; // fails closed until the identity is accepted
  }
  throw error;
}
```

`UntrustedIdentityError` (`UNTRUSTED_IDENTITY`) is the classic "safety number changed"
event and carries `.untrustedAddress` and `.identity`. It reports a candidate that differs
from the identity tuple already pinned for that contact. The SDK throws it from five sites
on the session and sending paths, and the operation fails closed.

Accepting a change is explicit, and is not the same as verifying it:

```ts
await client.acceptIdentityRotation(remoteUserId, newCompositeIdentity);
```

`trustIdentity()` does not exist, despite appearing in a stale SDK document.
Use `acceptIdentityRotation(userId, identity, identityType?)`. It resets sessions bound to
the old tuple and returns the contact's identity record. It does not mark the contact
`VERIFIED`.

### Two different safety-number shapes [#two-different-safety-number-shapes]

These are separate objects. Do not merge them.

```ts
const safetyNumber = await client.verify(remoteUserId);
// { numeric, fingerprint, userId, identityType, trustState, confirmation }

showVerificationDialog(safetyNumber);
await client.confirmSafetyNumber(safetyNumber.confirmation);
```

`client.verify()` returns comparison data and an immutable `confirmation` token for the
displayed tuple. A key that changes between rendering and confirmation cannot pass by
accident. It does **not** return `emojis` or `scannable`. Use the standalone module for
all representations:

```ts
import { generateCompositeSafetyNumber } from '@open-e2ee/signal-protocol-sdk/safety';

const composite = generateCompositeSafetyNumber(
  localCompositeIdentity,
  remoteCompositeIdentity,
  localUserId,
  remoteUserId,
);
// { numeric, emojis, hex, qrData, scannable }

if (composite.scannable.compare(scannedQrBytes) === 'match') {
  await recordUserDecision(remoteUserId);
}
```

`IdentityTrustState` is `'UNVERIFIED_TOFU' | 'VERIFIED'`. There is no third state, and
verification is a statement about one tuple at one moment, not a permanent property of a
contact.

### The part the research settles [#the-part-the-research-settles]

Users cannot do this. In one study, 21 of 28 computer science students could not verify a
public key. In another, which explained the risks first, only 13% completed the ceremony.
People primed to care, and most did not finish.

Keybase described the burden directly:

> "Checking is infeasible, since it happens way too often. Checking sucks."

It proposed **TADA, Trust After Device Additions**, instead of trust on first use. Users
must repeat the decision after a phone upgrade, reinstall, or tablet link.

Warning fatigue is therefore the *default* outcome of bannering every change, not a possible risk.
`UntrustedIdentityError` tells the truth. A high-base-rate interrupt creates the failure.

The industry increasingly makes key changes **auditable** instead of asking users to judge
each one. Apple's Contact Key Verification and WhatsApp's Automatic Device Verification
check continuity in the background. This SDK provides comparison data, but no transparency
log or automated continuity check.

> **Tradeoff — Banner every identity change, or reserve the interrupt**
>
> Bannering everything is defensible on paper: nobody can say you hid a change. It also
> produces, in a 500-person deployment, a continual stream of warnings about colleagues' new
> phones. Within a month, the interaction becomes muscle memory. This repetition trains
> users to dismiss the genuine event.
>
> Reserve interrupts for cases that your product can justify. Examples include first contact,
> a high-value action, or an account that your signals flagged. This choice keeps warnings
> meaningful but lets some changes pass unseen. Choose based on whether users face key
> substitution attacks or mostly routine device changes.

> **Tradeoff — Block sends on identity change, or record and continue**
>
> Blocking is the strict reading: no message leaves for a key the user has not accepted. It
> is also a hard stop mid-task, triggered most often by something benign. It converts a
> security decision into an obstacle that users clear quickly.
>
> Recording and continuing keeps the product usable and preserves evidence for the security
> team. A user who never opens that log has effectively accepted an unverified key. The SDK
> raises the error and fails closed. Your product layer must choose the response based on the
> message's value.

> **Tradeoff — Sync verification?**
>
> Trust state stays on one device. A contact verified on a phone remains unverified on a tablet.
> `syncVerificationStateToLinkedDevices(...)` is a call you make, not a background
> behavior.
>
> Syncing lets one ceremony cover all user devices. It also copies a decision from a
> possibly compromised device to devices that did not show the ceremony. Without sync, each
> device trusts only what it observed. Users must then verify each new device, which creates
> another source of warning fatigue.

## Trust boundaries: what crosses which line [#trust-boundaries-what-crosses-which-line]

**Device to relay.** Sealed envelopes cross this boundary. Public identity keys and prekeys
also cross because peers must fetch them. The relay does not receive plaintext or private
keys. Therefore, it cannot resolve offline conflicts, restore a lost device, or classify an
identity change.

**Device to device.** Transfer moves cryptographic state directly. Ephemeral ECDH keys
derive the encryption keys. The device encrypts identity and backup material before it
reaches a transport. The managed device link sends no private key to the relay.

**Device to your application's storage.** Your app owns decrypted message rows, local
files, outbox rows, audit records, and trust decisions. Nothing in the SDK reaches in.

**The line that does not exist.** No boundary here lets a server resolve any of the three
problems on this page. That absence is the design, and every decision above is downstream
of it.

## 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 |
|---|---|---|---|---|
| Application outbox rows | yes | no | n/a | no |
| Envelope ciphertext | yes | yes | n/a | size, routing, arrival time |
| Skipped message keys (`maxMessageKeysStored`) | yes | no | n/a | no |
| Session record (`version: 4`) | yes | no | n/a | no |
| `client.syncStatus` | yes | no | n/a | no |
| `identityKeyPair` private half | yes | no | n/a | no |
| `identityKeyPair` public half | yes | yes | n/a | yes |
| Prekeys (private halves) | yes | no | n/a | no |
| Prekeys (public halves) | yes | yes | n/a | count and consumption rate |
| Backup from `sending.getBackup()` | yes | encrypted, if routed that way | optional, encrypted | size and write time |
| Backup encryption key | yes, or user-held | no | n/a | no |
| `safetyNumber.numeric` | yes | no | n/a | no |
| `safetyNumber.confirmation` | yes | no | n/a | no |
| Trust state (`UNVERIFIED_TOFU` / `VERIFIED`) | yes | no | n/a | no |
| `UntrustedIdentityError.identity` | yes | already public | n/a | yes |
| Your audit record of identity changes | yes | no | n/a | no |
| Encrypted device name | yes | yes, encrypted | n/a | that a device exists |

Teams often miss the public prekey row. The relay observes consumption rate. A 2025
WhatsApp study found that 13% of companion devices lacked a one-time prekey during the
scan. Exhaustion weakens forward secrecy without an error.
`checkPreKeyStatus()` returns `{ oneTimePreKeysRemaining, needsReplenishment }`, and the
`onPreKeyLow` callback fires against the `preKeyLowThreshold` default of 50.

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

> **Failure mode — Erasing the old device before the new one has read the backup**
>
> The application owns transport selection, peer confirmation, progress UI, interruption
> recovery, and old-device erasure. A transfer can report completion before the new device
> finishes a durable restore. If the user then resets the old device, no server copy remains.
> Erase the old device only after the new device confirms a durable read.

> **Failure mode — Debug logs that contain the material you were protecting**
>
> An undecryptable message can encourage additional logging. Element shipped a bug that
> included this data in debug logs:
>
> > "the private part of the backup key pair [was] logged to application debug logs… 156 unique Matrix IDs have been affected."
>
> Log identifiers, error codes, envelope timestamps, and `.changedAddress`. Never log key
> material, plaintext, or backup blobs. Audit log statements during review, not after an
> incident. See [observability](https://docs.open-e2ee.dev/operate/observability.md).

## Production caveats [#production-caveats]

The SDK is `15.0.x`. Public APIs and persisted formats follow semantic versioning. Persisted formats
matter here: a backup written by an older build may contain session records the current
build rejects and resets rather than migrates.

The SDK is reviewed continuously by adversarial AI agents; it is not audited by any
independent firm. The Expo store is the primary supported adapter and needs a
development build. If you use the key-value store, you supply its backend.
Verify its durability with the exported backend-conformance kit and wire
the `reopen` hook. The in-memory store and an
in-process test relay are development only: recovery testing
built on them proves nothing about durability. `forceCompleteKeyReset()` is development
and debugging only. Do not wire it to a user-facing "reset my account" button.

> **Not covered — Key transparency and legal hold**
>
> Verifiable append-only logs of identity keys, and the auditor infrastructure that makes
> them meaningful, are not part of this SDK. Whether your organization must retain messages
> and produce them on request is a legal question that interacts strongly with the profile
> you pick above. Take it to counsel, not to this page.

## Next [#next]

- [Offline send, receive, and reconciliation](https://docs.open-e2ee.dev/build/offline-and-reconciliation.md): the SDK-level detail behind part one
- [Recovery, backup, and migration](https://docs.open-e2ee.dev/build/recovery-backup-migration.md): the three profiles in full
- [Identity changes and safety numbers](https://docs.open-e2ee.dev/build/identity-change-safety-numbers.md): the verification build
- [Error handling](https://docs.open-e2ee.dev/operate/error-handling.md): the full error taxonomy
