# Multi-device (https://docs.open-e2ee.dev/build/multi-device.md)

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

Every Alice-and-Bob tutorial stops at two devices that both existed before the
first message. Real products do not work that way. Alice buys a tablet in March,
and her phone dies in July. Both events affect session state that started its
ratchet in January. This page covers those events.

## The device model [#the-device-model]

A user has a changing set of devices that share the account identity.
Each device has separate device-authentication keys, prekeys, and sessions.

The primary device uses `deviceId` `1`. The backend allocates linked device IDs
from `2` through `5`. A client must not choose its own linked-device ID.
That gives a ceiling of five devices: one primary and four linked. The relay owns
slot allocation because it is the only party that can see the whole set and
enforce uniqueness against an authenticated account.

A registration adds only the first device of a Relay account. Each later device
joins by the managed device link. The Relay refuses a registration with a new
device key on an account that has a device, with code `DEVICE_LINK_REQUIRED`.

The managed device link has two forms. The two-device link joins a new device
that starts with an empty store. The one-process link joins a device whose
store already holds the account identity.

Sesame is the specification that governs this. The SDK selects SESAME's per-user
identity-key model. Every linked device holds that tuple unchanged.
Registration IDs, prekeys, and sessions are device-specific. Sesame is Revision 2,
dated 2017-04-14.

## Linking is not transfer [#linking-is-not-transfer]

These are two separate operations. Do not confuse them. That is the most
expensive mistake available on this page.

| | Two-device link | One-process link | Transfer |
|---|---|---|---|
| Purpose | Join a new device to the OpenE2EE Signal Protocol Relay account | Join a device whose store holds the account identity | Move the account identity to another device |
| Moves identity material | yes, in an end-to-end encrypted envelope | **no**, the store must already hold it | yes, in an encrypted bundle |
| Moves prekeys | no, the new device creates fresh prekeys | no, the new device creates fresh prekeys | no, the new device creates fresh prekeys |
| Moves group master keys | yes, in the envelope | yes, in the calling process | no |
| Moves sessions | **no** | **no** | **no** |
| Moves message history | **no** | **no** | **no**, only an encrypted backup that you build can |
| Entry point | `joinHostedSignalProtocolRelayAccount()` and `approveHostedSignalProtocolRelayDeviceLink()` from the package root | `linkHostedSignalProtocolRelayDevice()` from the package root | `/device` |

The two-device link moves the account identity in its envelope, so the new
device needs no transfer. For the one-process link, transfer puts the account
identity on the new device, and the link then joins that device to the
account. A user might tap "add my tablet" and expect their archive to appear.
No operation on this page moves that archive.

## Joining a new device [#joining-a-new-device]

The two-device link joins a new device to the account. The new device starts
with an empty store and shows a link code. Device 1 approves the code and
sends the account identity and the groups in an end-to-end encrypted envelope.
The new device then registers with its own device ID, registration ID,
prekeys, and device key.

### What the user does [#what-the-user-does]

On the new device:

1. Open the application and choose to link the device to an existing account.
2. Keep the link code on the screen. The code changes every 90 seconds.

On device 1:

3. Scan the link code.
4. Read the confirmation screen. Approve only a link that you started on your
   own new device.

On the new device:

5. Check the account that the new device shows.
6. Wait for the new device to finish the link.

### Join on the new device [#join-on-the-new-device]

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

const { client, deviceId, applicationData } = await joinHostedSignalProtocolRelayAccount({
  adapters: { storage }, // an empty store
  hosted: {
    relayUrl,
    onLinkCode: (code) => showQrCode(code),
    confirmAccount: ({ accountAddress }) => askUserToConfirmAccount(accountAddress),
    deviceName: 'Laptop',
    profileKeys,
    onFirstSync,
  },
  signal: controller.signal,
});
```

`adapters.storage` must be empty. The join refuses a store that holds an
identity with `STORE_NOT_EMPTY`. A store with an unfinished join is the
exception. See [An interrupted join](https://docs.open-e2ee.dev/build/multi-device.md#an-interrupted-join).

The SDK calls `hosted.onLinkCode` after the Relay channel is ready. Show each
code as a QR code. A code is valid for 90 seconds. Then the SDK opens a new
channel and calls `hosted.onLinkCode` with a new code. Replace the old code on
the screen. The code holds the X25519 public key of the new device, and the
Relay never gets that key.

The SDK calls `hosted.confirmAccount` with the `accountAddress` from the
envelope. The call comes after the new device opens the envelope and before it
registers. Show the account, and return the choice of the user. A `false`
return stops the join with `CANCELLED`. The join then registers nothing and
writes nothing to the store.

`hosted.deviceName` must be 1 to 50 UTF-16 code units. For another length, the
join throws a `RangeError` before it sends a request. The join does not
truncate a name. It encrypts the name to the account identity key, so each
device of the account can read the name, and the Relay cannot. Without the
option, the device has no name until a rename.

The call resolves with the started client, its device ID, and the
`applicationData` of the approval.

The SDK does not copy the profile key.
Device 1 puts the profile key in `applicationData`. Store that key on the new
device after the join resolves. Until then, `getOwnProfileKey()` must return
`null` or wait for the key. It must never make a new key. Each device of an
account must return the same [profile key](https://docs.open-e2ee.dev/signal-relay/profile-keys.md).

`hosted.onProgress` reports the `'device-link'` operation with the phases
`'preparing-linked-device'`, `'copying'`, `'submitting'`, and `'complete'`, in
that order. The join also takes `hosted.onFirstSync` and
`hosted.onOwnDevicesChanged`. See [First sync to a new
device](https://docs.open-e2ee.dev/build/multi-device.md#first-sync-to-a-new-device) and [Other devices of the
account](https://docs.open-e2ee.dev/build/multi-device.md#other-devices-of-the-account).

### Approve on device 1 [#approve-on-device-1]

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

// `signal` is the client of device 1. `scannedCode` is the text of the QR code.
if (await confirmLinkOnDevice1()) {
  const { deviceId } = await approveHostedSignalProtocolRelayDeviceLink(signal, scannedCode, {
    applicationData: encodeProfileKey(ownProfileKey),
  });
}
```

Always show a confirmation screen before the call. Another person can see the
link code. If that person controls device 1 of an account in the same Relay
project, that person can approve the code first. The new device then joins the
account of that person.

That person cannot read the data of the real account.
That person can read the data that the user then makes on the new device. For
this reason, the new device shows the account in `hosted.confirmAccount` before
it registers.

Only device 1 can approve a link. Another device gets `NOT_PRIMARY`.

`applicationData` must be 16,384 bytes or less. For a larger value, the call
throws a `RangeError` and sends no request. The approval keeps a `deviceName`
option only for compatibility. That option does nothing, and a later major
version removes it. The new device names itself with `hosted.deviceName`.

The call resolves only after the new device links. It reads the link status
with a wait of 500 ms that doubles up to 5 seconds. It resolves with the device
ID that the Relay gave the new device.

When the link token expires before the new device registers, the call rejects
with `LINK_CODE_EXPIRED`. For example, the user of the new device can refuse
the account. An `AbortSignal` in `options.signal` stops the wait with
`CANCELLED`. The new device can still register after that.

A resolved call does not prove that the device is still on the account. The
Relay keeps the `linked` status of the token after a later removal of the
device. To see the current devices, call `listHostedSignalProtocolRelayDevices()`
or use `hosted.onOwnDevicesChanged`.

### What the envelope carries [#what-the-envelope-carries]

Device 1 puts these items in the envelope:

- The `aci` identity key pair of the account.
- The `pni` identity key pair, when the account has one.
- The account address.
- A single-use link token from the Relay.
- The master key of each group that the group store of device 1 lists.
- `applicationData`, when the application gives it.

The envelope holds no registration ID, no device name, no session, and no
message history. The new device makes its own registration ID, prekeys, and
sessions.

The envelope uses hybrid X25519 and post-quantum ML-KEM-768 key agreement.
HKDF-SHA256 derives the key, and AES-256-GCM encrypts the body. The SDK pads
the plaintext to a multiple of 4,096 bytes, so the Relay sees only that size
step. The Relay carries the envelope and cannot decrypt it.

The group store of device 1 does not list a group that a release before 12.0.0
wrote until a read of the group. Read each group once on device 1 before the
link. Sessions and sender keys start fresh on the new device.

### Limits [#limits]

| Item | Value |
|---|---|
| Link code | 90 seconds. Then the new device shows a new code. |
| Link token | 10 minutes on the Relay clock. Single use. |
| Approval wait | Until the new device links, or the link token expires. |
| Devices | 5 per account, with the IDs 1 to 5. The Relay checks the limit when it issues the token and again at registration. |
| Slot hold after a failed approval | Until the token expires, up to 10 minutes. No call cancels a token. |
| Slot hold after a failed registration | Until the Relay deletes the token, 24 hours after the token expires. |
| Envelope plaintext | 258,044 bytes. |
| `applicationData` | 16,384 bytes. |
| Device name | 1 to 50 UTF-16 code units. |

A rate limit gives `HostedSignalProtocolRelayHttpError` with code
`QUOTA_EXCEEDED`. That error is retryable. Wait for the time that `Retry-After`
gives, and then try again.

### Failures [#failures]

A refusal of the link throws `HostedSignalProtocolRelayDeviceProvisioningError`.
Its `retryable` value is always `false`, because the same input gets the same
refusal.

| Code | Device | Cause | What the application shows |
|---|---|---|---|
| `LINK_CODE_INVALID` | Device 1 | The scanned text is not a link code, its key hash does not match, or its version is unknown. | Scan the code again. If the error stays, update the application on device 1. |
| `LINK_CODE_EXPIRED` | Device 1 | The channel of the code closed, or the link token expired before the new device registered. | Scan the current code on the new device. |
| `NOT_PRIMARY` | Device 1 | The device is not device 1. | Approve the link on device 1. |
| `DEVICE_LIMIT_REACHED` | Both | The account has no free device slot. On the new device, the store keeps the unfinished join. | Remove a device, and then start the link again. |
| `ENVELOPE_TOO_LARGE` | Device 1 | The envelope plaintext is larger than 258,044 bytes. | Make `applicationData` smaller. |
| `ENVELOPE_INVALID` | New | The new device cannot open or read the envelope, or the Relay refused its key proof. The join discards its state. | Start the link again. |
| `STORE_NOT_EMPTY` | New | The store holds an identity and no unfinished join, or the join in the store is complete. | Use an empty store. |
| `LINK_TOKEN_REJECTED` | New | The Relay refused the link token. The join discards its state. | Start the link again. If device 1 lists the device, remove it there. |
| `SIGNAL_RELAY_UNSUPPORTED` | Both | The Relay does not serve the two-device link. | Use the one-process link, or try again later. |
| `CANCELLED` | Both | The `AbortSignal` fired, or `hosted.confirmAccount` returned `false`. | Nothing. |

When the Relay has the two-device link turned off, the join and the approval
throw `SIGNAL_RELAY_UNSUPPORTED`. The device list and the removal still work.

### An interrupted join [#an-interrupted-join]

The new device writes a join marker before its first identity write. To
continue an interrupted join, call `joinHostedSignalProtocolRelayAccount()`
again with the same store. The join continues with the stored link token and
opens no new channel.

The join repeats the registration with the same body after no answer, a 5xx
answer, or a retryable answer that is not a rate limit. It sends it at most two
more times. Then it throws, and the store keeps the unfinished join.

The Relay can register the device and then lose its answer. A later join with
the same store gets the same answer until 24 hours after the link token
expires. After that time, the join gives `LINK_TOKEN_REJECTED`, and the device
that the Relay registered has no owner. Remove that device on device 1. See
[Removing a device](https://docs.open-e2ee.dev/build/multi-device.md#removing-a-device).

### Other devices of the account [#other-devices-of-the-account]

`hosted.onOwnDevicesChanged` receives `{ added, removed }`. Each value is a list
of device IDs. `added` holds only the other devices of the account. The option
is on `createHostedSignalProtocolClient()`, `resumeHostedSignalProtocolClient()`,
and `joinHostedSignalProtocolRelayAccount()`.

The Relay sends no notice of a change. The SDK reads the device list of the
account at these times:

- Once after the client starts.
- Each time the Relay connection moves to connected.
- On the send and repair paths.

The SDK compares the list with a stored record, so a restart does not hide a
change. On a device that just joined, the first read sets the record and does
not call the callback.

## Linking a device in one process [#linking-a-device-in-one-process]

The one-process link joins a device whose store already holds the account
identity. First put the account identity into the new device's store. Use
device transfer, or a channel that your application owns. The new device creates its
own prekeys and sessions after the import:

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

const device = getTransferDeviceInfo();

const receiving = await prepareNewDeviceTransfer(device);
await appQr.show(receiving.qrCode);

const sending = await prepareOldDeviceTransferWithBackup(backupStorage, device);
const backup = await sending.getBackup();
```

`getTransferDeviceInfo()` comes from `/device/expo`. `/device/react-native`
exports the same function. On Node, build the `TransferDeviceInfo` object
yourself, with any of `platform`, `osVersion`, and `appVersion`. The QR code and
the backup carry only the fields that you supply. Pass `{}` to send none.

Then join the new device to the Relay account:

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

const client = await linkHostedSignalProtocolRelayDevice({
  adapters: { storage: linkedStorage },
  activeDeviceStorage,
  hosted: { relayUrl },
});
```

`activeDeviceStorage` is the store of device 1. Only device 1 can link a
device. Without `hosted.adapter`, the call reads the stored Relay session of
that store. When that session is not device 1, the call throws
`HostedSignalProtocolRelayDeviceProvisioningError` with code `NOT_PRIMARY`
before it writes to a store or sends a request.

The account identity of `activeDeviceStorage` must match the identity in
`linkedStorage`. The call reads the
device-authentication private key from each store. It signs the link challenge
in the calling process. Thus that process must hold the active device's store,
private keys included.

With no `hosted.adapter`, the SDK sends the link over the authenticated Relay
transport. When the Relay refuses the active device's token, the SDK renews the
token and signs both device proofs again. The renewal needs no new identity
assertion.

To use your own transport, pass `hosted.adapter`. Its `linkDevice()` gets the
public identity, the linked device's own prekey material, and a challenge signer
for each device. It gets no private key. When the Relay refuses the link, throw
`HostedSignalProtocolRelayHttpError` with the Relay's `status`, `code`, `message`, and
`retryable`. The package root and `/client` export `HostedSignalProtocolRelayHttpError`.

The call returns the linked device's client. The link copies no sessions.
Sessions start fresh. For each group that the active device's group store
lists, the link copies the master key into the linked group store. The link
skips a listed group that has no master key. The linked group store
is `groups.store`, or the SDK group store on the linked store. The copy runs in
the calling process, so the link sends no master key to the Relay. A client with
`groups` on the linked device then fetches each copied group. It skips a group
that `groups.isGroupBlocked` reports as blocked. It also skips a group when that
hook throws. `hosted.onProgress` reports the phase `'copying'` for the
`'device-link'` operation before the copy.

The SDK group store does not list an older-format group until a read or a
write of the group. That read or write migrates the record to the current
format and lists the group. Read each group once on the active device before
the link.

By default, the link reads groups from the SDK group store on
`activeDeviceStorage`. If a client runs on the active device during the link,
pass that client's group store as `activeGroupStore`, or stop that client
before the link.

A new link gives the linked device its own registration ID. The call writes the
linked device's registration ID into the linked store before it registers.
When the linked store holds a phone number identity (PNI), that identity gets a
separate ID. A custom `SignalProtocolLocalStore` must accept an overwrite of the
identity record.

The call refuses a linked group store that lists a group that the link did not
write. It also refuses a linked store that holds a device-authentication key
but no stored registration for its current registration ID. Both refusals
throw `HostedSignalProtocolRelayDeviceLinkError` with code `DEVICE_LINK_STORE_NOT_EMPTY`
before the call writes the identity records or copies a group. Link the device
again with a new store that holds only the account identity.

A `HostedSignalProtocolRelayHttpError` with code `KEY_PROOF_INVALID`, `CONFLICT`, or
`NOT_PRIMARY` and `retryable` false starts a rollback of a link that is not
complete. The call removes the link state and the copied groups, and rethrows.
It rethrows a `NOT_PRIMARY` refusal as
`HostedSignalProtocolRelayDeviceProvisioningError`. It keeps the
identity records and the registration, so the next call sends the same
registration ID. A completed link has no rollback.

The call cannot tell whether the Relay accepted the link before the error. So
a custom adapter throws this error only for a refusal of the link request.
After the Relay accepts the link, the adapter throws a different error. The
default transport follows the same rule. After the Relay accepts the link, a
refusal of the linked device's token renewal with one of these codes becomes a
plain `Error` with that refusal as `cause`.

Every other error keeps the link state in the linked store. After an error
that keeps the link state, call again with the same stores. The call sends the
same registration and prekey material, so the Relay answers with the same
device. The default transport and a custom adapter get the same material.

If the first sync of the linked client fails, the call stops that client and
rejects. The next call resumes the link.

Version 12.0.0 removed the earlier device provisioning protocol and its
`./device/provisioning` subpath. The two-device link does not use that
protocol. See [Upgrades](https://docs.open-e2ee.dev/operate/upgrades.md).

### Security boundaries [#security-boundaries]

- Ephemeral ECDH keys derive the transfer encryption keys.
- The SDK encrypts identity material before it reaches a relay or transport.
- Transfer bundles never contain signed prekeys, one-time prekeys, ratchet sessions, sender-key state, message state, or retry outbox state.
- The two-device link sends the identity key pairs and the group master keys only inside its end-to-end encrypted envelope. The Relay carries the envelope and cannot decrypt it.
- The one-process link sends no private key or group master key to the Relay. The process that calls it must hold the active device's store.
- The SDK encrypts device names to the account identity key. Each device of the account can read a name, and the Relay cannot.
- Backend authentication must bind registration, unlink, and removal to the owning account.
- Account reset must clear the device-ID cache, platform secret storage, and protocol store as one product-level lifecycle.

The transfer QR code authenticates the channel only to the extent that your
application protects what the user scans or shares. A screenshot in a group
chat exposes that code.

**Figure:** Device transfer moves the account identity to a linked device. Message history stays on the primary device. The encrypted identity bundle crosses the boundary and exposes metadata. Sessions and message history stay on the primary device.

> **Failure mode — Device linking does not restore old messages**
>
> Existing devices encrypted past messages to the keys that they held at the time. A
> tablet linked in March keeps the account identity but starts fresh sessions.
> Its prekeys and sessions did not exist when devices sealed the January messages.
> No API on this page restores the session keys or message history.
>
> This limit creates a support ticket, not an exception. The user sees an empty thread
> on a device that they consider "their account". Meta encountered the same limit while it made
> one-to-one Messenger chats end-to-end encrypted by default. Jon Millican of Meta gave the
> reason on the
> [Security Cryptography Whatever](https://securitycryptographywhatever.com/2023/12/28/e2ee-fb-messenger/)
> podcast on 2023-12-28:
>
> > "historically, Messenger has always allowed you to log in anywhere and just access
> > everything. … But being able to guarantee that someone can do that wherever their
> > Facebook account is available essentially means that Facebook has to have access to
> > that message."
>
> If you want history on new devices, you need an encrypted backup your application
> builds and the user holds a key to. That product policy creates costs for both
> choices. See [Recovery, backup, and migration](https://docs.open-e2ee.dev/build/recovery-backup-migration.md).

## First sync to a new device [#first-sync-to-a-new-device]

A new device does not have the profile key, the settings, the contacts, or the
block list of the account. Device 1 can send them to the new device in one
end-to-end encrypted bundle. This bundle is the first sync. It carries no
messages and no sessions.

The SDK sends no first sync when device 1 approves a link. Your application
calls `sendHostedSignalProtocolRelayFirstSync()` on device 1 after the new
device joins. For example, call it when
`approveHostedSignalProtocolRelayDeviceLink()` resolves with the device ID, or
when `hosted.onOwnDevicesChanged` lists the device in `added`.

### Send the bundle [#send-the-bundle]

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

// `signal` is the client of device 1.
const { deviceId } = await approveHostedSignalProtocolRelayDeviceLink(signal, linkCode);

const { bundleId } = await sendHostedSignalProtocolRelayFirstSync(signal, deviceId, {
  profileKey: ownProfileKey, // 32 bytes
  settings: { readReceipts: true, typingIndicators: false },
  contacts, // your contact list: { userId, profileKey?, applicationData? }[]
  blocked, // your block list: { recipientId, blockedAt }[]
});
```

The bundle has at least one of these parts:

| Part | Type | Rule |
|---|---|---|
| `profileKey` | `Uint8Array` | The profile key of the account. 32 bytes. |
| `settings` | `{ readReceipts: boolean; typingIndicators: boolean }` | Both members are required. |
| `contacts` | `{ userId: string; profileKey?: Uint8Array; applicationData?: Uint8Array }[]` | Each `userId` is not empty and is unique in the bundle. Each `profileKey` is 32 bytes. The SDK does not read `applicationData`. |
| `blocked` | `{ recipientId: string; blockedAt: number }[]` | Each `recipientId` is not empty and is unique in the bundle. `blockedAt` is milliseconds since the Unix epoch, a non-negative safe integer. |
| `applicationData` | `Uint8Array` | The SDK does not read it. |

Each part is a full snapshot of its kind. A part that is present replaces that
kind on the new device. An empty array clears that kind. A part that is absent
keeps that kind unchanged. The SDK reads no part from its own stores, so your
application supplies each part.

The call resolves with the `bundleId` of the bundle. The call is not
idempotent. Each call sends a new bundle with a new `bundleId`. To stop the
call, pass an `AbortSignal` as `options.signal`. A signal that fires after the
Relay accepts the bundle does not stop the delivery.

### Size [#size]

Serialized content of 140,000 bytes or less always fits. The content adapter
serializes the bundle before the encryption. The default content adapter writes
JSON with each byte field in base64, so the serialized content is larger than
the byte fields of the bundle.

The call checks the size two times, and each check gives a `RangeError`. Before
the encryption, it refuses serialized content above 196,608 bytes. After the
encryption and before the post, it checks the encoded delivery of the encrypted
bundle. The Relay accepts a delivery of 262,144 bytes or less. Content of
196,608 bytes or less can still fail the second check.

Before the second check, the call reads the own device list of the account.
That read can fetch prekey bundles to open sessions with own devices.

### Billing [#billing]

The Relay counts each accepted call as one message to one device. That message
uses one [delivery unit](https://docs.open-e2ee.dev/signal-relay/delivery-and-push.md#delivery-units). A
second call is a second message.

### Refusals [#refusals]

`sendHostedSignalProtocolRelayFirstSync()` refuses these cases:

| Case | Error |
|---|---|
| The client is not device 1 | `HostedSignalProtocolRelayDeviceProvisioningError` with code `NOT_PRIMARY` |
| The own device list of the account does not hold `deviceId`, or the Relay accepted no copy for it | `HostedSignalProtocolRelayDeviceProvisioningError` with code `DEVICE_NOT_FOUND` |
| `options.signal` fires, or the client stops, before the Relay accepts the bundle | `HostedSignalProtocolRelayDeviceProvisioningError` with code `CANCELLED` |
| `deviceId` is not a safe integer of 2 or more | `RangeError` |
| A bundle value has the wrong type | `TypeError` |
| The bundle has no part, or a bundle value is out of range | `RangeError` |
| The serialized content is above 196,608 bytes, or the encoded delivery is above 262,144 bytes | `RangeError`, before the post |
| The content adapter has no `serializeFirstSync` | `TypeError` |
| The client is not connected to the Relay | `Error` |

The call checks the types before the ranges. A bundle with both faults gives the
`TypeError`.

The call sends only to a device in the own device list of the account. The new
device refuses sync content from another account, so a first sync from another
account never reaches `onFirstSync`.

### Receive the bundle [#receive-the-bundle]

Set `hosted.onFirstSync` on the new device. Pass the same callback to
`joinHostedSignalProtocolRelayAccount()`, `createHostedSignalProtocolClient()`,
and `resumeHostedSignalProtocolClient()`. The client binds the callback before
its first receive, so a bundle that waits in the mailbox of the device reaches
it. `linkHostedSignalProtocolRelayDevice()` has no `onFirstSync` option.

```ts
import {
  createHostedSignalProtocolClient,
  type HostedSignalProtocolRelayFirstSyncCallback,
} from '@open-e2ee/signal-protocol-sdk';

const onFirstSync: HostedSignalProtocolRelayFirstSyncCallback = async (bundle) => {
  // Replace each part in full, so a second call with the same bundle
  // gives the same state.
  await appState.transaction(async (tx) => {
    if (bundle.profileKey) await tx.setOwnProfileKey(bundle.profileKey);
    if (bundle.settings) await tx.setSettings(bundle.settings);
    if (bundle.contacts) await tx.replaceContacts(bundle.contacts);
    if (bundle.blocked) await tx.replaceBlockList(bundle.blocked);
    if (bundle.applicationData) await tx.setApplicationData(bundle.applicationData);
  });
};

const signal = await createHostedSignalProtocolClient({
  adapters,
  hosted: {
    getIdentityAssertion,
    relayUrl: process.env.OPEN_E2EE_SIGNAL_RELAY_URL!,
    onFirstSync,
  },
  hooks: {
    onMessageDecrypted: async (envelope) => {
      // Your message handler.
    },
  },
});
```

Set `hooks.onMessageDecrypted` too. The client starts the Relay subscription
only when you set that hook.

The callback gets the bundle and `{ bundleId, senderDeviceId, createdAt }`.
`createdAt` is a `Date` from the clock of device 1.

The device applies each bundle once. It writes an apply-once record after the
callback resolves. A later delivery of the same `bundleId` gives no call.

When the callback throws or rejects, the device writes no record. The durable
local receive queue then gives the bundle to the callback again, also after a
restart. The Relay does not deliver the bundle again. A crash after the
callback and before the record write also gives one more call with the same
`bundleId`. Thus make the callback safe to run again for the same `bundleId`:
apply each part as a full replace.

If you set `hosted.profileKeys`, store the profile key of the bundle where
`getOwnProfileKey()` reads it. Each device of an account must return the same
[profile key](https://docs.open-e2ee.dev/signal-relay/profile-keys.md).

The device does not apply a first sync in these cases. It logs a warning with
the behavior in the table.

| Case | Behavior |
|---|---|
| The sender is an own device other than device 1 | `FIRST_SYNC_NOT_FROM_PRIMARY` |
| The bundle fails a check | `FIRST_SYNC_MALFORMED` |
| The bundle is older than the newest bundle that the device applied | `FIRST_SYNC_STALE` |
| The client has no `onFirstSync` | `FIRST_SYNC_UNHANDLED` |

Without `onFirstSync`, the device consumes the bundle, and the bundle does not
come again. Send a new first sync from device 1. A first sync never reaches
`onMessageDecrypted`. Upgrade every device of one account in one release. An own
device on an older SDK gives the raw first sync to `onMessageDecrypted`. The raw
decrypt methods return a first sync unapplied.

## Listing, renaming, and removing devices [#listing-renaming-and-removing-devices]

### Listing devices [#listing-devices]

`listHostedSignalProtocolRelayDevices(client)` returns one entry for each
device of the account:

| Field | Value |
|---|---|
| `deviceId` | The device ID, from 1 to 5. |
| `isPrimary` | `true` for device 1. |
| `isCurrent` | `true` for the device that calls. |
| `name` | The name from the join or the last rename. Absent for a device with no name, or a name that this client cannot decrypt. |
| `linkedAt` | A `Date`, the time of the link, for a device that a two-device link made. Absent for other devices. |

Each device that holds the account identity key can decrypt a device name. The
Relay gives `name` and `linkedAt` only for the account of the caller.

### Renaming a device [#renaming-a-device]

`renameHostedSignalProtocolRelayDevice(client, deviceId, name)` sets the name of
a device of the account. Device 1 can rename each device from 1 to 5. A linked
device can rename only itself.

The call encrypts the name to the account identity key. For a device ID that is
not an integer from 1 to 5, the call throws a `RangeError` and sends no request.
It does the same for a name that is not 1 to 50 UTF-16 code units. It does not
truncate a name.

| Case | Error |
|---|---|
| A linked device renames another device | `HostedSignalProtocolRelayDeviceProvisioningError` with code `NOT_PRIMARY` |
| The slot holds no device | `HostedSignalProtocolRelayDeviceProvisioningError` with code `DEVICE_NOT_FOUND` |
| The Relay does not have the rename route | `HostedSignalProtocolRelayDeviceProvisioningError` with code `SIGNAL_RELAY_UNSUPPORTED` |

### Removing a device [#removing-a-device]

`removeHostedSignalProtocolRelayDevice(client, deviceId)` removes a device from
the account:

- Device 1 can remove device 2, 3, 4, or 5.
- Each device can remove itself.
- No device can remove device 1. To replace device 1, use account recovery or
  account deletion.

For device 1, or for an ID that is not an integer, the call throws a
`RangeError` and sends no request. A linked device that removes another device
gets `HostedSignalProtocolRelayDeviceProvisioningError` with code
`NOT_PRIMARY`. A slot that holds no device gives success, because the account
is then in the requested state.

To remove a device from device 1:

1. Call `listHostedSignalProtocolRelayDevices(client)` and show the devices.
2. Let the user choose a device to remove.
3. Show a confirmation screen.
4. Call `removeHostedSignalProtocolRelayDevice(client, deviceId)`.

After the removal of another device, the call reads the device list again. When
that read succeeds, `hosted.onOwnDevicesChanged` reports the removal on the
calling device. A failed read only logs a warning.

To remove a device from the device itself:

1. Call `removeHostedSignalProtocolRelayDevice(client, ownDeviceId)` with the
   running client.
2. Stop the client.
3. Delete the device-local store.

A self-removal returns after the Relay accepts it. It does not read the device
list again.

The removed client stops with `HostedSignalProtocolRelayDeviceRevokedError`,
and its Relay connection stops with the reason `'device-revoked'`. Each later
call of that client that needs the device token throws the same error and
sends no request. A registration with the key of the removed device gets
`DEVICE_REVOKED`, so `assertionPurpose: 'reregister'` cannot bring the device
back. The other devices of the account get the device ID in `removed` of
`hosted.onOwnDevicesChanged`.

The slot of a removed device stays held until the Relay deletes the data of
that device. Then a new device can use the slot.

### Removal is a Relay revocation only [#removal-is-a-relay-revocation-only]

Removal stops the Relay from serving the device. It does not take keys off the
removed device. The removed device keeps the account identity key pair and the
group master keys that it had. The SDK does not rotate sender keys after a
removal. Removal does not delete the messages that the device already
decrypted.

### A lost or stolen device [#a-lost-or-stolen-device]

For a lost or stolen device, run an account recovery. A recovery gives the
account a new identity key pair. The keys on the lost device then do not give
access to the account.

1. Sign the user in again. Recovery needs a recent provider sign-in.
2. Open an empty device-local store on a device that the user keeps.
3. Call `createHostedSignalProtocolClient()` with `hosted.assertionPurpose` set
   to `'recover'`.
4. Link each other device of the user again with the two-device link.

A recovery has these costs:

- It revokes each device of the account, device 1 too.
- The recovered device gets device ID 1. It has no sessions and no message
  history.
- Peers must verify and accept the new identity key. See [Identity changes and
  safety numbers](https://docs.open-e2ee.dev/build/identity-change-safety-numbers.md).
- Each link token from before the recovery stops working.

### Joining again after a removal [#joining-again-after-a-removal]

A removed device keeps its store, and a join refuses that store with
`STORE_NOT_EMPTY`. To join the account again with the same store:

1. Stop each client of the store.
2. Call `resetRemovedHostedSignalProtocolRelayDevice()`.
3. Call `joinHostedSignalProtocolRelayAccount()` with the same store, and
   approve the link code on device 1.

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

await resetRemovedHostedSignalProtocolRelayDevice({
  adapters: { storage },
  hosted: { relayUrl },
  // Only when the removed client had a group store of its own.
  groups: { store: groupStore },
});
const { client } = await joinHostedSignalProtocolRelayAccount({ /* ... */ });
```

The reset renews the device token. It deletes the local account state only when
the Relay refuses the renewal with `DEVICE_REVOKED`. It then deletes the
identities, the sessions, the prekeys, the message records, the device key, the
device session, and the join marker. With `groups.store`, it also deletes each
group of that store. When the Relay still serves the device, the reset throws
`HostedSignalProtocolRelayDeviceProvisioningError` with code
`DEVICE_NOT_REMOVED` and deletes nothing. For each other failure, it throws the
error unchanged and deletes nothing.

The join registers a new device with a new registration ID and a new device
key. The device can get another device ID.

## Keeping linked devices in step [#keeping-linked-devices-in-step]

Sessions are per-device. A linked device can contradict the primary if it does not
receive a read, block, or verification decision. The SDK ships explicit sync operations
for state that has no other path between devices:

```ts
await signal.syncReadToLinkedDevices(/* … */);
await signal.syncConfigurationToLinkedDevices(/* … */);
await signal.syncVerificationStateToLinkedDevices(/* … */);
await signal.syncBlockedRecipientsToLinkedDevices({ recipients: blocked, syncedAt: Date.now() });
```

Also available: `syncViewOnceOpenToLinkedDevices`, `syncMediaAttachmentDeleteToLinkedDevices`,
`syncUsernameStateToLinkedDevices`, `syncRecipientUsernameToLinkedDevices`, and
`syncTaskNotificationAckToLinkedDevices`. Each is a message you choose to send.
None of them fire on their own.

The client sends one sync on its own. A `GroupKeySync` gives the key of each
managed group to the other devices of the account. The client sends it when it
creates or joins a group, and when it sees an own device for the first time.
Each start also sends it to each own device that the client has not recorded as
holding the key. So a linked device knows each group of the account before any
group traffic comes. Upgrade every device of one account in one release. An own
device on an older SDK gives the raw sync, with the group master key, to
`onMessageDecrypted`. See
[groups](https://docs.open-e2ee.dev/build/groups.md).

> **Tradeoff — The cost of device fanout**
>
> For one direct message, the sending device encrypts once for each recipient device.
> It also sends an encrypted transcript to each of its other devices.
> With healthy devices and valid sessions, that is `nB + (nA−1)` message copies.
> At the five-device ceiling for both users, that is nine copies.
> Retries, device reconciliation, and separate control messages add their own traffic.
>
> Capping devices lower reduces fanout. The Relay permits at most five devices per account.
> Each additional active device adds another destination.
> The application chooses when to send the explicit sync operations above.
> Ordinary direct sends automatically create sent-message transcripts for other devices.
> A send to your own account posts only a sent transcript to each other device of
> the account. It posts nothing when the account has no other device.

## Transfer to replacement hardware [#transfer-to-replacement-hardware]

If a new device replaces an old device instead of joining it, use the same
transfer path shown above. The transfer bundle carries the account identity
only. The new device creates fresh prekeys and sessions after the restore.

The application owns transport selection, peer confirmation, progress UI,
interruption recovery, and wiping old-device state after a successful replacement.
Do not erase the old device before the new device validates and durably
restores the backup. That ordering is the whole safety property, and it is yours
to enforce.

**Opacity ledger**

| Artifact | Stays on device | Sent to relay | In object store | Visible as metadata |
|---|---|---|---|---|
| Transfer QR code from `prepareNewDeviceTransfer()` | yes | no | no | no |
| Transfer backup from `getBackup()` | yes | encrypted, if you route it that way | optional | size |
| `TransferDeviceInfo` fields | yes, in the QR code and the backup | only inside the encrypted backup, if you route it that way | no | no |
| `activeDeviceStorage` private keys | yes | no | no | no |
| Group master keys | yes, the link copies them in the calling process | only inside end-to-end encrypted message content; the link sends none | no | no |
| Link code of the two-device link | yes, on the screen of the new device and in the scan on device 1 | only the channel address, never the X25519 public key | no | the channel address |
| Envelope of the two-device link | yes, on device 1 and the new device | only end-to-end encrypted | no | the account and device 1 that delivered it, and its size in steps of 4,096 bytes |
| `applicationData` of the approval | yes, on device 1 and the new device | only inside the envelope | no | no |
| First-sync bundle | yes, on device 1 and the new device | only as end-to-end encrypted message content | no | sender device, destination device, delivery class, size, and time |
| Device names | yes | only encrypted to the account identity key | no | the size of the encrypted name |
| Account public identity | yes | yes, in the link request | no | yes |
| Linked device ID | yes | yes | no | yes, the Relay assigns it from `2` through `5` and records the link time |
| Registration IDs, prekeys, sessions | yes, per device | registration ID and public prekeys | no | registration ID and prekey counts |
| Message history | yes, on devices that had it | no | no | no |

> **Not covered — Remote wipe**
>
> The SDK cannot delete data on a removed, lost, or stolen device. Removal and
> account recovery stop future access through the Relay. They do not remove the
> keys or the messages that the device already holds. Your product policy for a
> stolen phone is your own. [Device lifecycle](https://docs.open-e2ee.dev/build/device-lifecycle.md) and
> [Deletion and revocation](https://docs.open-e2ee.dev/operate/deletion-revocation.md) cover the lifecycle and
> the revocation.

The SDK is `15.0.x`. Public APIs and persisted formats follow semantic versioning.

## Next [#next]

- [Recovery, backup, and migration](https://docs.open-e2ee.dev/build/recovery-backup-migration.md): the history question this page raises and does not answer
- [Device lifecycle](https://docs.open-e2ee.dev/build/device-lifecycle.md): registration, device IDs, and unlink
- [Identity changes and safety numbers](https://docs.open-e2ee.dev/build/identity-change-safety-numbers.md): what your peers see when you add a device
- [Keys, identity, and sessions](https://docs.open-e2ee.dev/learn/keys-identity-sessions.md): why a device, not a user, is the unit
