# Device registration and lifecycle (https://docs.open-e2ee.dev/build/device-lifecycle.md)

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

A user represents a changing set of devices, not an account row. Signal Protocol
sessions address individual devices. The SDK scopes device-authentication keys,
prekeys, sessions, and envelopes to a `(userId, deviceId)` pair. Linked devices
share the account identity. Your product defines the account above that pair.

This fact controls the complete lifecycle. A reinstalled phone becomes a different
device for the same user. A linked tablet keeps the account identity.
It gets fresh device-authentication keys, prekeys, and sessions.
An account reset destroys device-local key material.
No server can restore that material.

**Figure:** One user has three devices. Each device has its own device-authentication key. Each device has separate device-authentication keys. Encrypted transfer can copy the account identity.

## Construct a client with a device identity [#construct-a-client-with-a-device-identity]

`createSignalProtocolClient` takes the device identity up front. It is not mutable afterwards.

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

const client = await createSignalProtocolClient({
  identity: { userId, deviceId: 1 },
  adapters: { storage, relay },
});
```

`deviceId` is optional and defaults to `1`, the primary device. A single-device
product can omit it. Add an explicit value before the product supports another
device.

## Let the backend allocate device IDs [#let-the-backend-allocate-device-ids]

The backend allocates linked device IDs from `2` through `5`. A client must not
select its own linked-device ID. Each user can have at most five devices: one
primary and four linked devices.

If two devices both select `deviceId: 2`, they overwrite each other's prekeys.
They also receive envelopes for the other device. The resulting session state
cannot converge. The relay contract assigns linked-device slot allocation to the
server.

On the OpenE2EE Signal Protocol Relay, a new device joins with the managed device
link. In the two-device link, the new device starts with an empty store and calls
`joinHostedSignalProtocolRelayAccount()`. Device 1 approves the link code with
`approveHostedSignalProtocolRelayDeviceLink()`. The account identity and the groups
go to the new device through the provisioning channel, and the Relay cannot read them.

In the one-process link, put the account identity into the linked device's store
first. Use device transfer or a channel that your application owns. Then call
`linkHostedSignalProtocolRelayDevice()`, which returns the linked device's client.
A client that you construct on an empty store does not join the account. Instead, it
creates an identity that the rest of the account does not recognize.

> **Failure mode — Client construction before the identity import**
>
> With an empty store, the client generates new identity material. It publishes this
> material under a device ID that the backend considers occupied. Peers then fetch
> keys that do not match the identity in their existing sessions. The receiving
> peer gets `UNTRUSTED_IDENTITY` or `IDENTITY_MISMATCH` during decryption. The
> device that caused the mismatch does not receive these errors.
>
> The OpenE2EE Signal Protocol Relay refuses this registration when the account
> already has a device. `createHostedSignalProtocolClient` then throws a
> `HostedSignalProtocolRelayHttpError` with code `DEVICE_LINK_REQUIRED`. See
> [Error handling](https://docs.open-e2ee.dev/operate/error-handling.md#when-the-account-already-has-a-device).
>
> Use `isUntrustedIdentityError()` to separate the trust case from other decryption
> failures. Construct the client only after the transfer or your own channel durably
> writes the account identity.

## The device-ID cache [#the-device-id-cache]

The device-ID module keeps the allocated ID in your `SignalProtocolLocalSecretVault`,
so it survives process restarts. Read it through that module, not the client.

```ts
import {
  clearDeviceIdCache,
  getDeviceId,
  getDeviceIdSync,
  preloadDeviceId,
} from '@open-e2ee/signal-protocol-sdk/device/device-id';

await preloadDeviceId(vault);
const deviceId = await getDeviceId(vault);
```

Pass the vault that you pass to `DeviceLifecycleManager`. With no vault, both
functions throw an `EncryptionError` with code `SECRET_VAULT_REQUIRED`.

`getDeviceIdSync()` returns the cached value or the primary-device default. Call
it after `preloadDeviceId()` resolves. Otherwise, use it only where a fallback to
device `1` is safe. A synchronous read before preload returns `1` on a linked
device. All dependent calls then address the wrong device.

> **Tradeoff — Secure storage outlives the app sandbox**
>
> Platform secure storage and application sandbox data have different uninstall,
> restore, and backup lifecycles. On iOS, a keychain entry can survive an uninstall
> that removes the encrypted store. The retained device ID then points to a slot
> whose keys no longer exist locally.
>
> If you trust retained secure-storage state, you cannot prove that it belongs to
> the new installation. If you reject it, the user must link the device again after
> each reinstall. The SDK writes an ownership sentinel to the application sandbox.
> Lifecycle code can use it to detect a mismatch. Your product must then choose to
> link or reclaim the device. Test this behavior on hardware because simulator
> uninstall behavior can differ.

## What `syncToServer()` publishes [#what-synctoserver-publishes]

```ts
await client.syncToServer();
```

This call publishes the device's public identity material and prekeys. It also
replenishes low one-time-prekey inventory. After the call, peers can fetch a bundle
and send envelopes to the device. Before the call, the relay cannot fan messages
out to it.

Afterward, `client.syncStatus` reports `'synced' | 'failed' | 'none'`. The device
sends public key material and routing metadata. The relay never needs message
plaintext or device private keys. The device generates private halves and keeps
them in the local store. See [Relay and prekeys](https://docs.open-e2ee.dev/build/relay-and-prekeys.md) for
replenishment values and the rotation schedule.

## `DeviceLifecycleManager` [#devicelifecyclemanager]

`DeviceLifecycleManager` provides a framework-neutral registration workflow. It
persists the device ID, compares it with the backend registry, detects stale or
orphaned devices, and clears local state.

```ts
import {
  DeviceLifecycleManager,
  type DeviceLifecycleDeps,
} from '@open-e2ee/signal-protocol-sdk/device/lifecycle';

const lifecycle = new DeviceLifecycleManager(userId, deps);
await lifecycle.initialize();
```

`DeviceLifecycleDeps` injects a `SignalProtocolLocalSecretVault` and a backend
client with `query` and `mutation`. The constructor throws `SECRET_VAULT_REQUIRED`
when the vault is absent. It also injects your generated function references, key-storage
operations, and logger. The manager forwards those references. It does not select
a backend. It exposes `initialize()`, `registerDevice()`, `fetchDevices()`,
`loadStoredDeviceId()`, `checkDeviceStale()`, `makePrimary()`, and
`clearLocalDevice()`.

The application remains responsible for authenticated backend functions and for placing initialization in its own startup lifecycle.

## One lifecycle, four operations [#one-lifecycle-four-operations]

Registration, linking, unlink, and account reset are four points on one product-level lifecycle, not four independent features.

**Registration** claims a device slot and publishes key material.

**Linking** adds a linked device. In the two-device link, the new device calls
`joinHostedSignalProtocolRelayAccount()` with an empty store, and device 1 calls
`approveHostedSignalProtocolRelayDeviceLink()`. Device 1 sends the account identity and
the groups to the new device in an encrypted envelope. The new device gets its own
device ID, registration ID, prekeys, and device key.

The one-process link, `linkHostedSignalProtocolRelayDevice()`, joins a store that
already holds the account identity to the OpenE2EE Signal Protocol Relay account. In the calling process,
it copies the master key of each group that the active device's group store lists.
It copies no sessions and no message history. It sends no private key or group
master key to the Relay. A new link gives the linked device its own
registration ID. Device transfer, or a channel that your application owns, puts
the account identity into the new store. Ephemeral ECDH keys derive the
transfer encryption keys. The SDK encrypts identity material before transport.

**Unlink** removes a slot and must remain consistent across active identity types.

**Account reset must clear the device-ID cache, platform secret storage, and
protocol store as one product-level lifecycle.**

Do not clear only the protocol store with `client.clearAllData()`. If the cached
device ID and vault wrapping key remain, the device reports a linked ID. It also
holds a key for a database that no longer exists. The device then generates a new
identity under an occupied slot. Clear all three resources, or clear none.

The device encrypts its name for backend storage. The relay holds
`encryptedDeviceName` bytes. The device decrypts the plaintext label for its local
device list.

## Authentication is yours [#authentication-is-yours]

The SDK does not provide login, session tokens, or an account model.

**Backend
authentication must bind registration, unlink, and removal to the
owning account.** Do not accept a client-supplied `userId` for a relay write. That
design lets any authenticated caller register another user's device.

The SDK interface guide defines this responsibility boundary:

> "the client owns protocol coordination; the host application owns persistence,
> authentication, authorization, and product policy."

> **Not covered — The link and transfer flows themselves**
>
> The managed device link adds a device to the account, and device 1 stays on the
> account. Encrypted transfer moves the account identity to replacement hardware. These
> are separate operations. See [Multi-device](https://docs.open-e2ee.dev/build/multi-device.md)
> for linking and [Recovery, backup, and migration](https://docs.open-e2ee.dev/build/recovery-backup-migration.md)
> for hardware replacement.

**Opacity ledger**

| Artifact | Stays on device | Sent to relay | In object store | Visible as metadata |
|---|---|---|---|---|
| `identityKeyPair` private half | yes | no | no | no |
| `identityKeyPair` public half | yes | yes | no | yes |
| `compositeIdentity` (canonical `CompositeIdentityV1`) | yes | yes | no | yes |
| `deviceId` (cached under `DEVICE_ID_KEY`) | yes | yes | no | yes |
| `registrationId` | yes | yes | no | yes |
| `encryptedDeviceName` | yes | yes | no | ciphertext length |
| Plaintext device name | yes | no | no | no |
| `SessionRecord` (`version: 4`) | yes | no | no | no |
| `"signal-store-wrapping-key"` vault entry | yes | no | no | no |

## Next [#next]

- [Local encrypted storage](https://docs.open-e2ee.dev/build/local-storage.md): the store and vault this lifecycle clears
- [Relay and prekeys](https://docs.open-e2ee.dev/build/relay-and-prekeys.md): what `syncToServer()` publishes and how often
- [Multi-device](https://docs.open-e2ee.dev/build/multi-device.md): link a device end to end
- [Identity change and safety numbers](https://docs.open-e2ee.dev/build/identity-change-safety-numbers.md): show a user when a device identity changes
