@kumiai/mls 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +21 -9
  2. package/lib/anchor.d.ts +87 -0
  3. package/lib/anchor.js +124 -0
  4. package/lib/credential.d.ts +3 -12
  5. package/lib/credential.js +0 -13
  6. package/lib/envelope-fold.d.ts +35 -0
  7. package/lib/envelope-fold.js +86 -0
  8. package/lib/envelope.d.ts +53 -0
  9. package/lib/envelope.js +87 -0
  10. package/lib/fold.d.ts +68 -0
  11. package/lib/fold.js +53 -0
  12. package/lib/group-commit.d.ts +100 -0
  13. package/lib/group-commit.js +252 -0
  14. package/lib/group-context.d.ts +11 -0
  15. package/lib/group-context.js +33 -0
  16. package/lib/group-create.d.ts +19 -0
  17. package/lib/group-create.js +85 -0
  18. package/lib/group-credential.d.ts +6 -0
  19. package/lib/group-credential.js +39 -0
  20. package/lib/group-handle.d.ts +177 -0
  21. package/lib/group-handle.js +613 -0
  22. package/lib/group-info.d.ts +57 -0
  23. package/lib/group-info.js +85 -0
  24. package/lib/group-membership.d.ts +25 -0
  25. package/lib/group-membership.js +36 -0
  26. package/lib/group-welcome.d.ts +67 -0
  27. package/lib/group-welcome.js +178 -0
  28. package/lib/group.d.ts +7 -233
  29. package/lib/group.js +7 -653
  30. package/lib/head.d.ts +79 -0
  31. package/lib/head.js +150 -0
  32. package/lib/index.d.ts +11 -3
  33. package/lib/index.js +11 -3
  34. package/lib/ledger.d.ts +49 -0
  35. package/lib/ledger.js +67 -0
  36. package/lib/mutex.d.ts +14 -0
  37. package/lib/mutex.js +20 -0
  38. package/lib/policy.d.ts +71 -0
  39. package/lib/policy.js +191 -0
  40. package/lib/recovery.d.ts +227 -0
  41. package/lib/recovery.js +456 -0
  42. package/lib/roster.d.ts +45 -0
  43. package/lib/roster.js +72 -0
  44. package/lib/types.d.ts +31 -11
  45. package/package.json +2 -3
  46. package/lib/capability.d.ts +0 -47
  47. package/lib/capability.js +0 -79
@@ -0,0 +1,85 @@
1
+ import { createGroupInfoWithExternalPubAndRatchetTree, decode, encode, mlsMessageDecoder, mlsMessageEncoder, protocolVersions, wireformats } from 'ts-mls';
2
+ import { GROUP_ANCHOR_EXTENSION_TYPE } from './anchor.js';
3
+ /**
4
+ * Read the MLS epoch from a framed message's cleartext header without decrypting.
5
+ * Advisory only — the header epoch is unauthenticated; use it to drop stale / buffer
6
+ * future messages before the authenticated processMessage. Returns undefined for
7
+ * non-message or undecodable bytes.
8
+ *
9
+ * Total by contract (a safe pre-filter over untrusted Delivery Service bytes): never
10
+ * throws. ts-mls `decode` throws on some malformed inputs (e.g. oversized); that is
11
+ * caught and treated as "not a message".
12
+ */ export function readMessageEpoch(bytes) {
13
+ const message = (()=>{
14
+ try {
15
+ return decode(mlsMessageDecoder, bytes);
16
+ } catch {
17
+ return undefined;
18
+ }
19
+ })();
20
+ if (message == null) return undefined;
21
+ if (message.wireformat === wireformats.mls_private_message) {
22
+ return message.privateMessage.epoch;
23
+ }
24
+ if (message.wireformat === wireformats.mls_public_message) {
25
+ return message.publicMessage.content.epoch;
26
+ }
27
+ return undefined;
28
+ }
29
+ /**
30
+ * Read a framed MLSMessage(GroupInfo)'s epoch and ratchet-tree hash without joining
31
+ * or mutating state. Used to confirm an external-resync Commit was canonically
32
+ * accepted: compare the returned (epoch, treeHash) against the rejoiner's own
33
+ * post-commit state. Equal ⟹ this device's Commit won the epoch; unequal ⟹ another
34
+ * won and the rejoin must retry.
35
+ *
36
+ * Structural read only — does NOT verify the GroupInfo signature; the caller obtains
37
+ * the bytes over the group's authorized channel. Unlike readMessageEpoch, this THROWS
38
+ * on malformed input: an already-trusted malformed GroupInfo is a programming error.
39
+ */ export function inspectGroupInfo(groupInfoBytes) {
40
+ const message = decode(mlsMessageDecoder, groupInfoBytes);
41
+ if (message == null) {
42
+ throw new Error('Invalid groupInfo: failed to decode MLSMessage');
43
+ }
44
+ if (message.wireformat !== wireformats.mls_group_info) {
45
+ throw new Error(`Invalid groupInfo: expected wireformat mls_group_info, got ${String(message.wireformat)}`);
46
+ }
47
+ const { groupContext } = message.groupInfo;
48
+ return {
49
+ epoch: groupContext.epoch,
50
+ treeHash: groupContext.treeHash
51
+ };
52
+ }
53
+ /**
54
+ * Read a framed MLSMessage(GroupInfo)'s group-identifying bindings without joining:
55
+ * the group id its GroupContext names and the raw genesis-anchor extension bytes. A
56
+ * recovering peer compares both against the group it believes it is healing, so a
57
+ * GroupInfo for another group or with a different anchor is refused before it can
58
+ * steer an external join. Structural read only; does not verify the signature. Throws
59
+ * on malformed input, like {@link inspectGroupInfo}.
60
+ */ export function readGroupInfoBinding(groupInfoBytes) {
61
+ const message = decode(mlsMessageDecoder, groupInfoBytes);
62
+ if (message == null) {
63
+ throw new Error('Invalid groupInfo: failed to decode MLSMessage');
64
+ }
65
+ if (message.wireformat !== wireformats.mls_group_info) {
66
+ throw new Error(`Invalid groupInfo: expected wireformat mls_group_info, got ${String(message.wireformat)}`);
67
+ }
68
+ const { groupContext } = message.groupInfo;
69
+ const anchor = groupContext.extensions.find((ext)=>ext.extensionType === GROUP_ANCHOR_EXTENSION_TYPE);
70
+ return {
71
+ groupID: new TextDecoder().decode(groupContext.groupId),
72
+ anchorExtensionData: anchor?.extensionData instanceof Uint8Array ? anchor.extensionData : null
73
+ };
74
+ }
75
+ export async function exportGroupInfo(params) {
76
+ const groupInfo = await createGroupInfoWithExternalPubAndRatchetTree(params.group.state, [], params.group.context.cipherSuite);
77
+ const framed = {
78
+ version: protocolVersions.mls10,
79
+ wireformat: wireformats.mls_group_info,
80
+ groupInfo
81
+ };
82
+ return {
83
+ groupInfo: encode(mlsMessageEncoder, framed)
84
+ };
85
+ }
@@ -0,0 +1,25 @@
1
+ import { type GroupHandle } from './group-handle.js';
2
+ export type RemoveMemberResult = {
3
+ /** Framed MLSMessage bytes. Broadcast to existing members via the DS. */
4
+ commitMessage: Uint8Array;
5
+ newGroup: GroupHandle;
6
+ /** Post-commit epoch (== newGroup.epoch). NOT the commit's wire-header epoch: a
7
+ * commit is framed at the sender's pre-commit epoch (== epoch - 1n), which is what
8
+ * receivers compare against their own handle.epoch for ordering (see
9
+ * readMessageEpoch). */
10
+ epoch: bigint;
11
+ };
12
+ /**
13
+ * Remove a member. Advances the epoch and rotates keys.
14
+ *
15
+ * Removal must demote: a receiver rejects a Remove whose target is still `admin` in
16
+ * the folded roster. So removing an admin means riding the demotion entry on the same
17
+ * commit — pass it as `ledgerEntries`. The caller signs the entry; this only carries it.
18
+ *
19
+ * Reads `group` and returns a NEW derived handle (`newGroup`); it never advances
20
+ * `group`. The caller MUST adopt `newGroup` — never reuse `group` — before the next
21
+ * commit: two commits from the same source handle both frame at its epoch and diverge.
22
+ * The mutex only serializes concurrent calls against one handle; it does not make a
23
+ * second commit from a superseded handle safe.
24
+ */
25
+ export declare function removeMember(group: GroupHandle, leafIndex: number, ledgerEntries?: Array<string>): Promise<RemoveMemberResult>;
@@ -0,0 +1,36 @@
1
+ import { defaultProposalTypes, encode, mlsMessageEncoder } from 'ts-mls';
2
+ import { commitWithEntries } from './group-commit.js';
3
+ import { deriveGroup, mutexFor } from './group-handle.js';
4
+ /**
5
+ * Remove a member. Advances the epoch and rotates keys.
6
+ *
7
+ * Removal must demote: a receiver rejects a Remove whose target is still `admin` in
8
+ * the folded roster. So removing an admin means riding the demotion entry on the same
9
+ * commit — pass it as `ledgerEntries`. The caller signs the entry; this only carries it.
10
+ *
11
+ * Reads `group` and returns a NEW derived handle (`newGroup`); it never advances
12
+ * `group`. The caller MUST adopt `newGroup` — never reuse `group` — before the next
13
+ * commit: two commits from the same source handle both frame at its epoch and diverge.
14
+ * The mutex only serializes concurrent calls against one handle; it does not make a
15
+ * second commit from a superseded handle safe.
16
+ */ export async function removeMember(group, leafIndex, ledgerEntries) {
17
+ return mutexFor(group).run(async ()=>{
18
+ const removeProposal = {
19
+ proposalType: defaultProposalTypes.remove,
20
+ remove: {
21
+ removed: leafIndex
22
+ }
23
+ };
24
+ const enacted = ledgerEntries ?? [];
25
+ const result = await commitWithEntries(group, [
26
+ removeProposal
27
+ ], enacted);
28
+ const newGroup = deriveGroup(group, result.newState);
29
+ await newGroup.applyLedgerEntries(enacted);
30
+ return {
31
+ commitMessage: encode(mlsMessageEncoder, result.commit),
32
+ newGroup,
33
+ epoch: newGroup.epoch
34
+ };
35
+ });
36
+ }
@@ -0,0 +1,67 @@
1
+ import { type OwnIdentity } from '@kokuin/token';
2
+ import type { MemberCredential } from './credential.js';
3
+ import { GroupHandle } from './group-handle.js';
4
+ import type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
5
+ export type ProcessWelcomeResult = {
6
+ group: GroupHandle;
7
+ credential: MemberCredential;
8
+ };
9
+ export type ProcessWelcomeParams = {
10
+ identity: OwnIdentity;
11
+ invite: Invite;
12
+ /** Wire-form framed MLSMessage(Welcome) bytes (preferred), or a pre-decoded
13
+ * ts-mls Welcome object (legacy). `Uint8Array | unknown` collapses to
14
+ * `unknown` in TypeScript; the runtime `instanceof` check selects the path. */
15
+ welcome: Uint8Array | unknown;
16
+ keyPackageBundle: KeyPackageBundle;
17
+ ratchetTree?: unknown;
18
+ options?: GroupOptions;
19
+ };
20
+ /**
21
+ * Process a Welcome message to join a group.
22
+ */
23
+ export declare function processWelcome(params: ProcessWelcomeParams): Promise<ProcessWelcomeResult>;
24
+ export type ProcessWelcomeOnceParams = ProcessWelcomeParams & {
25
+ /** The group ids this member already holds a handle for. */
26
+ joined: Iterable<string>;
27
+ };
28
+ /**
29
+ * Join from a Welcome, unless this member already joined that group — then return
30
+ * `null` and keep the existing handle.
31
+ *
32
+ * A Welcome is delivered AT LEAST ONCE by design (a sender re-delivers on a crash
33
+ * between journaling its commit and delivering, or it would strand an invitee never
34
+ * told it was added), so the receiver must absorb the repeat. {@link processWelcome}
35
+ * does NOT — it is a pure function with no registry of joined groups, so a repeat
36
+ * succeeds silently and hands back a second handle frozen at the join epoch.
37
+ * **Adopting that handle rolls the member back: every member added since is gone from
38
+ * its roster, it can no longer read traffic, and nothing raises an error.** This
39
+ * function exists to remove that hazard.
40
+ *
41
+ * The check cannot be hoisted above `processWelcome`: a Welcome's group id is
42
+ * encrypted to the joiner's key, so there is nothing to check until the handle exists.
43
+ * So this joins, compares the resulting group id against `joined`, and drops the stale
44
+ * handle (a local falling out of scope — nothing zeroizes its key material) rather than
45
+ * returning it. Dedup keys on the group id alone; a Welcome for an id absent from
46
+ * `joined` is an ordinary first join.
47
+ */
48
+ export declare function processWelcomeOnce(params: ProcessWelcomeOnceParams): Promise<ProcessWelcomeResult | null>;
49
+ export type JoinGroupExternalParams = {
50
+ identity: OwnIdentity;
51
+ /** Framed MLSMessage(GroupInfo) bytes from exportGroupInfo. */
52
+ groupInfo: Uint8Array;
53
+ /** Caller's cached credential (from prior processWelcome). Reused as-is,
54
+ * not re-validated. */
55
+ credential: MemberCredential;
56
+ /** Stale-recovery only: atomically removes prior leaf for same identity. */
57
+ resync: true;
58
+ options?: GroupOptions;
59
+ authenticatedData?: Uint8Array;
60
+ };
61
+ export type JoinGroupExternalResult = {
62
+ /** Framed MLSMessage(PublicMessage) bytes. Broadcast to existing members. */
63
+ commitMessage: Uint8Array;
64
+ /** New GroupHandle at post-commit epoch. */
65
+ group: GroupHandle;
66
+ };
67
+ export declare function joinGroupExternal(params: JoinGroupExternalParams): Promise<JoinGroupExternalResult>;
@@ -0,0 +1,178 @@
1
+ import { createInMemoryDIDCache, normalizeDID } from '@kokuin/token';
2
+ import { decode, encode, generateKeyPackageWithKey, joinGroup as mlsJoinGroup, joinGroupExternal as mlsJoinGroupExternal, mlsMessageDecoder, mlsMessageEncoder, protocolVersions, wireformats } from 'ts-mls';
3
+ import { sanitizeRatchetTree } from './codec.js';
4
+ import { buildLeafCapabilities, resolveMlsContext } from './group-context.js';
5
+ import { makeMLSCredential } from './group-credential.js';
6
+ import { GroupHandle } from './group-handle.js';
7
+ import { assertHeadMatches, computeHead, readLedgerHead } from './head.js';
8
+ import { ledgerEntryDigest, verifyLedgerEntry } from './ledger.js';
9
+ import { ROLE_ENTRY_TYPE } from './roster.js';
10
+ /**
11
+ * Process a Welcome message to join a group.
12
+ */ export async function processWelcome(params) {
13
+ const { identity, invite, welcome, keyPackageBundle, ratchetTree, options } = params;
14
+ const cache = options?.cache ?? createInMemoryDIDCache();
15
+ const context = await resolveMlsContext(options);
16
+ // A Welcome is only this member's when the invite carries a role entry naming
17
+ // them: an invite minted for someone else is not an invitation to join.
18
+ const selfDID = normalizeDID(identity.id);
19
+ let namesSelf = false;
20
+ for (const token of invite.ledgerEntries){
21
+ const verified = await verifyLedgerEntry(token);
22
+ if (verified != null && verified.entry.type === ROLE_ENTRY_TYPE && verified.entry.groupID === invite.groupID && normalizeDID(verified.entry.subject) === selfDID) {
23
+ namesSelf = true;
24
+ break;
25
+ }
26
+ }
27
+ if (!namesSelf) {
28
+ throw new Error('processWelcome: the invite carries no role entry naming this identity');
29
+ }
30
+ let resolvedWelcome = welcome;
31
+ if (welcome instanceof Uint8Array) {
32
+ const decoded = decode(mlsMessageDecoder, welcome);
33
+ if (decoded == null || decoded.wireformat !== wireformats.mls_welcome) {
34
+ throw new Error('processWelcome: expected a framed MLSMessage(Welcome)');
35
+ }
36
+ resolvedWelcome = decoded.welcome;
37
+ }
38
+ const sanitizedTree = Array.isArray(ratchetTree) ? sanitizeRatchetTree(ratchetTree) : ratchetTree;
39
+ const state = await mlsJoinGroup({
40
+ context,
41
+ welcome: resolvedWelcome,
42
+ keyPackage: keyPackageBundle.publicPackage,
43
+ privateKeys: keyPackageBundle.privatePackage,
44
+ ...sanitizedTree != null && {
45
+ ratchetTree: sanitizedTree
46
+ }
47
+ });
48
+ const credential = {
49
+ id: identity.id,
50
+ groupID: invite.groupID
51
+ };
52
+ const group = new GroupHandle({
53
+ state,
54
+ credential,
55
+ context,
56
+ cache,
57
+ resolver: options?.resolver,
58
+ commitPolicy: options?.commitPolicy,
59
+ resolveLedgerEntries: options?.resolveLedgerEntries,
60
+ onLedgerEntries: options?.onLedgerEntries
61
+ });
62
+ // The head authenticated in the joined GroupContext is the fold from genesis over the
63
+ // group's entries, in order. Recompute it over the inviter's supplied entries: an
64
+ // omitted, reordered, or truncated list cannot reproduce it. Checked before folding,
65
+ // so an incomplete ledger never reaches the roster.
66
+ const authenticated = readLedgerHead(group);
67
+ if (authenticated == null) {
68
+ throw new Error('processWelcome: the group has no ledger head extension');
69
+ }
70
+ assertHeadMatches(authenticated.head, computeHead(invite.groupID, invite.ledgerEntries.map(ledgerEntryDigest)));
71
+ // Fold the invite's entries: the roster is seeded from the anchor and the fold grants
72
+ // authority only to an admin-so-far, so a member-signed entry cannot promote anyone
73
+ // even though applyLedgerEntries itself is the permissive primitive.
74
+ await group.applyLedgerEntries(invite.ledgerEntries);
75
+ return {
76
+ group,
77
+ credential
78
+ };
79
+ }
80
+ /**
81
+ * Join from a Welcome, unless this member already joined that group — then return
82
+ * `null` and keep the existing handle.
83
+ *
84
+ * A Welcome is delivered AT LEAST ONCE by design (a sender re-delivers on a crash
85
+ * between journaling its commit and delivering, or it would strand an invitee never
86
+ * told it was added), so the receiver must absorb the repeat. {@link processWelcome}
87
+ * does NOT — it is a pure function with no registry of joined groups, so a repeat
88
+ * succeeds silently and hands back a second handle frozen at the join epoch.
89
+ * **Adopting that handle rolls the member back: every member added since is gone from
90
+ * its roster, it can no longer read traffic, and nothing raises an error.** This
91
+ * function exists to remove that hazard.
92
+ *
93
+ * The check cannot be hoisted above `processWelcome`: a Welcome's group id is
94
+ * encrypted to the joiner's key, so there is nothing to check until the handle exists.
95
+ * So this joins, compares the resulting group id against `joined`, and drops the stale
96
+ * handle (a local falling out of scope — nothing zeroizes its key material) rather than
97
+ * returning it. Dedup keys on the group id alone; a Welcome for an id absent from
98
+ * `joined` is an ordinary first join.
99
+ */ export async function processWelcomeOnce(params) {
100
+ const { joined, ...welcomeParams } = params;
101
+ const held = new Set(joined);
102
+ const result = await processWelcome(welcomeParams);
103
+ if (held.has(result.group.groupID)) {
104
+ return null;
105
+ }
106
+ return result;
107
+ }
108
+ export async function joinGroupExternal(params) {
109
+ const { identity, groupInfo: groupInfoBytes, credential, resync, options, authenticatedData } = params;
110
+ // Resync replaces the caller's own prior leaf, so the rejoining identity must match
111
+ // the presented credential. A friendly precheck, not the security boundary: on a
112
+ // mismatch ts-mls rejects the external commit downstream anyway. Eviction
113
+ // completeness rests on ts-mls requiring a matching prior leaf in the resynced tree,
114
+ // which a removed member no longer has.
115
+ if (normalizeDID(identity.id) !== normalizeDID(credential.id)) {
116
+ throw new Error(`joinGroupExternal: identity.id (${identity.id}) must match credential.id (${credential.id}) for resync`);
117
+ }
118
+ const cache = options?.cache ?? createInMemoryDIDCache();
119
+ const context = await resolveMlsContext(options);
120
+ const message = decode(mlsMessageDecoder, groupInfoBytes);
121
+ if (message == null) {
122
+ throw new Error('Invalid groupInfo: failed to decode MLSMessage');
123
+ }
124
+ if (message.wireformat !== wireformats.mls_group_info) {
125
+ throw new Error(`Invalid groupInfo: expected wireformat mls_group_info, got ${String(message.wireformat)}`);
126
+ }
127
+ // Discriminated-union narrow via the literal wireformat tag — no cast needed.
128
+ const { groupInfo } = message;
129
+ // A resync must target the group this credential names. The returned handle reports
130
+ // `credential.groupID` whatever group it joins, so without this a caller steered onto
131
+ // a GroupInfo for another group would hold a handle that lies about its identity.
132
+ const offeredGroupID = new TextDecoder().decode(groupInfo.groupContext.groupId);
133
+ if (offeredGroupID !== credential.groupID) {
134
+ throw new Error(`joinGroupExternal: groupInfo names group ${offeredGroupID}, not credential.groupID (${credential.groupID})`);
135
+ }
136
+ // The rejoining leaf must advertise every GroupContext extension the group uses, or
137
+ // ts-mls rejects the external join. Derive them from the GroupInfo being resynced
138
+ // against, honoring an explicit capabilities override.
139
+ const keyPackage = await generateKeyPackageWithKey({
140
+ credential: makeMLSCredential(identity),
141
+ signatureKeyPair: {
142
+ signKey: identity.privateKey,
143
+ publicKey: identity.publicKey
144
+ },
145
+ cipherSuite: context.cipherSuite,
146
+ capabilities: buildLeafCapabilities(groupInfo.groupContext.extensions, options?.capabilities)
147
+ });
148
+ const { publicMessage, newState } = await mlsJoinGroupExternal({
149
+ context,
150
+ groupInfo,
151
+ keyPackage: keyPackage.publicPackage,
152
+ privateKeys: keyPackage.privatePackage,
153
+ resync,
154
+ ...authenticatedData != null && {
155
+ authenticatedData
156
+ }
157
+ });
158
+ const framedCommit = {
159
+ version: protocolVersions.mls10,
160
+ wireformat: wireformats.mls_public_message,
161
+ publicMessage
162
+ };
163
+ const commitMessage = encode(mlsMessageEncoder, framedCommit);
164
+ const group = new GroupHandle({
165
+ state: newState,
166
+ credential,
167
+ context,
168
+ cache,
169
+ resolver: options?.resolver,
170
+ commitPolicy: options?.commitPolicy,
171
+ resolveLedgerEntries: options?.resolveLedgerEntries,
172
+ onLedgerEntries: options?.onLedgerEntries
173
+ });
174
+ return {
175
+ commitMessage,
176
+ group
177
+ };
178
+ }
package/lib/group.d.ts CHANGED
@@ -1,233 +1,7 @@
1
- import { type DIDCache, type DIDResolver, type OwnIdentity, type SigningIdentity } from '@kokuin/token';
2
- import { type ClientState, type Credential, type IncomingMessageCallback, type KeyPackage, type MlsContext, type ProposalWithSender } from 'ts-mls';
3
- import { type GroupPermission } from './capability.js';
4
- import { type GroupMember, type MemberCredential } from './credential.js';
5
- import type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
6
- export declare function makeMLSCredential(identity: OwnIdentity): Credential;
7
- /**
8
- * Thrown by GroupHandle.processMessage/decrypt when the active commit policy
9
- * rejects an incoming commit. The handle is left at its pre-commit epoch.
10
- */
11
- export declare class CommitRejectedError extends Error {
12
- #private;
13
- constructor(proposals: Array<ProposalWithSender>, senderLeafIndex?: number);
14
- get proposals(): Array<ProposalWithSender>;
15
- get senderLeafIndex(): number | undefined;
16
- }
17
- export type GroupHandleParams = {
18
- state: ClientState;
19
- credential: MemberCredential;
20
- context: MlsContext;
21
- /** Stringified root capability (for delegation) */
22
- rootCapability: string;
23
- cache: DIDCache;
24
- resolver?: DIDResolver;
25
- /** Default commit policy applied by processMessage/decrypt. */
26
- commitPolicy?: IncomingMessageCallback;
27
- };
28
- /**
29
- * Mutable wrapper around MLS group state + Enkaku credential.
30
- */
31
- export declare class GroupHandle {
32
- #private;
33
- constructor(params: GroupHandleParams);
34
- get groupID(): string;
35
- get epoch(): bigint;
36
- get treeHash(): Uint8Array;
37
- get credential(): MemberCredential;
38
- get state(): ClientState;
39
- get rootCapability(): string;
40
- get context(): MlsContext;
41
- get cache(): DIDCache;
42
- get resolver(): DIDResolver | undefined;
43
- /** The commit policy enforced by processMessage/decrypt, if any. Carried
44
- * onto handles derived from this one (commitInvite/removeMember). */
45
- get commitPolicy(): IncomingMessageCallback | undefined;
46
- get memberCount(): number;
47
- findMemberLeafIndex(id: string): number | undefined;
48
- /**
49
- * Enumerate the group's current members from the ratchet tree, in ascending
50
- * leaf-index order. Leaves whose credential identity fails to parse are skipped
51
- * (same tolerance as findMemberLeafIndex). Reflects the handle's current #state
52
- * — call before and after processMessage to diff a commit's membership change.
53
- */
54
- listMembers(): Array<GroupMember>;
55
- /**
56
- * Encrypt an application message for the group.
57
- */
58
- encrypt(plaintext: Uint8Array): Promise<{
59
- message: unknown;
60
- consumed: Array<Uint8Array>;
61
- }>;
62
- /**
63
- * Decrypt an application message from the group.
64
- *
65
- * Accepts either wire-form bytes (framed MLSMessage `Uint8Array`) or a
66
- * pre-decoded ts-mls message object. The param type widens to `unknown`
67
- * because `Uint8Array | unknown` collapses to `unknown` in TypeScript; the
68
- * runtime `instanceof` check selects the decode path. Note: `encrypt`
69
- * currently emits objects, so the bytes path is for symmetry with
70
- * processMessage and future wire-form application messages.
71
- */
72
- decrypt(message: Uint8Array | unknown, opts?: {
73
- commitPolicy?: IncomingMessageCallback;
74
- }): Promise<Uint8Array>;
75
- /**
76
- * Process a received MLS message (Commit, Proposal, or application).
77
- *
78
- * Accepts either wire-form bytes (the preferred input — framed MLSMessage
79
- * `Uint8Array`, e.g. from commitInvite/removeMember) or a pre-decoded ts-mls
80
- * message object (legacy path). The param type widens to `unknown` because
81
- * `Uint8Array | unknown` collapses to `unknown` in TypeScript; the runtime
82
- * `instanceof` check selects the decode path.
83
- */
84
- processMessage(message: Uint8Array | unknown, opts?: {
85
- commitPolicy?: IncomingMessageCallback;
86
- }): Promise<Uint8Array | null>;
87
- }
88
- export type CreateGroupResult = {
89
- group: GroupHandle;
90
- credential: MemberCredential;
91
- };
92
- /**
93
- * Create a new MLS group. The identity becomes the sole member and admin.
94
- */
95
- export declare function createGroup(identity: OwnIdentity, groupID: string, options?: GroupOptions): Promise<CreateGroupResult>;
96
- export type RestoreGroupParams = {
97
- state: ClientState;
98
- credential: MemberCredential;
99
- rootCapability: string;
100
- options?: GroupOptions;
101
- };
102
- export declare function restoreGroup(params: RestoreGroupParams): Promise<GroupHandle>;
103
- export type CreateInviteParams = {
104
- group: GroupHandle;
105
- identity: SigningIdentity;
106
- recipientDID: string;
107
- permission: GroupPermission;
108
- };
109
- export type CreateInviteResult = {
110
- invite: Invite;
111
- };
112
- /**
113
- * Create an invite for a new member.
114
- * Does NOT add them to the group — call commitInvite with their key package to do that.
115
- */
116
- export declare function createInvite(params: CreateInviteParams): Promise<CreateInviteResult>;
117
- export type CommitInviteResult = {
118
- /** Framed MLSMessage bytes. Broadcast to existing members via the DS. */
119
- commitMessage: Uint8Array;
120
- /** Framed MLSMessage(Welcome) bytes. Delivered to the new member. */
121
- welcomeMessage: Uint8Array;
122
- newGroup: GroupHandle;
123
- /** Post-commit epoch the group is now at (== newGroup.epoch). NOTE: this is
124
- * NOT the epoch carried in the commit's wire header — a commit is framed at
125
- * the sender's pre-commit epoch (== epoch - 1n), which is what receivers
126
- * compare against their own handle.epoch for ordering (see readMessageEpoch). */
127
- epoch: bigint;
128
- };
129
- /**
130
- * Commit an invite by adding the invitee's key package to the group.
131
- * Produces an MLS Commit + Welcome.
132
- */
133
- export declare function commitInvite(group: GroupHandle, keyPackage: KeyPackage): Promise<CommitInviteResult>;
134
- export type ProcessWelcomeResult = {
135
- group: GroupHandle;
136
- credential: MemberCredential;
137
- };
138
- export type ProcessWelcomeParams = {
139
- identity: OwnIdentity;
140
- invite: Invite;
141
- /** Wire-form framed MLSMessage(Welcome) bytes (preferred), or a pre-decoded
142
- * ts-mls Welcome object (legacy). `Uint8Array | unknown` collapses to
143
- * `unknown` in TypeScript; the runtime `instanceof` check selects the path. */
144
- welcome: Uint8Array | unknown;
145
- keyPackageBundle: KeyPackageBundle;
146
- ratchetTree?: unknown;
147
- options?: GroupOptions;
148
- };
149
- /**
150
- * Process a Welcome message to join a group.
151
- */
152
- export declare function processWelcome(params: ProcessWelcomeParams): Promise<ProcessWelcomeResult>;
153
- export type RemoveMemberResult = {
154
- /** Framed MLSMessage bytes. Broadcast to existing members via the DS. */
155
- commitMessage: Uint8Array;
156
- newGroup: GroupHandle;
157
- /** Post-commit epoch the group is now at (== newGroup.epoch). NOTE: this is
158
- * NOT the epoch carried in the commit's wire header — a commit is framed at
159
- * the sender's pre-commit epoch (== epoch - 1n), which is what receivers
160
- * compare against their own handle.epoch for ordering (see readMessageEpoch). */
161
- epoch: bigint;
162
- };
163
- /**
164
- * Remove a member from the group. Advances the epoch and rotates keys.
165
- */
166
- export declare function removeMember(group: GroupHandle, leafIndex: number): Promise<RemoveMemberResult>;
167
- /**
168
- * Read the MLS epoch from a framed handshake/application message's cleartext
169
- * header, without decrypting. Advisory only — the header epoch is unauthenticated;
170
- * use it to drop stale / buffer future messages before the authenticated
171
- * processMessage. Returns undefined for non-message or undecodable bytes.
172
- *
173
- * Total by contract: this is a safe pre-filter over bytes arriving from an
174
- * untrusted Delivery Service, so it never throws. ts-mls `decode` throws (e.g.
175
- * CodecError on input larger than its max size) rather than returning undefined
176
- * for some malformed inputs; that is caught and treated as "not a message".
177
- */
178
- export declare function readMessageEpoch(bytes: Uint8Array): bigint | undefined;
179
- export type InspectGroupInfoResult = {
180
- /** The GroupInfo's epoch, read from its groupContext. */
181
- epoch: bigint;
182
- /** The GroupInfo's ratchet-tree hash, read from its groupContext. Compare for
183
- * equality against a known post-commit state's treeHash to confirm canonical
184
- * convergence (same epoch + same treeHash ⟺ same group state). */
185
- treeHash: Uint8Array;
186
- };
187
- /**
188
- * Non-destructively inspect a framed MLSMessage(GroupInfo) — read its epoch and
189
- * ratchet-tree hash without joining or mutating any state. Used to confirm an
190
- * external-resync Commit was canonically accepted: compare the returned
191
- * (epoch, treeHash) for equality against the rejoiner's own post-commit state
192
- * (GroupHandle.epoch / GroupHandle.treeHash). Equal ⟹ this device's Commit won
193
- * the epoch; unequal ⟹ another Commit won and the rejoin must retry.
194
- *
195
- * Structural read only: it does NOT verify the GroupInfo signature. The caller
196
- * is expected to have obtained the bytes over the group's authorized channel.
197
- * Unlike readMessageEpoch (a total pre-filter over untrusted DS bytes), this
198
- * THROWS on malformed input — a malformed already-trusted GroupInfo is a
199
- * programming error, not expected traffic.
200
- */
201
- export declare function inspectGroupInfo(groupInfoBytes: Uint8Array): InspectGroupInfoResult;
202
- /**
203
- * Generate a key package for joining groups.
204
- */
205
- export declare function createKeyPackageBundle(identity: OwnIdentity, options?: GroupOptions): Promise<KeyPackageBundle>;
206
- export type ExportGroupInfoParams = {
207
- group: GroupHandle;
208
- };
209
- export type ExportGroupInfoResult = {
210
- /** Framed MLSMessage(GroupInfo) bytes. Self-describing with protocol
211
- * version + wireformat + GroupInfo (external_pub + ratchet tree embedded). */
212
- groupInfo: Uint8Array;
213
- };
214
- export declare function exportGroupInfo(params: ExportGroupInfoParams): Promise<ExportGroupInfoResult>;
215
- export type JoinGroupExternalParams = {
216
- identity: OwnIdentity;
217
- /** Framed MLSMessage(GroupInfo) bytes from exportGroupInfo. */
218
- groupInfo: Uint8Array;
219
- /** Caller's cached credential (from prior processWelcome). Reused as-is,
220
- * not re-validated. */
221
- credential: MemberCredential;
222
- /** Stale-recovery only: atomically removes prior leaf for same identity. */
223
- resync: true;
224
- options?: GroupOptions;
225
- authenticatedData?: Uint8Array;
226
- };
227
- export type JoinGroupExternalResult = {
228
- /** Framed MLSMessage(PublicMessage) bytes. Broadcast to existing members. */
229
- commitMessage: Uint8Array;
230
- /** New GroupHandle at post-commit epoch. */
231
- group: GroupHandle;
232
- };
233
- export declare function joinGroupExternal(params: JoinGroupExternalParams): Promise<JoinGroupExternalResult>;
1
+ export { type CommitInviteResult, type CommitLedgerEntriesResult, type CreateInviteParams, type CreateInviteResult, commitInvite, commitLedgerEntries, createInvite, } from './group-commit.js';
2
+ export { type CreateGroupResult, createGroup, type RestoreGroupParams, restoreGroup, } from './group-create.js';
3
+ export { createKeyPackageBundle, makeMLSCredential } from './group-credential.js';
4
+ export { CommitRejectedError, GroupHandle, type GroupHandleParams, type HeldLedgerEntry, type LedgerLogEntry, } from './group-handle.js';
5
+ export { type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, type GroupInfoBinding, type InspectGroupInfoResult, inspectGroupInfo, readGroupInfoBinding, readMessageEpoch, } from './group-info.js';
6
+ export { type RemoveMemberResult, removeMember } from './group-membership.js';
7
+ export { type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, type ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, } from './group-welcome.js';