@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
package/lib/group.js CHANGED
@@ -1,653 +1,7 @@
1
- import { createInMemoryDIDCache, isPeer4, normalizeDID, stringifyToken } from '@kokuin/token';
2
- import { createApplicationMessage, createCommit, createGroupInfoWithExternalPubAndRatchetTree, decode, defaultCapabilities, defaultCredentialTypes, defaultProposalTypes, encode, generateKeyPackageWithKey, getCiphersuiteImpl, createGroup as mlsCreateGroup, joinGroup as mlsJoinGroup, joinGroupExternal as mlsJoinGroupExternal, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, protocolVersions, wireformats } from 'ts-mls';
3
- import { createDIDAuthenticationService } from './authentication.js';
4
- import { createGroupCapability, delegateGroupMembership } from './capability.js';
5
- import { sanitizeRatchetTree } from './codec.js';
6
- import { parseMLSCredentialIdentity } from './credential.js';
7
- import { nobleCryptoProvider } from './crypto.js';
8
- const DEFAULT_CIPHERSUITE = 'MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519';
9
- async function resolveMlsContext(options) {
10
- const name = options?.ciphersuiteName ?? DEFAULT_CIPHERSUITE;
11
- const cipherSuite = await getCiphersuiteImpl(name, options?.cryptoProvider ?? nobleCryptoProvider);
12
- const authService = createDIDAuthenticationService();
13
- return {
14
- cipherSuite,
15
- authService
16
- };
17
- }
18
- export function makeMLSCredential(identity) {
19
- const id = identity.id;
20
- const isPeer = isPeer4(id);
21
- if (isPeer && !('longForm' in identity && typeof identity.longForm === 'string')) {
22
- throw new Error('peer:4 identity is missing longForm; only identities from createIdentity can be used as MLS members');
23
- }
24
- const payload = {
25
- id
26
- };
27
- if (isPeer) {
28
- payload.longForm = identity.longForm;
29
- }
30
- return {
31
- credentialType: defaultCredentialTypes.basic,
32
- identity: new TextEncoder().encode(JSON.stringify(payload))
33
- };
34
- }
35
- /**
36
- * Thrown by GroupHandle.processMessage/decrypt when the active commit policy
37
- * rejects an incoming commit. The handle is left at its pre-commit epoch.
38
- */ export class CommitRejectedError extends Error {
39
- #proposals;
40
- #senderLeafIndex;
41
- constructor(proposals, senderLeafIndex){
42
- super('Commit rejected by group commit policy');
43
- this.name = 'CommitRejectedError';
44
- this.#proposals = proposals;
45
- this.#senderLeafIndex = senderLeafIndex;
46
- }
47
- get proposals() {
48
- return this.#proposals;
49
- }
50
- get senderLeafIndex() {
51
- return this.#senderLeafIndex;
52
- }
53
- }
54
- /**
55
- * Wrap a consumer commit policy so the rejected commit's proposals are captured
56
- * for CommitRejectedError. ts-mls's ProcessMessageResult does not surface the
57
- * rejected proposals on the result, so we record them from the callback's own
58
- * argument on the 'reject' path onto `capture.rejected`. Returns undefined when
59
- * no policy is set.
60
- */ function wrapCommitPolicy(callback, capture) {
61
- if (callback == null) return undefined;
62
- return (incoming)=>{
63
- const action = callback(incoming);
64
- if (action === 'reject' && incoming.kind === 'commit') {
65
- capture.rejected = {
66
- proposals: incoming.proposals,
67
- senderLeafIndex: incoming.senderLeafIndex == null ? undefined : Number(incoming.senderLeafIndex)
68
- };
69
- }
70
- return action;
71
- };
72
- }
73
- /**
74
- * Mutable wrapper around MLS group state + Enkaku credential.
75
- */ export class GroupHandle {
76
- #state;
77
- #credential;
78
- #context;
79
- #rootCapability;
80
- #cache;
81
- #resolver;
82
- #commitPolicy;
83
- constructor(params){
84
- this.#state = params.state;
85
- this.#credential = params.credential;
86
- this.#context = params.context;
87
- this.#rootCapability = params.rootCapability;
88
- this.#cache = params.cache;
89
- this.#resolver = params.resolver;
90
- this.#commitPolicy = params.commitPolicy;
91
- }
92
- get groupID() {
93
- return this.#credential.groupID;
94
- }
95
- get epoch() {
96
- return this.#state.groupContext.epoch;
97
- }
98
- get treeHash() {
99
- return this.#state.groupContext.treeHash;
100
- }
101
- get credential() {
102
- return this.#credential;
103
- }
104
- get state() {
105
- return this.#state;
106
- }
107
- get rootCapability() {
108
- return this.#rootCapability;
109
- }
110
- get context() {
111
- return this.#context;
112
- }
113
- get cache() {
114
- return this.#cache;
115
- }
116
- get resolver() {
117
- return this.#resolver;
118
- }
119
- /** The commit policy enforced by processMessage/decrypt, if any. Carried
120
- * onto handles derived from this one (commitInvite/removeMember). */ get commitPolicy() {
121
- return this.#commitPolicy;
122
- }
123
- get memberCount() {
124
- return this.#state.ratchetTree.filter((node)=>node != null && node.nodeType === nodeTypes.leaf).length;
125
- }
126
- *#iterateMembers() {
127
- const tree = this.#state.ratchetTree;
128
- for(let i = 0; i < tree.length; i++){
129
- const node = tree[i];
130
- if (node != null && node.nodeType === nodeTypes.leaf) {
131
- const credential = node.leaf.credential;
132
- if ('identity' in credential) {
133
- let parsed;
134
- try {
135
- parsed = parseMLSCredentialIdentity(credential.identity);
136
- } catch {
137
- continue;
138
- }
139
- yield {
140
- leafIndex: i / 2,
141
- id: parsed.id
142
- };
143
- }
144
- }
145
- }
146
- }
147
- findMemberLeafIndex(id) {
148
- const targetNorm = normalizeDID(id);
149
- for (const member of this.#iterateMembers()){
150
- if (normalizeDID(member.id) === targetNorm) return member.leafIndex;
151
- }
152
- return undefined;
153
- }
154
- /**
155
- * Enumerate the group's current members from the ratchet tree, in ascending
156
- * leaf-index order. Leaves whose credential identity fails to parse are skipped
157
- * (same tolerance as findMemberLeafIndex). Reflects the handle's current #state
158
- * — call before and after processMessage to diff a commit's membership change.
159
- */ listMembers() {
160
- return [
161
- ...this.#iterateMembers()
162
- ];
163
- }
164
- /**
165
- * Encrypt an application message for the group.
166
- */ async encrypt(plaintext) {
167
- const { newState, message, consumed } = await createApplicationMessage({
168
- context: this.#context,
169
- state: this.#state,
170
- message: plaintext
171
- });
172
- this.#state = newState;
173
- return {
174
- message,
175
- consumed
176
- };
177
- }
178
- /**
179
- * Decrypt an application message from the group.
180
- *
181
- * Accepts either wire-form bytes (framed MLSMessage `Uint8Array`) or a
182
- * pre-decoded ts-mls message object. The param type widens to `unknown`
183
- * because `Uint8Array | unknown` collapses to `unknown` in TypeScript; the
184
- * runtime `instanceof` check selects the decode path. Note: `encrypt`
185
- * currently emits objects, so the bytes path is for symmetry with
186
- * processMessage and future wire-form application messages.
187
- */ async decrypt(message, opts) {
188
- let decoded = message;
189
- if (message instanceof Uint8Array) {
190
- const parsed = decode(mlsMessageDecoder, message);
191
- if (parsed == null) {
192
- throw new Error('decrypt: failed to decode MLSMessage');
193
- }
194
- decoded = parsed;
195
- }
196
- const callback = opts?.commitPolicy ?? this.#commitPolicy;
197
- const capture = {};
198
- const wrapped = wrapCommitPolicy(callback, capture);
199
- const result = await mlsProcessMessage({
200
- context: this.#context,
201
- state: this.#state,
202
- message: decoded,
203
- ...wrapped != null && {
204
- callback: wrapped
205
- }
206
- });
207
- if (result.kind === 'applicationMessage') {
208
- this.#state = result.newState;
209
- return result.message;
210
- }
211
- // On reject, ts-mls returns the pre-commit state, so the handle stays put.
212
- this.#state = result.newState;
213
- if (result.kind === 'newState' && result.actionTaken === 'reject') {
214
- throw new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex);
215
- }
216
- throw new Error('Expected application message but received handshake message');
217
- }
218
- /**
219
- * Process a received MLS message (Commit, Proposal, or application).
220
- *
221
- * Accepts either wire-form bytes (the preferred input — framed MLSMessage
222
- * `Uint8Array`, e.g. from commitInvite/removeMember) or a pre-decoded ts-mls
223
- * message object (legacy path). The param type widens to `unknown` because
224
- * `Uint8Array | unknown` collapses to `unknown` in TypeScript; the runtime
225
- * `instanceof` check selects the decode path.
226
- */ async processMessage(message, opts) {
227
- let decoded = message;
228
- if (message instanceof Uint8Array) {
229
- const parsed = decode(mlsMessageDecoder, message);
230
- if (parsed == null) {
231
- throw new Error('processMessage: failed to decode MLSMessage');
232
- }
233
- decoded = parsed;
234
- }
235
- const callback = opts?.commitPolicy ?? this.#commitPolicy;
236
- const capture = {};
237
- const wrapped = wrapCommitPolicy(callback, capture);
238
- const result = await mlsProcessMessage({
239
- context: this.#context,
240
- state: this.#state,
241
- message: decoded,
242
- ...wrapped != null && {
243
- callback: wrapped
244
- }
245
- });
246
- // On reject, ts-mls returns the pre-commit state, so the handle stays put.
247
- this.#state = result.newState;
248
- if (result.kind === 'newState' && result.actionTaken === 'reject') {
249
- throw new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex);
250
- }
251
- if (result.kind === 'applicationMessage') {
252
- return result.message;
253
- }
254
- return null;
255
- }
256
- }
257
- // ---------------------------------------------------------------------------
258
- // Lifecycle functions
259
- // ---------------------------------------------------------------------------
260
- /**
261
- * Build the leaf-node capabilities for a member joining or creating a group.
262
- * RFC 9420 requires a member's leaf to advertise every non-default GroupContext
263
- * extension type the group uses; we derive that set from the group's extensions
264
- * so it cannot desync. This applies equally to a creator (extensions from the
265
- * group being created) and to an external rejoiner (extensions from the
266
- * GroupInfo it resyncs against) — a rejoining leaf that advertises only the
267
- * defaults is rejected by ts-mls with "client does not support every extension
268
- * in the GroupContext". An explicit `override` (GroupOptions.capabilities) wins
269
- * verbatim.
270
- */ function buildLeafCapabilities(extensions, override) {
271
- if (override != null) return override;
272
- const base = defaultCapabilities();
273
- const types = new Set([
274
- ...base.extensions,
275
- ...extensions.map((e)=>e.extensionType)
276
- ]);
277
- return {
278
- ...base,
279
- extensions: [
280
- ...types
281
- ]
282
- };
283
- }
284
- /**
285
- * Create a new MLS group. The identity becomes the sole member and admin.
286
- */ export async function createGroup(identity, groupID, options) {
287
- const cache = options?.cache ?? createInMemoryDIDCache();
288
- const context = await resolveMlsContext(options);
289
- const extensions = options?.extensions ?? [];
290
- const statePromise = generateKeyPackageWithKey({
291
- credential: makeMLSCredential(identity),
292
- signatureKeyPair: {
293
- signKey: identity.privateKey,
294
- publicKey: identity.publicKey
295
- },
296
- cipherSuite: context.cipherSuite,
297
- capabilities: buildLeafCapabilities(extensions, options?.capabilities)
298
- }).then((keyPackage)=>{
299
- return mlsCreateGroup({
300
- context,
301
- groupId: new TextEncoder().encode(groupID),
302
- keyPackage: keyPackage.publicPackage,
303
- privateKeyPackage: keyPackage.privatePackage,
304
- extensions
305
- });
306
- });
307
- const [state, rootCap] = await Promise.all([
308
- statePromise,
309
- createGroupCapability(identity, groupID)
310
- ]);
311
- const rootCapability = stringifyToken(rootCap);
312
- const credential = {
313
- id: identity.id,
314
- capabilityChain: [
315
- rootCapability
316
- ],
317
- capability: rootCap,
318
- permission: 'admin',
319
- groupID
320
- };
321
- const group = new GroupHandle({
322
- state,
323
- credential,
324
- context,
325
- rootCapability,
326
- cache,
327
- resolver: options?.resolver,
328
- commitPolicy: options?.commitPolicy
329
- });
330
- return {
331
- group,
332
- credential
333
- };
334
- }
335
- export async function restoreGroup(params) {
336
- const cache = params.options?.cache ?? createInMemoryDIDCache();
337
- return new GroupHandle({
338
- state: params.state,
339
- credential: params.credential,
340
- context: await resolveMlsContext(params.options),
341
- rootCapability: params.rootCapability,
342
- cache,
343
- resolver: params.options?.resolver,
344
- commitPolicy: params.options?.commitPolicy
345
- });
346
- }
347
- /**
348
- * Create an invite for a new member.
349
- * Does NOT add them to the group — call commitInvite with their key package to do that.
350
- */ export async function createInvite(params) {
351
- const { group, identity, recipientDID, permission } = params;
352
- const memberCap = await delegateGroupMembership({
353
- identity,
354
- groupID: group.groupID,
355
- recipientDID,
356
- permission,
357
- parentCapability: group.rootCapability
358
- });
359
- const memberCapStr = stringifyToken(memberCap);
360
- const invite = {
361
- groupID: group.groupID,
362
- capabilityToken: memberCapStr,
363
- capabilityChain: [
364
- group.rootCapability,
365
- memberCapStr
366
- ],
367
- permission,
368
- inviterID: identity.id
369
- };
370
- return {
371
- invite
372
- };
373
- }
374
- /**
375
- * Commit an invite by adding the invitee's key package to the group.
376
- * Produces an MLS Commit + Welcome.
377
- */ export async function commitInvite(group, keyPackage) {
378
- const addProposal = {
379
- proposalType: defaultProposalTypes.add,
380
- add: {
381
- keyPackage
382
- }
383
- };
384
- const result = await createCommit({
385
- context: group.context,
386
- state: group.state,
387
- extraProposals: [
388
- addProposal
389
- ],
390
- ratchetTreeExtension: true
391
- });
392
- const newGroup = new GroupHandle({
393
- state: result.newState,
394
- credential: group.credential,
395
- context: group.context,
396
- rootCapability: group.rootCapability,
397
- cache: group.cache,
398
- resolver: group.resolver,
399
- commitPolicy: group.commitPolicy
400
- });
401
- if (result.welcome == null) {
402
- throw new Error('commitInvite: expected a Welcome message for the add proposal');
403
- }
404
- return {
405
- commitMessage: encode(mlsMessageEncoder, result.commit),
406
- welcomeMessage: encode(mlsMessageEncoder, result.welcome),
407
- newGroup,
408
- epoch: newGroup.epoch
409
- };
410
- }
411
- /**
412
- * Process a Welcome message to join a group.
413
- */ export async function processWelcome(params) {
414
- const { identity, invite, welcome, keyPackageBundle, ratchetTree, options } = params;
415
- const cache = options?.cache ?? createInMemoryDIDCache();
416
- const context = await resolveMlsContext(options);
417
- // Validate the invite's capability chain before trusting it.
418
- // validateGroupCapability internally calls verifyToken with cache/resolver and returns the
419
- // verified token — reuse it instead of calling verifyToken a second time without cache/resolver.
420
- const { validateGroupCapability } = await import('./capability.js');
421
- const capToken = await validateGroupCapability({
422
- tokenData: invite.capabilityToken,
423
- groupID: invite.groupID,
424
- delegationChain: invite.capabilityChain.length > 1 ? invite.capabilityChain.slice(0, -1) : undefined,
425
- options: {
426
- cache,
427
- resolver: options?.resolver
428
- }
429
- });
430
- let resolvedWelcome = welcome;
431
- if (welcome instanceof Uint8Array) {
432
- const decoded = decode(mlsMessageDecoder, welcome);
433
- if (decoded == null || decoded.wireformat !== wireformats.mls_welcome) {
434
- throw new Error('processWelcome: expected a framed MLSMessage(Welcome)');
435
- }
436
- resolvedWelcome = decoded.welcome;
437
- }
438
- const sanitizedTree = Array.isArray(ratchetTree) ? sanitizeRatchetTree(ratchetTree) : ratchetTree;
439
- const state = await mlsJoinGroup({
440
- context,
441
- welcome: resolvedWelcome,
442
- keyPackage: keyPackageBundle.publicPackage,
443
- privateKeys: keyPackageBundle.privatePackage,
444
- ...sanitizedTree != null && {
445
- ratchetTree: sanitizedTree
446
- }
447
- });
448
- const credential = {
449
- id: identity.id,
450
- capabilityChain: invite.capabilityChain,
451
- capability: capToken,
452
- permission: invite.permission,
453
- groupID: invite.groupID
454
- };
455
- const group = new GroupHandle({
456
- state,
457
- credential,
458
- context,
459
- rootCapability: invite.capabilityChain[0] ?? (()=>{
460
- throw new Error('Invalid invite: capability chain must not be empty');
461
- })(),
462
- cache,
463
- resolver: options?.resolver,
464
- commitPolicy: options?.commitPolicy
465
- });
466
- return {
467
- group,
468
- credential
469
- };
470
- }
471
- /**
472
- * Remove a member from the group. Advances the epoch and rotates keys.
473
- */ export async function removeMember(group, leafIndex) {
474
- const removeProposal = {
475
- proposalType: defaultProposalTypes.remove,
476
- remove: {
477
- removed: leafIndex
478
- }
479
- };
480
- const result = await createCommit({
481
- context: group.context,
482
- state: group.state,
483
- extraProposals: [
484
- removeProposal
485
- ]
486
- });
487
- const newGroup = new GroupHandle({
488
- state: result.newState,
489
- credential: group.credential,
490
- context: group.context,
491
- rootCapability: group.rootCapability,
492
- cache: group.cache,
493
- resolver: group.resolver,
494
- commitPolicy: group.commitPolicy
495
- });
496
- return {
497
- commitMessage: encode(mlsMessageEncoder, result.commit),
498
- newGroup,
499
- epoch: newGroup.epoch
500
- };
501
- }
502
- /**
503
- * Read the MLS epoch from a framed handshake/application message's cleartext
504
- * header, without decrypting. Advisory only — the header epoch is unauthenticated;
505
- * use it to drop stale / buffer future messages before the authenticated
506
- * processMessage. Returns undefined for non-message or undecodable bytes.
507
- *
508
- * Total by contract: this is a safe pre-filter over bytes arriving from an
509
- * untrusted Delivery Service, so it never throws. ts-mls `decode` throws (e.g.
510
- * CodecError on input larger than its max size) rather than returning undefined
511
- * for some malformed inputs; that is caught and treated as "not a message".
512
- */ export function readMessageEpoch(bytes) {
513
- const message = (()=>{
514
- try {
515
- return decode(mlsMessageDecoder, bytes);
516
- } catch {
517
- return undefined;
518
- }
519
- })();
520
- if (message == null) return undefined;
521
- if (message.wireformat === wireformats.mls_private_message) {
522
- return message.privateMessage.epoch;
523
- }
524
- if (message.wireformat === wireformats.mls_public_message) {
525
- return message.publicMessage.content.epoch;
526
- }
527
- return undefined;
528
- }
529
- /**
530
- * Non-destructively inspect a framed MLSMessage(GroupInfo) — read its epoch and
531
- * ratchet-tree hash without joining or mutating any state. Used to confirm an
532
- * external-resync Commit was canonically accepted: compare the returned
533
- * (epoch, treeHash) for equality against the rejoiner's own post-commit state
534
- * (GroupHandle.epoch / GroupHandle.treeHash). Equal ⟹ this device's Commit won
535
- * the epoch; unequal ⟹ another Commit won and the rejoin must retry.
536
- *
537
- * Structural read only: it does NOT verify the GroupInfo signature. The caller
538
- * is expected to have obtained the bytes over the group's authorized channel.
539
- * Unlike readMessageEpoch (a total pre-filter over untrusted DS bytes), this
540
- * THROWS on malformed input — a malformed already-trusted GroupInfo is a
541
- * programming error, not expected traffic.
542
- */ export function inspectGroupInfo(groupInfoBytes) {
543
- const message = decode(mlsMessageDecoder, groupInfoBytes);
544
- if (message == null) {
545
- throw new Error('Invalid groupInfo: failed to decode MLSMessage');
546
- }
547
- if (message.wireformat !== wireformats.mls_group_info) {
548
- throw new Error(`Invalid groupInfo: expected wireformat mls_group_info, got ${String(message.wireformat)}`);
549
- }
550
- const { groupContext } = message.groupInfo;
551
- return {
552
- epoch: groupContext.epoch,
553
- treeHash: groupContext.treeHash
554
- };
555
- }
556
- /**
557
- * Generate a key package for joining groups.
558
- */ export async function createKeyPackageBundle(identity, options) {
559
- const { cipherSuite } = await resolveMlsContext(options);
560
- const result = await generateKeyPackageWithKey({
561
- credential: makeMLSCredential(identity),
562
- signatureKeyPair: {
563
- signKey: identity.privateKey,
564
- publicKey: identity.publicKey
565
- },
566
- cipherSuite,
567
- capabilities: options?.capabilities ?? defaultCapabilities()
568
- });
569
- return {
570
- ...result,
571
- ownerDID: identity.id
572
- };
573
- }
574
- export async function exportGroupInfo(params) {
575
- const groupInfo = await createGroupInfoWithExternalPubAndRatchetTree(params.group.state, [], params.group.context.cipherSuite);
576
- const framed = {
577
- version: protocolVersions.mls10,
578
- wireformat: wireformats.mls_group_info,
579
- groupInfo
580
- };
581
- return {
582
- groupInfo: encode(mlsMessageEncoder, framed)
583
- };
584
- }
585
- export async function joinGroupExternal(params) {
586
- const { identity, groupInfo: groupInfoBytes, credential, resync, options, authenticatedData } = params;
587
- const rootCapability = credential.capabilityChain[0];
588
- if (rootCapability == null) {
589
- throw new Error('Invalid credential: capability chain must not be empty');
590
- }
591
- // Guard: resync requires the rejoining identity to match the leaf being
592
- // replaced. If `identity.id` does not match `credential.id`, ts-mls's
593
- // findIndex returns -1 and the downstream `removeLeafNodeMutable(tree, -1)`
594
- // call enters an unbounded loop (ts-mls bug; the no-match branch is not
595
- // guarded). Reject early with a clear error.
596
- if (normalizeDID(identity.id) !== normalizeDID(credential.id)) {
597
- throw new Error(`joinGroupExternal: identity.id (${identity.id}) must match credential.id (${credential.id}) for resync`);
598
- }
599
- const cache = options?.cache ?? createInMemoryDIDCache();
600
- const context = await resolveMlsContext(options);
601
- const message = decode(mlsMessageDecoder, groupInfoBytes);
602
- if (message == null) {
603
- throw new Error('Invalid groupInfo: failed to decode MLSMessage');
604
- }
605
- if (message.wireformat !== wireformats.mls_group_info) {
606
- throw new Error(`Invalid groupInfo: expected wireformat mls_group_info, got ${String(message.wireformat)}`);
607
- }
608
- // Discriminated-union narrow via the literal wireformat tag — no cast needed.
609
- const { groupInfo } = message;
610
- // The rejoining leaf must advertise every GroupContext extension the group
611
- // uses (e.g. a genesis-anchor extension), or ts-mls rejects the external
612
- // join with "client does not support every extension in the GroupContext".
613
- // Derive them from the GroupInfo being resynced against, honoring an explicit
614
- // capabilities override.
615
- const keyPackage = await generateKeyPackageWithKey({
616
- credential: makeMLSCredential(identity),
617
- signatureKeyPair: {
618
- signKey: identity.privateKey,
619
- publicKey: identity.publicKey
620
- },
621
- cipherSuite: context.cipherSuite,
622
- capabilities: buildLeafCapabilities(groupInfo.groupContext.extensions, options?.capabilities)
623
- });
624
- const { publicMessage, newState } = await mlsJoinGroupExternal({
625
- context,
626
- groupInfo,
627
- keyPackage: keyPackage.publicPackage,
628
- privateKeys: keyPackage.privatePackage,
629
- resync,
630
- ...authenticatedData != null && {
631
- authenticatedData
632
- }
633
- });
634
- const framedCommit = {
635
- version: protocolVersions.mls10,
636
- wireformat: wireformats.mls_public_message,
637
- publicMessage
638
- };
639
- const commitMessage = encode(mlsMessageEncoder, framedCommit);
640
- const group = new GroupHandle({
641
- state: newState,
642
- credential,
643
- context,
644
- rootCapability,
645
- cache,
646
- resolver: options?.resolver,
647
- commitPolicy: options?.commitPolicy
648
- });
649
- return {
650
- commitMessage,
651
- group
652
- };
653
- }
1
+ export { commitInvite, commitLedgerEntries, createInvite } from './group-commit.js';
2
+ export { createGroup, restoreGroup } from './group-create.js';
3
+ export { createKeyPackageBundle, makeMLSCredential } from './group-credential.js';
4
+ export { CommitRejectedError, GroupHandle } from './group-handle.js';
5
+ export { exportGroupInfo, inspectGroupInfo, readGroupInfoBinding, readMessageEpoch } from './group-info.js';
6
+ export { removeMember } from './group-membership.js';
7
+ export { joinGroupExternal, processWelcome, processWelcomeOnce } from './group-welcome.js';