Skip to Content
OpenE2EEDocs

Error handling and retries

The full error taxonomy, which failures are retryable, and how to recover a session without making ratchet state worse.

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

Encrypted messaging fails differently from the rest of your application. You can repeat a failed HTTP call. You usually cannot repeat a failed decrypt because the attempt advances a state machine. This page covers the taxonomy the SDK throws, which parts of it are worth retrying, and what recovery actually means.

The base class

Every error in the EncryptionErrorCode family extends EncryptionError. The class extends Error and adds three fields:

  • .code: a stable EncryptionErrorCode value. This is the field you branch on.
  • .context: structured context about the operation. Safe to log after redaction. See observability.
  • .originalError: the underlying cause, if a wrapper supplied it.

The code taxonomy

Session

CodeMeaningWhat it implies
SESSION_NOT_FOUNDNo session exists for the addressEstablish one
SESSION_CORRUPTEDSession data is invalidDelete and re-establish

Message

CodeMeaningWhat it implies
INVALID_CIPHERTEXTMalformed message format, or a retry_request envelope given to processIncomingEnvelope()Drop malformed ciphertext. Give a retry_request envelope to receiveIncomingEnvelopes()
DECRYPTION_FAILEDCould not decryptInspect session state
ENCRYPTION_FAILEDCould not encryptInspect session state
MESSAGE_DUPLICATENo 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 insteadDiscard
TOO_MANY_SKIPPED_MESSAGESSkip bound exceededReset session

Identity and trust

UNTRUSTED_IDENTITY requires an explicit trust decision when a candidate no longer matches the pinned tuple. IDENTITY_MISMATCH and SIGNATURE_VERIFICATION_FAILED are integrity failures. Reject their input and inspect the operation.

Prekey and establishment

INVALID_PREKEY_BUNDLE, PREKEY_NOT_FOUND, PREKEY_ROTATION_REQUIRED.

Ratchet

COUNTER_OVERFLOW, INVALID_DH_KEY.

Storage

KEY_STORAGE_ERROR wraps a key-storage failure. STORAGE_QUOTA_EXCEEDED means that the disk or the storage quota is full. The rejected write does not persist, and the store stays open. Inspect the first error's cause. Free space before retrying the second.

Specialized classes and their guards

Use the exported type guards to centralize narrowing and keep call sites stable. The current guards delegate to instanceof, so they require one loaded copy of the SDK. Do not bundle duplicate package instances.

ClassGuardExtra fields
UntrustedIdentityErrorisUntrustedIdentityError().untrustedAddress, .identity
DuplicatedMessageErrorisDuplicatedMessageError().duplicatedAddress, .counter?, .epoch?, .fingerprintPreview?
SealedSenderAuthErrorisSealedSenderAuthError()—
PQXDHRequiredErrorisPQXDHRequiredError().remoteAddress, .reason, .retryable, .suggestedRetryDelay?
StorageQuotaExceededErrorisStorageQuotaExceededError()—

PQXDHRequiredError is what a peer with no post-quantum material looks like under the postQuantum: 'required' policy, which is the only policy. It is a fail-closed outcome, not a fault. See upgrades.

Identify a "Bad MAC" failure

There is no class named BadMacError in this SDK. The classic libsignal "Bad MAC" failure surfaces as DECRYPTION_FAILED. If you search your logs for BadMac, you will find nothing and conclude the problem is elsewhere. Search for the code.

Dispatching

import {
  EncryptionError,
  EncryptionErrorCode,
  ProtocolAddress,
  isUntrustedIdentityError,
} from '@open-e2ee/signal-protocol-sdk';
// The remaining narrowing guards live on the /types subpath, not the package root.
import {
  isDuplicatedMessageError,
  isPQXDHRequiredError,
  isStorageQuotaExceededError,
} from '@open-e2ee/signal-protocol-sdk/types';

async function handleEncryptionError(client, remoteAddress: ProtocolAddress, error: unknown) {
  if (!(error instanceof EncryptionError)) throw error;

  // 1. Human trust decisions. Never automatic.
  if (isUntrustedIdentityError(error)) {
    await ui.showIdentityChanged({
      userId: error.untrustedAddress.userId,
      deviceId: error.untrustedAddress.deviceId,
      identity: error.identity,
    });
    return;
  }

  // 2. Outcomes with a defined move that is not an error to the user.
  if (isDuplicatedMessageError(error)) {
    return; // consumed or expired skipped key
  }
  if (isPQXDHRequiredError(error)) {
    await ui.showPeerCannotReceive(error.remoteAddress, error.reason);
    return;
  }
  if (isStorageQuotaExceededError(error)) {
    await storage.freeSpaceThenRetry();
    return;
  }

  // 3. Codes.
  switch (error.code) {
    case EncryptionErrorCode.MESSAGE_DUPLICATE:
      return; // group paths can raise the base class with this code
    case EncryptionErrorCode.SESSION_CORRUPTED:
      await client.deleteSession(remoteAddress);
      return;
    case EncryptionErrorCode.TOO_MANY_SKIPPED_MESSAGES:
      await ui.showMessageUnavailable(remoteAddress);
      return;
    case EncryptionErrorCode.DECRYPTION_FAILED:
      metrics.increment('signal.decrypt.failed', { code: error.code });
      return;
    default:
      client.logger.error?.('Unhandled Signal Protocol error', error, { code: error.code });
  }
}

Note the ordering. Specialized guards run before the code switch because an UntrustedIdentityError also carries a code. A generic branch would otherwise swallow it.

What to retry, and what never to retry

/utils/retry exports withRetry(fn, options) with operationName, maxRetries, baseDelay, maxDelay, and enableJitter. It also exports isRetryableError(error), which encodes the SDK's own view.

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

await withRetry(() => client.syncToServer(), {
  operationName: 'syncToServer',
  maxRetries: 2,
  baseDelay: 2000,
  maxDelay: 30000,
});

Retryable. Network and timeout failures, database lock and busy conditions, and transient race conditions. These are I/O problems wearing a crypto costume. syncToServer(), rotatePreKeys(), and prekey bundle fetches belong here.

Retried once by the SDK. A user-visible or background-sync send can receive 503 DELIVERY_UNCERTAIN from the OpenE2EE Signal Protocol Relay: the delivery was neither confirmed nor refused. The SDK posts the identical request one more time under the same message identifier before it throws. When the error still reaches your code, isOutgoingMessageError(error) gives you error.clientMessageId. Call send() again with that identifier and the SDK replays the stored ciphertext. Never send the same content under a new identifier, and never change the request under a reused one: the Relay answers 409 RETRY_CONFLICT, which is terminal. See the Relay delivery table.

Explicitly non-retryable. The SDK treats ten codes as terminal and will not retry them. Eight are EncryptionErrorCode values: INVALID_PREKEY_BUNDLE, ENCRYPTION_FAILED, TOO_MANY_SKIPPED_MESSAGES, KEY_STORAGE_ERROR, UNTRUSTED_IDENTITY, SIGNATURE_VERIFICATION_FAILED, RECIPIENT_NOT_REGISTERED, and PREKEY_FETCH_RATE_LIMITED. Two are the Relay codes UPGRADE_REQUIRED and DEVICE_REVOKED. HostedSignalProtocolRelayUpgradeRequiredError carries UPGRADE_REQUIRED when the Relay no longer serves the protocol version of the SDK. Only a newer SDK release succeeds. See Relay protocol version.

The SDK also does not retry HostedSignalProtocolRelayDeviceUnknownError. See when the Relay refuses this device.

Never wrap a decrypt in a retry. This is the single most common mistake. Retrying decryptMessage(...) does not help. The applicable message key was already consumed or was never derivable. Each attempt re-enters a state machine that moves forward.

Repeated attempts against a damaged session consume the skipped-key budget. They can leave ratchet state less recoverable than before. If a decrypt fails, route to recovery. Do not try again.

Never retry an identity change. UNTRUSTED_IDENTITY means the candidate no longer matches the peer's pinned tuple. That is a trust decision belonging to a person. Automating it converts a security control into a notification.

When the Relay refuses this device

The Relay can refuse this device. Two errors name that refusal. Neither is an EncryptionError, and the SDK retries neither one. The main entry and /client export both classes.

ErrorCauseWhat the application does
HostedSignalProtocolRelayDeviceRevokedErrorAn account recovery revoked this device, or the device was removed from the account, for example by idle expiry. code is DEVICE_REVOKED, status is 403, and retryable is false.Sign the user out of this device. A removal or an idle expiry revokes the device's authentication key permanently. The Relay refuses that key with DEVICE_REVOKED on a token refresh, a registration, and a device link. To use this device again, link it again from the primary device. The new link gets a new device key.
HostedSignalProtocolRelayDeviceUnknownErrorA device token request found no device for the stored session. code is NOT_FOUND, status is 404, and retryable is false.Ask the user to confirm a re-registration of this device. Do not re-register without that confirmation. When the account has other devices, the Relay refuses the re-registration with DEVICE_LINK_REQUIRED. See When the account already has a device.

The SDK never registers a device or retries after a device refusal. createHostedSignalProtocolClient throws either error when the stored session cannot get a device token. It does not register a new device in its place. A running client throws them from its Relay calls. A client call can wrap them in an EncryptionError, as the originalError. isRetryableError() returns false for both errors.

The mailbox subscription stops with the reason device-revoked or device-unknown. It does not reconnect and does not pull. A switch over SignalProtocolRelayConnectionReason must handle both values.

The subscription also stops with the reason authority-refused when the Relay refuses its socket token request or a pull conclusively. That refusal has retryable false and the code AUTHORITY_DENIED, NOT_FOUND, or OPERATION_EXPIRED. A deleted account gets this refusal. A refusal with retryable true goes to the retry schedule. A NOT_FOUND on the socket token request is a refusal of this device, so the reason is then device-unknown.

Re-register a device

To re-register, create the client again with assertionPurpose: 'reregister'. The client keeps the stored identity and device key, and it asks for a register assertion. It throws before any assertion when the store holds no identity or no device key. A retry after a failed call sends the same registration again.

A re-registration has these effects:

  • When the account holds this device key with the same Signal identity, the device keeps its device ID.
  • When the account holds other devices but not this device key, the Relay refuses the re-registration with DEVICE_LINK_REQUIRED. If recovery revoked the device and the Relay has no revoked-key record, the device reads as unknown. It gets this refusal. See When the account already has a device.
  • After the SDK submits an account deletion request from this store, it refuses the re-registration with DELETION_ALREADY_REQUESTED. To register the person again with a new account, see Register after account deletion.
  • When a deletion removed the account, the Relay refuses the re-registration with AUTHORITY_DENIED. The Relay refuses each registration with an identity of a deleted account, for example a store copy that holds the device-owned identity key of the deleted account.
import {
  HostedSignalProtocolRelayDeviceRevokedError,
  HostedSignalProtocolRelayDeviceUnknownError,
  createHostedSignalProtocolClient,
} from '@open-e2ee/signal-protocol-sdk';

try {
  signal = await createHostedSignalProtocolClient(options);
} catch (error) {
  if (error instanceof HostedSignalProtocolRelayDeviceRevokedError) {
    signOutThisDevice();
  } else if (
    error instanceof HostedSignalProtocolRelayDeviceUnknownError &&
    (await confirmReregistration())
  ) {
    signal = await createHostedSignalProtocolClient({
      ...options,
      hosted: { ...options.hosted, assertionPurpose: 'reregister' },
    });
  } else {
    throw error;
  }
}

When the account already has a device

The Relay registers only the first device of an account. A registration with a new device key on an account that has a device gets HTTP 409. createHostedSignalProtocolClient then throws a HostedSignalProtocolRelayHttpError with code DEVICE_LINK_REQUIRED, status 409, and retryable false. This occurs with custom-token and native provider identity. Examples are a reinstall, a new phone, and cleared site data.

Do not retry the registration. A retry sends the same registration and gets the same refusal. Do not wrap the registration in withRetry(): isRetryableError() returns true for this error, because the check does not read retryable and does not list DEVICE_LINK_REQUIRED. Do one of these:

  • Link the device from an active device of the account. See Multi-device.
  • Recover the account with assertionPurpose: 'recover'. Recovery revokes every earlier device of the account.

A known device key with a different Signal identity gets KEY_PROOF_INVALID. In device-owned identity, a new store makes a new account, so it does not get this refusal.

When a retry request ends with no resend

A failed decrypt asks the sender device for a resend. That retry request can end with no resend. The content of the failed envelope is then lost. The onRetryTerminal hook tells your application when this happens, so it can show that the message is unavailable.

The hook runs once for each request, with a RetryTerminalEvent. The event has the terminal class, the failedEnvelopeId, and recovery?. Only a posting-deadline end resets the session. A request-expired end that the SDK moved from an SDK 13.x record can also have recovery. The failedEnvelopeId is the Relay message ID of the envelope that the requester failed to decrypt. The main entry and /client export the RetryTerminalEvent and RetryTerminalClass types.

ClassCauseDevice that gets it
missing-senderThe device that sent the failed message is gone.The requester
revoked-authorityThe Relay revoked the authority of the post.The requester
request-expiredThe Relay answered or holds the latest attempt of the request, and the content did not come before the deadline. The deadline is 14 days after the first failure. The session does not reset. This class is not the delivery error cause request-ended.The requester
posting-deadlineThe Relay did not accept the latest attempt of the request. A post was due at or after the posting deadline, 24 hours after the first failure, or the Relay refused a post with OPERATION_EXPIRED, or the request got to its deadline. The requester then archives its session with the sender device, and recovery describes that reset.The requester
attempts-exhaustedThe resend that answers the fifth attempt also failed. The request posts no sixth attempt and resets no session.The requester
deletionThe account of the other device is deleted.The requester
abuse-allowance-exhaustedThe sender used up its retry allowance.The requester
missing-prekeyThe Relay has no prekey bundle of the requester, so the sender of the resend cannot start a new session.The sender of the failed message
membership-refusedThe requester is not a current member of the group of the message, or the group has no membership source, so the sender gives no content.The sender of the failed message
signal.registerHook('onRetryTerminal', async (event) => {
  await messageStore.markUndecryptable(event.failedEnvelopeId, event.class);
});

The SDK stores the terminal state before it calls the hook. A client stop during the hook can make it run again after the next start. Write the hook so that a second call for the same failedEnvelopeId has no new effect.

Session recovery

Four operations, in ascending order of destruction:

  • hasSession(remoteAddress): cheap existence check before you decide anything.
  • getSessionHealth(userId): diagnostics. Returns status, sessionExists, issues[], a keyStatus block (hasIdentityKey, hasSignedPreKey, hasKyberPreKey, signedPreKeyAgeDays, kyberPreKeyAgeDays, needsRotation), and, when a session exists, sessionStatus with ageDays, messagesSent, messagesReceived, isExpiredForSending, and isExpiredForReceiving.
  • archiveSession(remoteAddress): moves the current session to the inactive list. This preserves it for delayed message decryption. Per SESAME §3.2 the "previously active session is moved to the head of the inactive sessions list." Use this operation when a peer reinstalls and their session no longer matches. Messages encrypted to the old session can still arrive.
  • deleteSession(remoteAddress): destroys it. Anything still in flight under that session becomes undecryptable.

forceCompleteKeyReset() sits outside this ladder. It returns a ForceKeyResetResult counting deletedSessions and deletedPreKeys, and the SDK documents it as a development and debugging operation. If production code calls it, the product lacks a recovery path. The call is not itself a recovery path.

Opacity ledger

ArtifactStays on deviceSent to relayIn object storeVisible as metadata
EncryptionError.codeyesnonosafe to export to telemetry
EncryptionError.contextyesnonoexport only after redaction
.identityyesnonopublic halves; never log
.untrustedAddressyesnonoidentifies a peer; treat as PII
Failed ciphertextyesalready at relaynoenvelope size
Message plaintextyesnonono
Session record (version: 4)yesnonono

Request registration support

If a registration response provides x-signal-relay-request-id, copy only its value. SDK 14.4 does not add that reference to its error object. In a browser, open developer tools and select the registration request in the Network panel. Read the ID from the response headers. For SDK versions that provide an optional error.requestId, use it when present. An absent ID does not establish whether a request occurred.

Send the request ID, approximate UTC time, SDK version, and runtime name and version. Include the public HTTP status and error code when available. State the environment, Sandbox or Production, the operation, and whether this was the first attempt or a retry. The ID grants no diagnostic read access. A missing retained record leaves the historical outcome unknown.

Do not send HAR files, cURL output, tokens, assertions, private keys, or database contents. Keep the encrypted device store and existing identity. Do not clear storage, reinstall, or reset the identity to get a request ID.

Next

On this page