# Groups (https://docs.open-e2ee.dev/build/groups.md)

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

The SDK exposes two group APIs. They are not alternatives or versions of each
other. One moves messages. The other moves group state. Most group products need
both, so choose the correct API for each task.

| | Sender-key messaging | Encrypted group state |
|---|---|---|
| Answers | "How do I encrypt one message for 40 people?" | "Who is in this group, what is it called, who may edit it?" |
| Surface | `createGroupSenderKey`, `encryptGroupMessage`, `processIncomingEnvelope`, `rotateGroupSenderKey` | `createGroup`, `addGroupMember`, `syncGroup`, `GroupManager` |
| Backend stores | envelopes | opaque encrypted group state, sequenced by version |
| You can skip it if | your groups are small enough that pairwise fanout is fine | your app already has a membership system it trusts |

## A. Sender-key messaging [#a-sender-key-messaging]

Pairwise fanout encrypts the message body separately for every recipient device.
For a group of 40 users at two devices each, one message requires roughly 80
encryptions and 80 distinct ciphertexts. The sender's device repeats that linear
work for every message.

Sender keys break the coupling. Create one symmetric chain for the group. Distribute
it once to each member over the existing pairwise sessions. The sender then encrypts
each message once:

```ts
await signal.createGroupSenderKey(groupId);
await signal.distributeGroupSenderKey(groupId, memberUserIds);

const encrypted = await signal.encryptGroupMessage(groupId, 'ship it');

for (const member of groupMembers) {
  await sendToMember(member, encrypted); // same bytes to everyone
}
```

`distributeGroupSenderKey(groupId, memberUserIds)` is a convenience over
`distributeSenderKeyToUser(groupId, recipientUserId)`. Both use pairwise sessions.
The sender cannot encrypt the distribution message with the key that the message
delivers. On the receiving side, give the framed message to
`processIncomingEnvelope()` as a `sender_key` envelope:

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

await signal.processGroupSenderKeyDistribution(
  groupId,
  senderId,
  senderDeviceId,
  distributionMessage,
);

const outcome = await signal.processIncomingEnvelope({
  id: delivered.id,
  senderUserId: senderId,
  senderDeviceId,
  ciphertext: bytesToBase64(framedMessage),
  timestamp: delivered.timestamp,
  messageType: 'sender_key',
});

if (outcome.kind === 'processed') {
  await saveMessage(outcome.plaintext);
  await signal.completeReceive(outcome.messageId);
}
```

The envelope names no group. The client resolves the group from the frame.
`processIncomingEnvelope()` keeps the content until the application calls
`completeReceive()`. A refusal gives a `denied` outcome. See
[receive outcomes](https://docs.open-e2ee.dev/reference/api.md#receive-outcomes).

The output of `encryptGroupMessage()` carries no group context, unless its
plaintext holds one. A receiver with a `groups` config denies that output for a
managed group with the reason `legacy-no-context`, or `blocked` when the group
is blocked. A receiver with no `groups` config refuses it with a
`GroupReceiveRefusedError` of reason `configuration`. Send the content of a
managed group with `send()`. A caller that delivers the bytes of
`encryptGroupMessage()` itself decrypts them with `decryptEnvelope()`.

Distribution costs `O(n)` per membership change. Message encryption cost stays
constant as group size changes.

`getGroupSenderKeyDistribution(...)` returns the distribution payload for custom routing.
`hasGroupSenderKey(groupId)` reports whether a local chain exists.
`getGroupSenderKeyStats(...)` reports its state, and `deleteGroupSenderKey(groupId)` removes it.

Delivery does not change: the relay still carries one envelope per recipient
device. Sender keys reduce encryption work and ciphertext distinctness,
not envelope count.

### Rotation is the security property [#rotation-is-the-security-property]

A sender key is a symmetric chain. Every holder can read all messages that use it.
After the group removes someone, their chain still grants access to future messages.

```ts
const result = await signal.handleGroupMembershipChange(groupId, 'member_removed');

if (result.rotated) {
  for (const member of remainingMembers) {
    await sendToMember(member, JSON.stringify(result.distributionMessage));
  }
}
```

`handleGroupMembershipChange(groupId, change)` takes `'member_added'`,
`'member_removed'`, or `'metadata_changed'`. It encodes the rule that removal and
metadata changes rotate the key. Addition does not rotate it because the new member
only needs the current key. The method returns `{ rotated, distributionMessage }`.
`rotateGroupSenderKey(groupId)` is the direct form.

> **Failure mode — A removal that does not rotate is not a removal**
>
> If the chain is not rotated, the removed member continues to decrypt every
> subsequent group message using the key they already have. The UI will say they
> left. The cryptography will disagree.
>
> This failure produces no error or exception. The sending path does not detect it.
> The removed device can still open ciphertext if it can still get envelopes. Wire
> rotation into the same code path that writes the membership change, not into a
> later listener that might not run.

> **Tradeoff — Group size against rotation cost**
>
> Rotation re-runs distribution: one pairwise-encrypted distribution message per
> remaining member device. In a 200-person group that is roughly 200 to 400
> encryptions and envelopes, on the rotating device, per removal.
>
> A large group with frequent changes spends its budget on key rotation instead of
> messages. On a phone, users notice this battery and time cost. The SDK leaves two
> product choices to you. Cap group size to bound rotation, or reduce the events that
> rotate keys. No third option preserves both large groups and immediate forward secrecy.
> Any batch or delay creates a window where a removed member can still read.

## B. Encrypted group state [#b-encrypted-group-state]

Sender keys say nothing about group membership. The group state API provides the
encrypted state model. It covers the title, description, membership list, access control, and
invite links. The backend stores and sequences this ciphertext without reading it.

> The application backend stores opaque encrypted group state and sequences
> changes, while each member device owns group secrets, decrypted state,
> authorization credentials, and sender-key rotation.

> The server must enforce authenticated access and version sequencing without
> receiving plaintext group attributes or group master keys.

Both halves of that second sentence define requirements. The server must still
authenticate each request because anyone can request state. It must also sequence
changes. Two devices that edit a group concurrently need a monotonic version for
reconciliation. The server completes both tasks on ciphertext.

The client needs a `groups` config block with the account's 32-byte `profileKey`.
With `createSignalProtocolClient`, the block also holds the pinned `trustRoot`.
The `groupServer` capability of the relay supplies the group server and the
credential issuers, and a custom deployment can override them in the same block.
With `createHostedSignalProtocolClient`, the OpenE2EE Signal Protocol Relay supplies the group keys in a
signed response.

A managed group ID is the group identifier in lowercase hex. Any other ID names
an ad hoc group. A client with a `groups` config denies all managed group
content that has no group context, with the reason `legacy-no-context`. It
denies such content also when it has state of the group. An earlier check can
deny the content first, such as `blocked` for a blocked group. Every sender must
run SDK 12.0.0 or later. A client with no `groups` config refuses such content
with a `GroupReceiveRefusedError` of reason `configuration`.

A new send to a managed group needs the group master key in the group store.
Without it, the send throws `EncryptionError` with the code
`GROUP_MASTER_KEY_MISSING`, and stores and posts nothing. Store the group
master key through the link or sync path, then send again. A send to an ad hoc
group does not need a master key.

From the client:

```ts
const { groupId, masterKey } = await signal.createGroup(
  creatorAci,
  creatorProfileKey,
  members,
  'Release engineering',
  { description: 'ship coordination' },
);

await signal.addGroupMember(groupId, editorAci, { serviceIdBytes: newMemberServiceId });
await signal.removeGroupMember(groupId, editorAci, targetAci);

const state = await signal.syncGroup(groupId);
```

`members` and the third argument of `addGroupMember()` take a `GroupMemberInput`.
A target with a verified profile-key credential is
`{ aciBytes, profileKey, profileKeyCredential }` and becomes a member immediately.
A target with only a ServiceId is `{ serviceIdBytes }` and becomes an invited
member. The invited member accepts with `acceptGroupMemberInvitation(groupId)`
and presents their own profile key.

Also on the client: `getGroupState(groupId)`, `leaveGroup(groupId, userAci)`,
`declineGroupMemberInvitation(groupId)`, `updateGroupTitle(...)`,
`updateGroupDescription(...)`, `updateGroupAccessControl(...)`,
`createGroupInviteLink(groupId, editorAci)`, and
`joinGroupViaInviteLink(url, userAci, userProfileKey)`.

The client gives the key of each managed group to the other devices of its own
account. When it creates a group, accepts a member invitation, or joins a group
through an invite link, it sends a `GroupKeySync` to each other own device. The
sync holds the group master key and the revision. When the client sees an own
device for the first time, it sends the key of each group to that device only. The client
marks an own device for a group when the Relay accepts its copy, or when that
device sent the key to this device. Each start sends the key of each group to
each own device that has no mark for the group. So the first start after an
upgrade from 13.x sends one `GroupKeySync` for each group and own device.

The client sends no key for a group while its record is unverified or while it
has no stored state. It also sends no key while the stored state does not list
the account as a member. A receiving device accepts a `GroupKeySync` only from its own account.
For a group with no record, it writes the record, stores the master key, and
schedules a fetch of the group. So an own device knows the group before any
group traffic comes. A repeated `GroupKeySync` applies once. A `GroupKeySync`
travels inside end-to-end encrypted message content.

`processIncomingEnvelope()`, the relay subscription, and the receive queue
consume a `GroupKeySync`. The application never gets it from them.
`processIncomingEnvelope()` returns the `null-message` outcome for it.
`decryptEnvelope()` and the raw decrypt methods `receive()`, `decryptMessage()`,
and `decryptMessages()` return the sync unapplied. That result holds the group
master key. Upgrade every own device of one account in one release. An
own device on an older SDK gives the raw sync, with the master key, to
`onMessageDecrypted`.

`getGroupInitStatus(groupId)` returns the `GroupInitStatus` of a group on this
device. It returns null when the device has no record of the group. Without the
`groups` config block, it throws an `EncryptionError` with code
`INITIALIZATION_FAILED`.

| Status | Meaning |
|---|---|
| `'ready'` | The device holds the group master key and the group state at the newest revision that it knows |
| `'stale'` | The device holds the group master key and the group state, but a sender named a newer revision. The client fetches the newer state |
| `'pending'` | The device holds the group master key and has no group state yet. The client fetches the state |
| `'no-key'` | The device knows the group but holds no group master key. The client cannot fetch the group until the device gets that key, from group traffic or from an own device |
| `'denied'` | The group server refused the newest revision that the device knows, for example because this account is not a member. A sender that names a newer revision makes the client try again |

The `onGroupInitStatus(groupId, status)` hook runs when a client write changes
the init status of a group. It gets the status after the write. The hook
observes each client write of the group master key, the group state, or the
receive data of the group. The receive data includes the newest revision that
the device knows and the last refusal of the group server.

The hook has these limits:

- The hook does not run when a write keeps the same status, or when
  `getGroupInitStatus()` returns null after the write.
- When two writes to one group run at the same time, the hook can miss the
  status between them.
- The hook calls run in order, and no write waits for a hook call. So the hook
  can call a client method for the same group.
- When the client cannot read the status before or after a write, the hook
  does not run for that write. The client logs a
  `GROUP_INIT_STATUS_READ_FAILED` warning.
- The hook does not run for the statuses that the store holds when the client
  starts. It also does not run for a write that your application makes
  directly to a group store. That store is `groups.store`, or the SDK group
  store on the client local store.
  Read each status with `getGroupInitStatus()` when the application starts.

```ts
signal.registerHook('onGroupInitStatus', (groupId, status) => {
  groupList.setInitStatus(groupId, status);
});
```

If your application manages group state outside the messaging client, such as in a
workspace service or existing org chart, use the standalone manager. Give it
your own server and store implementations:

```ts
import {
  GroupManager,
  createGroupId,
  type GroupServer,
  type GroupStateStore,
} from '@open-e2ee/signal-protocol-sdk/groups';

const groups = new GroupManager({
  store: appGroupStore as GroupStateStore,
  server: appGroupServer as GroupServer,
  issueCredential: () => appGroupCredentials.issue(),
  credentialPublicKey,
  issueProfileKeyCredential: (request) => appGroupCredentials.issueProfileKey(request),
  profileKeyCredentialPublicKey,
  aci: localAccountServiceId,
  profileKey,
});

const state = await groups.syncGroup(createGroupId(rawGroupId));
```

The `/zk/groups` subpath exports the zero-knowledge-proof primitives:
`deriveGroupSecretParams`, `getGroupPublicParams`, and `computeProfileKeyVersion`.
These primitives let a server verify group access without learning the requester's
member identity. You will not usually call them directly. Use them when your backend
must share the same parameters.

**Opacity ledger**

| Artifact | Stays on device | Sent to relay | In object store | Visible as metadata |
|---|---|---|---|---|
| Group sender key chain | yes | no | no | no |
| `SenderKeyDistributionMessage` | yes | encrypted pairwise | no | that a distribution envelope moved |
| `encryptGroupMessage()` output | yes | yes | no | size, recipient device count |
| `GroupKeySync` to own devices | yes | encrypted pairwise | no | that an envelope moved between devices of one account |
| `masterKey` from `createGroup()` | yes | only inside an encrypted `GroupKeySync` to own devices | no | no |
| `groupId` / `createGroupId()` value | yes | yes | no | yes — the server routes on it |
| Group title and description | yes, decrypted | encrypted | no | that they changed, and the version number |
| Membership list | yes, decrypted | encrypted | no | member count and change frequency |
| `creatorProfileKey` / member profile keys | yes | encrypted in group state | no | no |
| Group state version | yes | yes | no | yes — the server sequences on it |
| Invite link from `createGroupInviteLink()` | yes | yes | no | that a link exists |

The metadata column shows a relay limit. A relay that cannot read a group's name can
still observe roughly forty devices exchange two hundred envelopes on Tuesday
afternoon. It can also observe three state-version increments. See
[Limits and metadata](https://docs.open-e2ee.dev/learn/limits-and-metadata.md).

> **Not covered — Group membership as authorization**
>
> Your application authorizes joins, member removal, and invite links against your
> account system. The SDK enforces the cryptographic effects of a membership change.
> It does not decide whether policy permits the change.
>
> > "The client owns protocol coordination; the host application owns persistence,
> > authentication, authorization, and product policy."

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

## Next [#next]

- [Identity changes and safety numbers](https://docs.open-e2ee.dev/build/identity-change-safety-numbers.md): what happens when a group member's identity key changes
- [Multi-device](https://docs.open-e2ee.dev/build/multi-device.md): why group fanout counts devices, not users
- [Key rotation](https://docs.open-e2ee.dev/operate/key-rotation.md): rotation as an operational schedule
- [Limits and metadata](https://docs.open-e2ee.dev/learn/limits-and-metadata.md): what a relay still learns about a group
