# Errors (https://docs.open-e2ee.dev/reference/errors.md)

Applies to `@open-e2ee/signal-protocol-sdk` `15.0.x`. Public APIs and persisted formats follow semantic versioning.

Every error in this taxonomy extends `EncryptionError`. Branch on `error.code`,
or use a type guard when you need the extra properties a specialized class
carries. Other SDK modules publish separate error families. For how to structure
handling around this family, see [error handling](https://docs.open-e2ee.dev/operate/error-handling.md).

## Where to import from [#where-to-import-from]

> **Most guards are on /types, not the package root**
>
> The package root exports `EncryptionError`, `EncryptionErrorCode`, `SealedSenderAuthError` with `isSealedSenderAuthError`, and `UntrustedIdentityError` with `isUntrustedIdentityError`. An application branches on those errors. Import **every other narrowing guard** through the `/types` subpath: `isEncryptionError`, `isDuplicatedMessageError`, `isPQXDHRequiredError`, `isStorageQuotaExceededError`, and `isSecureRandomUnavailableError`.
>
> ```ts
> import { EncryptionErrorCode, isUntrustedIdentityError } from '@open-e2ee/signal-protocol-sdk';
> import { isDuplicatedMessageError } from '@open-e2ee/signal-protocol-sdk/types';
> ```
>
> Importing them from the root fails to resolve. See [package subpaths](https://docs.open-e2ee.dev/reference/package-subpaths.md).

## There is no `BadMacError` [#there-is-no-badmacerror]

> If you migrate from libsignal, you probably search for `BadMacError`. It does not exist in this package: the string "Bad MAC" appears nowhere in the source.
>
> The failure it names surfaces here as `EncryptionErrorCode.DECRYPTION_FAILED`. Match on that code, not on a class name or a message substring.

The same applies to error-message matching in general. Message text is not API. Codes are. See [migrating from libsignal](https://docs.open-e2ee.dev/guides/migrating-from-libsignal.md).

## `EncryptionError` [#encryptionerror]

The base class. Each specialized class on this page extends it.

| Member | Type | Notes |
|---|---|---|
| `code` | `EncryptionErrorCode` | Always present; this is the branch point |
| `context` | `EncryptionErrorContext \| undefined` | Structured detail |
| `address` | getter | Convenience read of `context.address` |
| `operation` | getter | Convenience read of `context.operation` |
| `originalError` | getter | The wrapped cause, when the error wraps one |

`EncryptionErrorContext` carries optional `address`, `operation`, `identityKey`, `identity`, `originalError`, and is open to additional keys.

```ts
import { EncryptionErrorCode } from '@open-e2ee/signal-protocol-sdk';
// Narrowing guards live on the /types subpath, not the package root.
import { isEncryptionError } from '@open-e2ee/signal-protocol-sdk/types';

try {
  await signal.send(recipientId, body);
} catch (error) {
  if (!isEncryptionError(error)) throw error;
  if (error.code === EncryptionErrorCode.UNTRUSTED_IDENTITY) {
    // stop and surface to the user; do not retry
  }
}
```

`isEncryptionError()` is the outermost guard for this family. A rejected value
can be an application error or an error from another SDK family.

## `EncryptionErrorCode` [#encryptionerrorcode]

The full enum, grouped as the source groups it.

### Session [#session]

| Code | What it means | What to do |
|---|---|---|
| `SESSION_NOT_FOUND` | No session with this address | Establish one, or let `send()` do it |
| `SESSION_CORRUPTED` | Stored session record is unusable | Delete the session and re-establish |
| `RECIPIENT_NOT_REGISTERED` | Recipient has no registered device | Surface to the user; there is nothing to retry against |
| `PREKEY_FETCH_RATE_LIMITED` | The OpenE2EE Signal Protocol Relay throttled the bundle fetch | Back off and retry later |
| `SESSION_ESTABLISHMENT_FAILED` | Handshake failed | Inspect `originalError`; often a bundle or relay problem |

### Message [#message]

| Code | What it means | What to do |
|---|---|---|
| `INVALID_CIPHERTEXT` | Malformed or truncated ciphertext, or a `retry_request` envelope given to `processIncomingEnvelope()` | Drop malformed ciphertext; do not retry. Give a `retry_request` envelope to `receiveIncomingEnvelopes()` |
| `DECRYPTION_FAILED` | Decryption did not produce plaintext | Drop the message. With a relay, the client sends any retry request. Without a relay, deliver the envelope that the `sendRetryRequest` option receives |
| `ENCRYPTION_FAILED` | Encryption failed locally | Not retryable; check session and key state |
| `INVALID_SEND_TIMESTAMP` | A new send cannot get a valid unique timestamp, or a sync to linked devices carries an application time that the SDK refuses. A new send also refuses a timestamp that a different send of the device used | Omit the timestamp, or correct it, for a new operation; inspect `InvalidSendTimestampError` |
| `SEND_ACCEPTANCE_UNKNOWN` | The posting deadline of a direct or group send ended and the Relay acceptance of a device is not known; the message might have arrived | Tell the user that the message might already have arrived; do not replay the send; inspect `SendAcceptanceUnknownError` |
| `SEND_NEVER_ACCEPTED` | The posting deadline of a direct or group send ended, the call raised no refusal, and no refused device has a stored refusal code | Tell the user which devices did not get the message; inspect `SendNeverAcceptedBySignalProtocolRelayError` |
| `MESSAGE_DUPLICATE` | No retained key exists below the current counter. For a message that this client processed or that gives no content, `processIncomingEnvelope()` returns the `duplicate` or `null-message` outcome instead | Discard it |
| `TOO_MANY_SKIPPED_MESSAGES` | Skip bound exceeded — `maxSkip`, default 25000 | Not retryable; the sender is too far ahead or something is wrong |
| `REPLAY_DETECTED` | Envelope and encrypted-content timestamps differ | Drop it; this is a defense, not a glitch |
| `SENDER_KEY_EXPIRED` | Group sender key is past its lifetime | Rotate and redistribute |
| `GROUP_MASTER_KEY_MISSING` | The client has no group master key for a managed group that it sends to. The send stores and posts nothing | Store the group master key through the link or sync path, then send again |

### Identity and trust [#identity-and-trust]

| Code | What it means | What to do |
|---|---|---|
| `UNTRUSTED_IDENTITY` | A candidate differs from the pinned tuple, or verification has no pinned tuple | Stop; require an explicit trust decision before accepting a changed tuple |
| `IDENTITY_MISMATCH` | Presented identity does not match the stored record | Stop; treat as a trust event |
| `SIGNATURE_VERIFICATION_FAILED` | A signature did not verify | Reject the material outright |

Never auto-accept an identity change. See [identity change and safety numbers](https://docs.open-e2ee.dev/build/identity-change-safety-numbers.md).

### Prekeys and session establishment [#prekeys-and-session-establishment]

| Code | What it means | What to do |
|---|---|---|
| `INVALID_PREKEY_BUNDLE` | Bundle is malformed or fails verification | Not retryable; a relay or peer bug |
| `PREKEY_NOT_FOUND` | Requested prekey is gone | Refetch the bundle |
| `PREKEY_ROTATION_REQUIRED` | Local prekeys are too old to send with | Rotate; see `maxPreKeyAgeMs` |

### Ratchet [#ratchet]

| Code | What it means | What to do |
|---|---|---|
| `COUNTER_OVERFLOW` | Message counter exceeded its bound | Re-establish the session |
| `INVALID_DH_KEY` | Ratchet public key rejected | Drop the message |

### Storage [#storage]

| Code | What it means | What to do |
|---|---|---|
| `KEY_STORAGE_ERROR` | Store failed reading or writing key material | Not retryable; check the adapter |
| `STORAGE_QUOTA_EXCEEDED` | The store refused a write for want of room | Free space or prompt the user; carries `StorageQuotaExceededError` |
| `SECRET_VAULT_REQUIRED` | A store that keeps a local secret was opened without a secret vault | Pass a vault, such as `ReactNativeKeychainSignalProtocolSecretVault` |
| `LOCAL_STORE_KEY_LOST` | The store holds data, but its vault holds no key for that data | Restore the vault entry, or reset the store; a reset deletes the local data |

### Initialization [#initialization]

| Code | What it means | What to do |
|---|---|---|
| `INITIALIZATION_FAILED` | Client creation did not complete | Do not use the instance; inspect `originalError` |
| `SECURE_RANDOM_UNAVAILABLE` | The runtime has no cryptographically secure random source | Install a global `crypto.getRandomValues` provider before the first SDK call; carries `SecureRandomUnavailableError` |
| `SIGNAL_PROTOCOL_RELAY_NAME_CONFLICT` | A receive record that an earlier SDK stored holds the Relay receipt decision under two names, with different values. The receive of that record gives the error. A call does not give it. The message is `A stored record holds <earlierName> and <newName> with different values. The two names hold one value.`; carries `SignalProtocolRelayNameConflictError` with `newName` and `earlierName` | Report a store error with `earlierName` and `newName` |

### Protocol strategy [#protocol-strategy]

| Code | What it means | What to do |
|---|---|---|
| `PQXDH_REQUIRED` | Post-quantum handshake required but unavailable | See `PQXDHRequiredError` below; possibly retry later |
| `PQXDH_FAILED` | PQXDH handshake failed | Inspect `reason`; fails closed rather than downgrading |
| `TRIPLE_RATCHET_REQUIRED` | Triple Ratchet required but unavailable | Peer cannot meet policy |

### SPQR [#spqr]

| Code | What it means |
|---|---|
| `SPQR_EPOCH_OUT_OF_RANGE` | Epoch outside the accepted window |
| `SPQR_MESSAGE_JUMP_TOO_LARGE` | Gap exceeds the bound |
| `SPQR_COUNTER_OVERFLOW` | Counter bound exceeded |
| `SPQR_INVALID_CIPHERTEXT` | Malformed SPQR ciphertext |
| `SPQR_VERSION_MISMATCH` | Unsupported SPQR version |

These are bounds checks in the post-quantum ratchet. They mean that the ratchet deliberately rejected a message. Drop it. If the error recurs, treat it as a signal that the peer states differ.

### Sealed sender [#sealed-sender]

| Code | What it means | What to do |
|---|---|---|
| `SEALED_SENDER_AUTH_FAILED` | Sender certificate or access key rejected | Fall back to an authenticated send, or refresh the certificate |
| `SEALED_SENDER_REQUIRED` | `sealedSender.deliveryMode` is `'required'`, and anonymous delivery is unavailable or its authorization was rejected | The SDK does not fall back to identified delivery; change the delivery mode only as a privacy decision |

### Runtime [#runtime]

| Code | What it means | What to do |
|---|---|---|
| `BINARY_BLOB_UNAVAILABLE` | The runtime's `Blob` cannot hold binary data, as on React Native, so `encryptFile` and `decryptFile` cannot work | Use `streamingEncrypt` and `streamingDecrypt` from `/files` |
| `SQLITE_ENGINE_UNAVAILABLE` | The SQLite Wasm engine did not load in its web worker | Allow `'wasm-unsafe-eval'` in the `script-src` of the worker script's own policy; check that the Wasm file is served as `application/wasm` |
| `OPFS_UNAVAILABLE` | The browser cannot keep a SQLite database in the origin private file system, for example in a private window | Use the IndexedDB store in this browsing context |
| `OPFS_FILE_BUSY` | Another tab or worker of the origin still holds the database file | Retry later; the file is unchanged, so do not change to another store |

### Generic [#generic]

| Code | What it means |
|---|---|
| `INVALID_STATE` | The operation is not valid in the current state |

## Specialized classes [#specialized-classes]

Each carries a type guard and extra properties. Use the guard to centralize
narrowing. The current guards delegate to `instanceof`, so duplicate SDK
instances remain unsupported.

| Class | Guard | Extra properties |
|---|---|---|
| `UntrustedIdentityError` | `isUntrustedIdentityError()` | `untrustedAddress`, `identity` |
| `DuplicatedMessageError` | `isDuplicatedMessageError()` | `duplicatedAddress`, `counter?`, `epoch?`, `fingerprintPreview?` |
| `SealedSenderAuthError` | `isSealedSenderAuthError()` | — |
| `PQXDHRequiredError` | `isPQXDHRequiredError()` | `remoteAddress`, `reason`, `retryable`, `suggestedRetryDelay?` |
| `StorageQuotaExceededError` | `isStorageQuotaExceededError()` | — |
| `SecureRandomUnavailableError` | `isSecureRandomUnavailableError()` | — |
| `InvalidSendTimestampError` | `isInvalidSendTimestampError()` | `timestamp`, `reason`, `earliest?`, `latest?` |

> The specialized classes prefix property names: `untrustedAddress`, `duplicatedAddress`, `remoteAddress`. They have no single `error.address` beyond the base-class getter that reads `context.address`.

`PQXDHRequiredError` detail:

| Property | Values |
|---|---|
| `reason` | `'no_kyber_prekey'` \| `'pqxdh_failed'` |
| `retryable` | `boolean` |
| `suggestedRetryDelay` | `30000` by default when `retryable` is true |

`'no_kyber_prekey'` with `retryable: true` is the common and recoverable case: the peer has not yet uploaded post-quantum key material. Wait `suggestedRetryDelay` and try again. The SDK has no classical handshake to fall back to. It fails closed: see [security and protocol policy](https://docs.open-e2ee.dev/reference/security-policy.md).

`DuplicatedMessageError` is not a fault. Delivery retries produce it. Swallow it.

A new application-supplied send timestamp must be a safe positive integer in
milliseconds. It can be at most 5 minutes ahead of the SDK clock or 24 hours
behind it. Each send timestamp is unique per sender device. The SDK throws
`InvalidSendTimestampError` before it stores or posts the send. Its `reason` is
`not_safe_positive_integer`, `too_far_ahead`, `too_old`, or `already_used`.
`earliest` and `latest` hold the window, and both are absent for `already_used`.

A new send with a timestamp that a different send of the device used gets
`already_used`. The SDK's own sends, such as the sender key distribution,
reserve timestamps from the same index of the device. So a `Date.now()` value
from the application can get `already_used` when the application did not use
the value again. Omit `timestamp`, or send again with no `timestamp` on
`already_used`. When a different send used the timestamp that the SDK reads
from its clock, the SDK moves to the next free millisecond. A moved timestamp
more than 5 minutes ahead of the SDK clock gets `too_far_ahead`.

A retry with a stored `clientMessageId` and its stored timestamp keeps that
timestamp without checking the window again. A manual resend and a retry answer
also keep the original timestamp.

## Relay delivery [#relay-delivery]

A hosted `send()` can fail after encryption succeeds, when the Relay answers the
delivery request with an error. These answers are not `EncryptionError`
instances. `send()` attaches the operation's `clientMessageId` to whatever it
throws, and `isOutgoingMessageError(error)` narrows to that shape. A repeat
`send()` with the same `clientMessageId` replays the persisted ciphertext under
the same Relay message identifier, so a retry never advances the ratchet twice.

| Code | Status | What it means | What the SDK does | What to do |
|---|---|---|---|---|
| `DELIVERY_UNCERTAIN` | 503 | The Relay could not confirm that a `user-visible` or `background-sync` delivery was recorded | Posts the identical request once more, then throws | Call `send()` again with the same `clientMessageId`, with backoff; never mint a new identifier for the same content |
| `RETRY_CONFLICT` | 409 | A repeat of an accepted operation changed its request, for example its delivery class | Throws at once | Fix the caller; the first acceptance stands |
| `DELIVERY_ALREADY_ACCEPTED` | 409 | The message identifier belongs to an operation that the Relay already accepted, so the Relay refused the request before it stored anything | Records the destination as accepted | Nothing; the first acceptance stands, and the Relay charged nothing for the refused request |

The SDK does not retry an `ephemeral` delivery. Treat an uncertain answer on that
class as a dropped best-effort message.

Each request to the Signal Protocol Relay ends after 30 s. This deadline includes
the response body. A request that exceeds the deadline rejects with
`Signal Protocol Relay request could not be completed`.
Its `cause` is `Signal Protocol Relay request timed out`.
For a `send()`, call `send()` again with the same
`clientMessageId`. The Relay drops a repeat of an operation that it accepted.

## Relay protocol version [#relay-protocol-version]

An HTTP call to the Relay throws `HostedSignalProtocolRelayUpgradeRequiredError` when the
Relay no longer serves the protocol version of the SDK. This error is not an
`EncryptionError`. The class is exported from the main entry and from `/client`.

| Property | Value |
|---|---|
| `code` | `'UPGRADE_REQUIRED'` |
| `status` | The HTTP status of the refusal, 426 from a current Relay |
| `retryable` | `false` |

The SDK does not retry it. The same request fails again until you ship a newer
SDK release. The mailbox subscription stops with the reason `upgrade-required`
for the same refusal on its socket. The code `PROTOCOL_UNSUPPORTED` stays
retryable. See [protocol versions](https://docs.open-e2ee.dev/signal-relay/protocol-versions.md).

## Relay device refusal [#relay-device-refusal]

The Relay can refuse this device. Two errors name that refusal. Neither is an
`EncryptionError`. The main entry and `/client` export both classes.

`HostedSignalProtocolRelayDeviceRevokedError` means that an account recovery revoked this
device, or that the device was removed from the account, for example by
[idle expiry](https://docs.open-e2ee.dev/signal-relay/device-lifecycle-and-recovery.md#remove-idle-linked-devices). To use
the device again, link it again.

| Property | Value |
|---|---|
| `code` | `'DEVICE_REVOKED'` |
| `status` | `403` |
| `retryable` | `false` |

`HostedSignalProtocolRelayDeviceUnknownError` means that a device token request found no
device for the stored session. The Relay sends this answer as `NOT_FOUND`.

| Property | Value |
|---|---|
| `code` | `'NOT_FOUND'` |
| `status` | `404` |
| `retryable` | `false` |

The SDK never registers a device or retries after either error.
`createHostedSignalProtocolClient` throws the error when the stored session
cannot get a device token. A client call can wrap it in an `EncryptionError`,
as the `originalError`. The mailbox subscription stops with the reason
`device-revoked` or `device-unknown`. A conclusive refusal of the session
stops it with the reason `authority-refused`. To re-register an unknown device
after the user confirms, create the client again with
`assertionPurpose: 'reregister'`. When the account has other devices, the Relay
refuses that re-registration with `DEVICE_LINK_REQUIRED`. See
[error handling](https://docs.open-e2ee.dev/operate/error-handling.md#when-the-relay-refuses-this-device).

A registration with a new device key on an account that has a device gets a
`HostedSignalProtocolRelayHttpError`. Link the device from an active device of
the account, or recover the account. See
[when the account already has a device](https://docs.open-e2ee.dev/operate/error-handling.md#when-the-account-already-has-a-device).

| Property | Value |
|---|---|
| `code` | `'DEVICE_LINK_REQUIRED'` |
| `status` | `409` |
| `retryable` | `false` |

## Retrying [#retrying]

`withRetry` and `isRetryableError` come from `@open-e2ee/signal-protocol-sdk/utils/retry`.

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

const result = await withRetry(() => signal.send(recipientId, body), {
  operationName: 'send message',
});
```

### `SignalProtocolRetryConfig` [#signalprotocolretryconfig]

| Field | Default | Notes |
|---|---|---|
| `maxRetries` | `2` | Retries after the first attempt; total attempts is `maxRetries + 1` |
| `baseDelay` | `1000` ms | First backoff interval |
| `maxDelay` | `10000` ms | Ceiling on any single delay |
| `enableJitter` | `true` | Subtracts up to 25% from each computed delay |
| `operationName` | `'unknown operation'` | Appears in log lines only |

Backoff multiplier is 2 and is not configurable.

### Never retried [#never-retried]

`isRetryableError()` returns `false` for exactly these codes:

| Code | Why |
|---|---|
| `INVALID_PREKEY_BUNDLE` | The bundle is wrong; time will not fix it |
| `ENCRYPTION_FAILED` | Local failure; state must change first |
| `TOO_MANY_SKIPPED_MESSAGES` | A bound was hit deliberately |
| `KEY_STORAGE_ERROR` | The store rejected the operation; the adapter must change first |
| `UNTRUSTED_IDENTITY` | Retrying past a trust event is the wrong behavior, not a slow one |
| `SIGNATURE_VERIFICATION_FAILED` | The material is rejected; a second attempt rejects it again |
| `RECIPIENT_NOT_REGISTERED` | There is nothing to send to until the recipient registers |
| `PREKEY_FETCH_RATE_LIMITED` | The relay is refusing on purpose; `withRetry` would press it |
| `UPGRADE_REQUIRED` | The Relay no longer serves the protocol version of this SDK; only a newer SDK succeeds |
| `DEVICE_REVOKED` | An account recovery revoked this device, or the device was removed from the account; the Relay refuses the revoked device key on a token refresh, a registration, and a device link |

`isRetryableError()` also returns `false` for `HostedSignalProtocolRelayDeviceUnknownError`.
That error has the code `NOT_FOUND`, which also names other failures, so the
check reads the error name.

`isRetryableError()` returns `true` for the `DEVICE_LINK_REQUIRED` refusal of a
registration. The check does not read `retryable`, and the code list does not
hold this code. Do not wrap a registration in `withRetry()`, because each
attempt gets the same refusal.

> `isRetryableError()` returns `true` for anything it does not recognize, including non-SDK errors. Wrapping an operation in `withRetry()` therefore retries unknown failures by default. This default can help with transient network faults but can hide programming errors. Scope `withRetry()` to the calls you intend to retry, not to a whole handler.

Beyond the code list, `isRetryableError()` also inspects the message text for transient patterns. Network faults: network, fetch, connection, timeout, socket, and the `ECONNREFUSED`, `ENOTFOUND`, `ENETUNREACH`, and `ETIMEDOUT` codes. Store contention: lock and busy. Races: race, concurrent, and conflict.

## Next [#next]

- [Error handling](https://docs.open-e2ee.dev/operate/error-handling.md): the handling patterns these codes feed
- [Identity change and safety numbers](https://docs.open-e2ee.dev/build/identity-change-safety-numbers.md): the trust-event path
- [Offline and reconciliation](https://docs.open-e2ee.dev/build/offline-and-reconciliation.md): retry and delivery in practice
- [Migrating from libsignal](https://docs.open-e2ee.dev/guides/migrating-from-libsignal.md): name-by-name mapping
