# Keys, identity, and sessions (https://docs.open-e2ee.dev/learn/keys-identity-sessions.md)

"The key" is not one thing. An application built on this SDK holds four kinds of key material with four lifetimes, four scopes, and four different failure consequences. Conflating them is a common design mistake.

## The composite identity [#the-composite-identity]

The JavaScript profile uses one composite identity per `(userId, identityType)`. Every linked device holds it unchanged.

```text
CompositeIdentityV1 =
    version
 || X25519 algorithm tag
 || X25519 public key
 || Ed25519 algorithm tag
 || Ed25519 public key
```

The complete canonical tuple, not either component by itself, is the identity trust object. The SDK locally derives a domain-separated commitment for comparison and transcript binding.

This distinction matters. An X25519 key alone is not the identity. Neither is an Ed25519 key alone. The concatenation, with its version byte and algorithm tags, is the identity. The SDK evaluates every trust decision against the whole tuple. This rule stops an adversary from swapping only the signing half or agreement half and inheriting an existing trust relationship.

The `/keys` subpath exports `createCompositeIdentityV1`, `generateIdentityKeyPair`, and the `CompositeIdentityV1` type. On a live client, `client.getIdentityPublicKey()` returns the local public identity material.

### First contact [#first-contact]

First contact establishes an explicitly unverified trust-on-first-use record. It does not claim authenticated identity. Trust starts at `UNVERIFIED_TOFU` and stays there until a safety number or application trust mechanism authenticates it. `generateCompositeSafetyNumber(...)` from `/safety` produces `numeric`, `emojis`, and `scannable` forms. The client's `verify(remoteUserId)` and `confirmSafetyNumber(confirmation)` carry the decision into protocol state.

### Existing trust [#existing-trust]

After the application pins a composite identity:

- replacing either component fails against the trusted commitment.
- the SDK rejects cached or supplied commitment mismatches before mutation.
- rotation requires an explicit trust decision.
- rollback to an older tuple is detectable.

The SDK promotes only the exact current tuple to `VERIFIED`. A verification that covered last month's tuple does not carry forward through a rotation, and it should not. The [Threat model](https://docs.open-e2ee.dev/learn/threat-model.md) explains what a hostile relay can and cannot do against this rule.

## TOFU is not a one-time decision [#tofu-is-not-a-one-time-decision]

Trust-on-first-use is usually described as a single moment: you meet a peer, you accept their key, done. That was never accurate for multi-device systems, and Keybase reframed it usefully as **TADA: Trust After Device Additions**. Every device a user adds re-runs the decision. Every phone upgrade re-runs it, for every contact, forever.

So identity change is routine and high-frequency, not an incident. Treat every change as a red alarm and users learn to click through it. Hide the change and you remove the only signal that distinguishes a phone upgrade from an interception. The SDK creates comparison data. The application owns QR rendering, scanning, the verification experience, and storage of the trust decision. [Identity change and safety numbers](https://docs.open-e2ee.dev/build/identity-change-safety-numbers.md) is where that work lives.

> **Failure mode — Verification ceremonies fail with real users**
>
> One study found that 21 of 28 computer science students could not verify a public key. Another study explained the risks first. Only 13% of its participants completed the ceremony. Assume that most users will not compare a safety number. Give users who compare one an unambiguous result.

## The four lifetimes [#the-four-lifetimes]

**Identity keys** are long-lived and per user. Every linked device of a user holds the composite tuple above unchanged. The application moves it to a new device by device transfer or by a channel that it owns. The SDK selects Sesame's per-user identity-key model. Losing the private half loses the identity. Rotating it means every peer sees a change and must make a trust decision.

**Registration IDs, prekeys, and signed prekeys** are device-specific. The relay publishes this material so a stranger can contact you while you are offline. `keyRefreshIntervalMs` defaults to 172800000 (2 days) and `maxPreKeyAgeMs` to 1209600000 (14 days). One-time prekeys upload in batches of 100, and the client-config `preKeyLowThreshold` defaults to 50. `syncToServer()` replenishes. `checkPreKeyStatus()` reports. `rotatePreKeys()` rotates every due key in one publication.

**Session state** is per remote address and holds the Double Ratchet. More below.

**Message keys** are per message and deleted after use. That deletion is the forward secrecy property: a device compromised today does not yield yesterday's messages, because yesterday's keys are gone. Bounded state exists for out-of-order delivery, `maxSkip` 25000, `maxMessageKeysStored` 2000 for each receiver chain, `keyExpirationMs` 604800000 (7 days), and those bounds make `TOO_MANY_SKIPPED_MESSAGES` a real error code rather than an unbounded memory sink.

> **Failure mode — Prekey exhaustion is measured, not hypothetical**
>
> A 2025 measurement study of WhatsApp found 13% of companion devices had no one-time prekey available at scan time. When the pool runs dry, session establishment silently falls back to material with weaker forward secrecy and no error surfaces. Watch `checkPreKeyStatus()`. See [Relay and prekeys](https://docs.open-e2ee.dev/build/relay-and-prekeys.md).

## What a session actually is [#what-a-session-actually-is]

A session is not a connection or login. It is persistent Double Ratchet state for one `(local device, remote address)` pair. It contains the root key, chain keys, ratchet key pairs, counters, and a bounded set of skipped message keys.

What makes sessions difficult is that **decryption mutates state**. Advancing the ratchet consumes a chain key and derives the next. This is not a cache you can rebuild. If a successful decrypt does not persist the session record, in-memory and on-disk state diverge. The next message then uses the wrong chain.

Session records must therefore persist atomically. A partial write or a concurrent decrypt on the same address corrupts state irrecoverably. Records use `version: 4`. The SDK rejects and resets older formats instead of migrating them. This choice prevents the ratchet from using state written under different rules.

> **Failure mode — Corruption surfaces as a MAC failure, and it can be silent**
>
> There is no `BadMacError` class in this SDK. The classic `libsignal` "Bad MAC" condition surfaces as `DECRYPTION_FAILED`. An unusable record can also produce `SESSION_CORRUPTED`.
>
> In February 2026, 479 Bad MAC exceptions from libsignal stopped WhatsApp inbound delivery. The report states that "the gateway believes it is connected and listening, making this a silent failure." A related project logged over 168,000 such errors in two hours across more than 400 sessions. These errors exhausted the Node heap and continued after session file deletion. Alert on the decrypt-failure rate, not process liveness. [Error handling](https://docs.open-e2ee.dev/operate/error-handling.md) covers recovery.

> **Tradeoff — Reset on conflict vs. preserve history**
>
> `deleteSession(remoteAddress)` and `archiveSession(remoteAddress)` recover a wedged conversation. `forceCompleteKeyReset()` recovers a wedged identity. Both discard anything still in flight under the old state. The peer sees a reset as a change that requires new acceptance. Not resetting keeps history intact and leaves the conversation broken. The SDK gives these failures distinct codes: a wedged record raises `SESSION_CORRUPTED`, and an identity candidate that differs from the pinned tuple raises `UNTRUSTED_IDENTITY`. Your application makes the call.

The SDK is 15.0.x. Public APIs and persisted formats follow semantic versioning. Session records can change in a future major release.

## Next [#next]

- [Local-first and offline-first](https://docs.open-e2ee.dev/learn/local-first.md): why this state cannot live anywhere but the device.
- [Identity change and safety numbers](https://docs.open-e2ee.dev/build/identity-change-safety-numbers.md): the ceremony, in code.
- [Local storage](https://docs.open-e2ee.dev/build/local-storage.md): atomic persistence and adapter selection.
- [Key rotation](https://docs.open-e2ee.dev/operate/key-rotation.md): schedules, thresholds, and what to alert on.
