@kumiai/mls 0.2.0 → 0.3.1

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.
package/lib/group.js CHANGED
@@ -1,1194 +1,7 @@
1
- import { createInMemoryDIDCache, isPeer4, normalizeDID } from '@kokuin/token';
2
- import { contentTypes, 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, senderTypes, wireformats } from 'ts-mls';
3
- import { buildCurrentGroupAnchorExtension, controlCapabilities, decodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, LEDGER_HEAD_EXTENSION_TYPE, readGroupAnchor } from './anchor.js';
4
- import { createDIDAuthenticationService } from './authentication.js';
5
- import { sanitizeRatchetTree } from './codec.js';
6
- import { parseMLSCredentialIdentity } from './credential.js';
7
- import { nobleCryptoProvider } from './crypto.js';
8
- import { decodeControlEnvelope, encodeControlEnvelope } from './envelope.js';
9
- import { foldEnvelope } from './envelope-fold.js';
10
- import { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, readLedgerHead, readLedgerHeadExtension } from './head.js';
11
- import { ledgerEntryDigest, signLedgerEntry, verifyLedgerEntry } from './ledger.js';
12
- import { createMutex } from './mutex.js';
13
- import { defaultCommitPolicy, MissingLedgerEntriesError } from './policy.js';
14
- import { foldRoster, ROLE_ENTRY_TYPE } from './roster.js';
15
- const DEFAULT_CIPHERSUITE = 'MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519';
16
- /** One serializer per live handle, so its state-mutating operations run one at a
17
- * time in issue order. Keyed weakly: the entry is collected with the handle, and
18
- * the handle carries no reference back to it. */ const MUTEXES = new WeakMap();
19
- function mutexFor(handle) {
20
- let mutex = MUTEXES.get(handle);
21
- if (mutex === undefined) {
22
- mutex = createMutex();
23
- MUTEXES.set(handle, mutex);
24
- }
25
- return mutex;
26
- }
27
- /** Overwrite retired secret buffers ts-mls hands back as `consumed`, so key
28
- * material does not linger in the heap after the state that used it is replaced. */ function zeroAll(buffers) {
29
- for (const buffer of buffers)buffer.fill(0);
30
- }
31
- async function resolveMlsContext(options) {
32
- const name = options?.ciphersuiteName ?? DEFAULT_CIPHERSUITE;
33
- const cipherSuite = await getCiphersuiteImpl(name, options?.cryptoProvider ?? nobleCryptoProvider);
34
- const authService = createDIDAuthenticationService();
35
- return {
36
- cipherSuite,
37
- authService
38
- };
39
- }
40
- export function makeMLSCredential(identity) {
41
- const id = identity.id;
42
- const isPeer = isPeer4(id);
43
- if (isPeer && !('longForm' in identity && typeof identity.longForm === 'string')) {
44
- throw new Error('peer:4 identity is missing longForm; only identities from createIdentity can be used as MLS members');
45
- }
46
- const payload = {
47
- id
48
- };
49
- if (isPeer) {
50
- payload.longForm = identity.longForm;
51
- }
52
- return {
53
- credentialType: defaultCredentialTypes.basic,
54
- identity: new TextEncoder().encode(JSON.stringify(payload))
55
- };
56
- }
57
- /**
58
- * Thrown by GroupHandle.processMessage when the active commit policy rejects
59
- * an incoming commit. The handle is left at its pre-commit epoch.
60
- */ export class CommitRejectedError extends Error {
61
- #proposals;
62
- #senderLeafIndex;
63
- constructor(proposals, senderLeafIndex){
64
- super('Commit rejected by group commit policy');
65
- this.name = 'CommitRejectedError';
66
- this.#proposals = proposals;
67
- this.#senderLeafIndex = senderLeafIndex;
68
- }
69
- get proposals() {
70
- return this.#proposals;
71
- }
72
- get senderLeafIndex() {
73
- return this.#senderLeafIndex;
74
- }
75
- }
76
- /**
77
- * Wrap a consumer commit policy so the rejected commit's proposals are captured
78
- * for CommitRejectedError. ts-mls's ProcessMessageResult does not surface the
79
- * rejected proposals on the result, so we record them from the callback's own
80
- * argument on the 'reject' path onto `capture.rejected`. Returns undefined when
81
- * no policy is set.
82
- */ function wrapCommitPolicy(callback, capture) {
83
- if (callback == null) return undefined;
84
- return (incoming)=>{
85
- const action = callback(incoming);
86
- if (action === 'reject' && incoming.kind === 'commit') {
87
- capture.rejected = {
88
- proposals: incoming.proposals,
89
- senderLeafIndex: incoming.senderLeafIndex == null ? undefined : Number(incoming.senderLeafIndex)
90
- };
91
- }
92
- return action;
93
- };
94
- }
95
- /**
96
- * Read the cleartext commit fields a PrivateMessage commit exposes before any
97
- * epoch secret is available: its `authenticatedData` carrier. Returns undefined
98
- * for anything that is not a PrivateMessage of contentType commit (application
99
- * message, proposal, PublicMessage, or a pre-decoded non-frame) — those keep the
100
- * pre-envelope code path. The decoded frame is widened to `unknown` on both
101
- * public entry points, so this narrows structurally rather than by cast.
102
- */ function readPrivateCommit(decoded) {
103
- if (decoded == null || typeof decoded !== 'object') return undefined;
104
- const frame = decoded;
105
- if (frame.wireformat !== wireformats.mls_private_message) return undefined;
106
- const pm = frame.privateMessage;
107
- if (pm == null || pm.contentType !== contentTypes.commit) return undefined;
108
- const data = pm.authenticatedData;
109
- return {
110
- authenticatedData: data instanceof Uint8Array ? data : new Uint8Array()
111
- };
112
- }
113
- /**
114
- * Read the DID an external-join commit proves control of. An external join is a
115
- * PublicMessage whose sender is a joining non-member (senderType
116
- * new_member_commit) carrying a commit; the committer holds no pre-commit leaf,
117
- * so its DID rides the commit's own UpdatePath leaf credential. Returns undefined
118
- * for anything that is not such a commit — those keep the pre-envelope path.
119
- * Returns `{ did: undefined }` for an external commit whose UpdatePath is absent
120
- * or whose leaf credential does not resolve to a basic-credential DID: it cannot
121
- * be a valid resync, so the caller rejects it. Narrows the `unknown` frame
122
- * structurally, mirroring readPrivateCommit / readMessageEpoch.
123
- */ function readExternalCommit(decoded) {
124
- if (decoded == null || typeof decoded !== 'object') return undefined;
125
- const frame = decoded;
126
- if (frame.wireformat !== wireformats.mls_public_message) return undefined;
127
- const pm = frame.publicMessage;
128
- if (pm == null || pm.senderType !== senderTypes.new_member_commit) return undefined;
129
- const content = pm.content;
130
- if (content == null || content.contentType !== contentTypes.commit) return undefined;
131
- const commit = content.commit;
132
- const path = commit?.path;
133
- if (path == null) return {
134
- did: undefined
135
- };
136
- const leafNode = path.leafNode;
137
- const credential = leafNode?.credential;
138
- if (credential == null || !(credential.identity instanceof Uint8Array)) {
139
- return {
140
- did: undefined
141
- };
142
- }
143
- try {
144
- return {
145
- did: parseMLSCredentialIdentity(credential.identity).id
146
- };
147
- } catch {
148
- return {
149
- did: undefined
150
- };
151
- }
152
- }
153
- /**
154
- * Project a held ledger into the roster. foldRoster is the role projection: it
155
- * drops every non-`group.role` entry by type, so the mixed-type ledger is fed in
156
- * as role inputs and the fold filters. The log is replayed in order, repeats and
157
- * all: a claim re-enacted at a later position must undo what came between.
158
- */ function foldLedgerRoster(ledger, anchor, groupID) {
159
- const entries = ledger.map(({ verified, entryID })=>({
160
- verified,
161
- entryID
162
- }));
163
- return foldRoster(entries, anchor, groupID);
164
- }
165
- /**
166
- * Mutable wrapper around MLS group state + Enkaku credential.
167
- */ export class GroupHandle {
168
- #state;
169
- #credential;
170
- #context;
171
- #cache;
172
- #resolver;
173
- #commitPolicy;
174
- #resolveLedgerEntries;
175
- #onLedgerEntries;
176
- #anchor;
177
- /** The ordered log of enactments — the ledger as the head chains it. The same
178
- * content id may appear more than once: a claim re-enacted at a later position
179
- * undoes what came between, which is how a demotion back to a previously-held
180
- * role expresses itself at all. */ #ledger;
181
- /** Entry bodies by content id, for resolving the ids an envelope names. A body
182
- * is the same body wherever it appears in the log, so this store is keyed. */ #entryBodies;
183
- #roster;
184
- constructor(params){
185
- this.#state = params.state;
186
- this.#credential = params.credential;
187
- this.#context = params.context;
188
- this.#cache = params.cache;
189
- this.#resolver = params.resolver;
190
- this.#commitPolicy = params.commitPolicy;
191
- this.#resolveLedgerEntries = params.resolveLedgerEntries;
192
- this.#onLedgerEntries = params.onLedgerEntries;
193
- // Seed the control state from the genesis anchor baked into the group's own
194
- // GroupContext. The anchor survives every epoch, so reading it here makes the
195
- // constructor the single choke that no anchorless handle can slip through: an
196
- // absent anchor fails closed rather than installing a permissive roster.
197
- const anchor = readGroupAnchor(this);
198
- if (anchor == null) {
199
- throw new Error('group has no anchor extension; cannot seed a control roster');
200
- }
201
- this.#anchor = anchor;
202
- this.#ledger = [
203
- ...params.ledger ?? []
204
- ];
205
- this.#entryBodies = new Map(this.#ledger.map(({ entryID, token, verified })=>[
206
- entryID,
207
- {
208
- token,
209
- verified
210
- }
211
- ]));
212
- this.#roster = foldLedgerRoster(this.#ledger, anchor, this.groupID);
213
- }
214
- get groupID() {
215
- return this.#credential.groupID;
216
- }
217
- get epoch() {
218
- return this.#state.groupContext.epoch;
219
- }
220
- get treeHash() {
221
- return this.#state.groupContext.treeHash;
222
- }
223
- get credential() {
224
- return this.#credential;
225
- }
226
- get state() {
227
- return this.#state;
228
- }
229
- get context() {
230
- return this.#context;
231
- }
232
- get cache() {
233
- return this.#cache;
234
- }
235
- get resolver() {
236
- return this.#resolver;
237
- }
238
- /** The commit policy enforced by processMessage, if any. Carried onto
239
- * handles derived from this one (commitInvite/removeMember). */ get commitPolicy() {
240
- return this.#commitPolicy;
241
- }
242
- /** The ledger-entry resolver, carried onto handles derived from this one. */ get resolveLedgerEntries() {
243
- return this.#resolveLedgerEntries;
244
- }
245
- /** The accepted-commit entry sink, carried onto handles derived from this one. */ get onLedgerEntries() {
246
- return this.#onLedgerEntries;
247
- }
248
- /** The genesis anchor seeded into this handle at construction. */ get anchor() {
249
- return this.#anchor;
250
- }
251
- /** The control-ledger log this handle holds, in enactment order, repeats and
252
- * all. Carried onto handles derived from this one (commitInvite/removeMember). */ get ledger() {
253
- return this.#ledger;
254
- }
255
- /** The ordered signed tokens this handle holds, including repeats — the ledger's
256
- * canonical persistent and wire form, and the list the authenticated head folds
257
- * over. Feeds createInvite, restoreGroup, and host persistence. The verified
258
- * entries are a derived cache with no export form: the only way into a ledger is
259
- * applyLedgerEntries, which re-verifies. */ get ledgerTokens() {
260
- return this.#ledger.map(({ token })=>token);
261
- }
262
- /** The control roster folded from the anchor and every applied ledger entry. */ get roster() {
263
- return this.#roster;
264
- }
265
- /**
266
- * Verify signed ledger tokens, append the valid ones to the log in the order
267
- * given, and refold the roster. Tokens that fail verification or whose groupID
268
- * does not match the group are dropped (defensive — this is the low-level apply
269
- * primitive; the commit pre-pass does the strict admin-issuer enforcement).
270
- * Every token is re-verified on the way in: no entry enters a ledger unverified,
271
- * whatever the import path.
272
- *
273
- * A token the log already holds is appended again rather than skipped. The log
274
- * is an ordered record of what each commit enacted, not a set of claims, and a
275
- * repeat is the only way to express a demotion back to a previously-held role.
276
- * Nothing replays a commit into it: MLS applies each commit exactly once,
277
- * restoreGroup replays a token list once, and processWelcome folds an invite once.
278
- * Runs serialized on the handle's mutex, like the other state-mutating operations.
279
- */ async applyLedgerEntries(tokens) {
280
- return mutexFor(this).run(async ()=>{
281
- for (const token of tokens){
282
- const verified = await verifyLedgerEntry(token);
283
- if (verified == null || verified.entry.groupID !== this.groupID) continue;
284
- const entryID = ledgerEntryDigest(token);
285
- this.#ledger.push({
286
- entryID,
287
- token,
288
- verified
289
- });
290
- this.#entryBodies.set(entryID, {
291
- token,
292
- verified
293
- });
294
- }
295
- this.#roster = foldLedgerRoster(this.#ledger, this.#anchor, this.groupID);
296
- });
297
- }
298
- get memberCount() {
299
- return this.#state.ratchetTree.filter((node)=>node != null && node.nodeType === nodeTypes.leaf).length;
300
- }
301
- *#iterateMembers() {
302
- const tree = this.#state.ratchetTree;
303
- for(let i = 0; i < tree.length; i++){
304
- const node = tree[i];
305
- if (node != null && node.nodeType === nodeTypes.leaf) {
306
- const credential = node.leaf.credential;
307
- if ('identity' in credential) {
308
- let parsed;
309
- try {
310
- parsed = parseMLSCredentialIdentity(credential.identity);
311
- } catch {
312
- continue;
313
- }
314
- yield {
315
- leafIndex: i / 2,
316
- id: parsed.id
317
- };
318
- }
319
- }
320
- }
321
- }
322
- findMemberLeafIndex(id) {
323
- const targetNorm = normalizeDID(id);
324
- for (const member of this.#iterateMembers()){
325
- if (normalizeDID(member.id) === targetNorm) return member.leafIndex;
326
- }
327
- return undefined;
328
- }
329
- /**
330
- * Enumerate the group's current members from the ratchet tree, in ascending
331
- * leaf-index order. Leaves whose credential identity fails to parse are skipped
332
- * (same tolerance as findMemberLeafIndex). Reflects the handle's current #state
333
- * — call before and after processMessage to diff a commit's membership change.
334
- */ listMembers() {
335
- return [
336
- ...this.#iterateMembers()
337
- ];
338
- }
339
- /**
340
- * Encrypt an application message for the group, returning framed wire bytes.
341
- * Encrypts at this handle's current epoch. A handle a commit has already
342
- * superseded (see {@link commitInvite}, {@link removeMember},
343
- * {@link commitLedgerEntries}) must not be reused to send — doing so silently
344
- * emits an application message at the now-stale epoch; adopt the commit's
345
- * `newGroup` and call `encrypt` on that instead.
346
- */ async encrypt(plaintext) {
347
- return mutexFor(this).run(async ()=>{
348
- const { newState, message, consumed } = await createApplicationMessage({
349
- context: this.#context,
350
- state: this.#state,
351
- message: plaintext
352
- });
353
- this.#state = newState;
354
- zeroAll(consumed);
355
- return encode(mlsMessageEncoder, message);
356
- });
357
- }
358
- /**
359
- * The async pre-pass feeding the synchronous ts-mls commit callback.
360
- * processMessage runs this before mlsProcessMessage, since it may receive a
361
- * commit. For anything that is not a PrivateMessage commit (application
362
- * message, proposal, PublicMessage, pre-decoded non-frame) it does
363
- * exactly what the code did before this step — resolve the caller policy, wrap
364
- * it for the rejected-proposal capture, and apply nothing on accept.
365
- *
366
- * For a PrivateMessage commit it decodes the control envelope, resolves and
367
- * verifies the entry bodies the envelope names, folds a candidate roster off
368
- * the pre-commit state, and precomputes the pure inputs the sync callback
369
- * reads. The returned callback is a pure lookup over that precomputed state:
370
- * a decode/fold failure is a hard reject; otherwise a caller policy wins the
371
- * permission decision, and with no caller policy the anchored default policy
372
- * runs. Missing entry bodies with no resolver throw MissingLedgerEntriesError
373
- * here — before mlsProcessMessage — so the handle stays at its pre-commit epoch.
374
- */ async #prepareCommitPipeline(decoded, opts) {
375
- const callerPolicy = opts?.commitPolicy ?? this.#commitPolicy;
376
- const capture = {};
377
- const commit = readPrivateCommit(decoded);
378
- let externalCommitDID;
379
- let isCommitMessage = commit != null;
380
- if (commit == null) {
381
- const external = readExternalCommit(decoded);
382
- if (external != null) {
383
- externalCommitDID = external.did;
384
- isCommitMessage = true;
385
- }
386
- // else: a standalone by-reference Proposal (or an application message / a
387
- // frame ts-mls will not call back on). Fall through with the roster
388
- // unchanged so `combined` judges a kind:'proposal' incoming under the same
389
- // defaultCommitPolicy rows a receiver applies to a commit's proposals; a
390
- // non-admin's authority-bearing proposal is rejected on receipt and never
391
- // stored. Application messages never reach the callback, so this is inert
392
- // for them.
393
- }
394
- let precomputedReject = false;
395
- let candidateRoster = this.#roster;
396
- let surfaced = [];
397
- let acceptedEntries = [];
398
- let envelopeIDs = [];
399
- if (isCommitMessage) {
400
- if (commit == null) {
401
- // An external-join commit carries no control envelope: it resolves nothing,
402
- // folds nothing, enacts no ledger entries, and never moves the head. The
403
- // candidate roster is the current roster unchanged. Its only precomputed
404
- // reject is an unresolvable committer DID (no UpdatePath / bad credential),
405
- // which cannot be a valid resync.
406
- precomputedReject = externalCommitDID === undefined;
407
- } else {
408
- const env = decodeControlEnvelope(commit.authenticatedData);
409
- if (!env.ok) {
410
- precomputedReject = true;
411
- } else {
412
- const ids = env.envelope.entries ?? [];
413
- envelopeIDs = ids;
414
- const resolved = new Map();
415
- const missing = [];
416
- for (const id of ids){
417
- const held = this.#entryBodies.get(id);
418
- if (held != null) {
419
- resolved.set(id, {
420
- ...held,
421
- entryID: id
422
- });
423
- } else {
424
- missing.push(id);
425
- }
426
- }
427
- if (missing.length > 0) {
428
- if (this.#resolveLedgerEntries == null) {
429
- throw new MissingLedgerEntriesError(missing);
430
- }
431
- const tokens = await this.#resolveLedgerEntries(missing);
432
- for (const token of tokens){
433
- const id = ledgerEntryDigest(token);
434
- // Content-addressing binds the untrusted body to the requested id.
435
- if (resolved.has(id) || !missing.includes(id)) continue;
436
- const verified = await verifyLedgerEntry(token);
437
- if (verified == null) continue;
438
- resolved.set(id, {
439
- token,
440
- verified,
441
- entryID: id
442
- });
443
- }
444
- const stillMissing = missing.filter((id)=>!resolved.has(id));
445
- if (stillMissing.length > 0) {
446
- throw new MissingLedgerEntriesError(stillMissing);
447
- }
448
- }
449
- const ordered = ids.map((id)=>{
450
- const input = resolved.get(id);
451
- if (input == null) throw new MissingLedgerEntriesError([
452
- id
453
- ]);
454
- return input;
455
- });
456
- const foldResult = foldEnvelope(this.#roster, ordered, this.groupID);
457
- if (!foldResult.ok) {
458
- precomputedReject = true;
459
- } else {
460
- candidateRoster = foldResult.roster;
461
- surfaced = foldResult.surfaced;
462
- acceptedEntries = ordered;
463
- }
464
- }
465
- }
466
- }
467
- const context = buildCommitPolicyContext(this, {
468
- baseRoster: this.#roster,
469
- candidateRoster,
470
- entryIDs: envelopeIDs,
471
- ...externalCommitDID !== undefined && {
472
- externalCommitDID
473
- }
474
- });
475
- const combined = (incoming)=>{
476
- // A decode/fold failure is a hard reject even under a caller policy: the
477
- // ledger the commit depends on is unresolvable or malformed.
478
- if (precomputedReject) return 'reject';
479
- if (callerPolicy != null) return callerPolicy(incoming);
480
- return defaultCommitPolicy(incoming, context);
481
- };
482
- const applyOnAccept = ()=>{
483
- // Appended, never deduped: the log records what this commit enacted, at the
484
- // position the head chained it.
485
- for (const { token, verified, entryID } of acceptedEntries){
486
- this.#ledger.push({
487
- entryID,
488
- token,
489
- verified
490
- });
491
- this.#entryBodies.set(entryID, {
492
- token,
493
- verified
494
- });
495
- }
496
- this.#roster = candidateRoster;
497
- if (surfaced.length > 0) this.#onLedgerEntries?.(surfaced);
498
- };
499
- return {
500
- callback: wrapCommitPolicy(combined, capture),
501
- capture,
502
- applyOnAccept
503
- };
504
- }
505
- /**
506
- * Process a received MLS message (Commit, Proposal, or application).
507
- *
508
- * Accepts either wire-form bytes (the preferred input — framed MLSMessage
509
- * `Uint8Array`, e.g. from commitInvite/removeMember) or a pre-decoded ts-mls
510
- * message object (legacy path). The param type widens to `unknown` because
511
- * `Uint8Array | unknown` collapses to `unknown` in TypeScript; the runtime
512
- * `instanceof` check selects the decode path.
513
- */ async processMessage(message, opts) {
514
- let decoded = message;
515
- if (message instanceof Uint8Array) {
516
- const parsed = decode(mlsMessageDecoder, message);
517
- if (parsed == null) {
518
- throw new Error('processMessage: failed to decode MLSMessage');
519
- }
520
- decoded = parsed;
521
- }
522
- return mutexFor(this).run(async ()=>{
523
- const { callback, capture, applyOnAccept } = await this.#prepareCommitPipeline(decoded, opts);
524
- const result = await mlsProcessMessage({
525
- context: this.#context,
526
- state: this.#state,
527
- message: decoded,
528
- ...callback != null && {
529
- callback
530
- }
531
- });
532
- this.#state = result.newState;
533
- zeroAll(result.consumed);
534
- if (result.kind === 'newState' && result.actionTaken === 'reject') {
535
- throw new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex);
536
- }
537
- if (result.kind === 'applicationMessage') {
538
- return result.message;
539
- }
540
- applyOnAccept();
541
- return null;
542
- });
543
- }
544
- }
545
- // ---------------------------------------------------------------------------
546
- // Lifecycle functions
547
- // ---------------------------------------------------------------------------
548
- /**
549
- * Build the leaf-node capabilities for a member joining or creating a group.
550
- * RFC 9420 requires a member's leaf to advertise every non-default GroupContext
551
- * extension type the group uses; we derive that set from the group's extensions
552
- * so it cannot desync. This applies equally to a creator (extensions from the
553
- * group being created) and to an external rejoiner (extensions from the
554
- * GroupInfo it resyncs against) — a rejoining leaf that advertises only the
555
- * defaults is rejected by ts-mls with "client does not support every extension
556
- * in the GroupContext". An explicit `override` (GroupOptions.capabilities) wins
557
- * verbatim.
558
- */ function buildLeafCapabilities(extensions, override) {
559
- if (override != null) return override;
560
- const base = defaultCapabilities();
561
- const types = new Set([
562
- ...base.extensions,
563
- ...extensions.map((e)=>e.extensionType)
564
- ]);
565
- return {
566
- ...base,
567
- extensions: [
568
- ...types
569
- ]
570
- };
571
- }
572
- /**
573
- * Create a new MLS group. The identity becomes the sole member and admin.
574
- */ export async function createGroup(identity, groupID, options) {
575
- const cache = options?.cache ?? createInMemoryDIDCache();
576
- const context = await resolveMlsContext(options);
577
- // Every group is anchored at creation: the creator is the epoch-0 admin, and
578
- // the ledger head starts at genesis. A caller-supplied anchor (e.g. one
579
- // carrying an `app` payload) is left untouched — the caller owns its contents.
580
- // Its `creatorDID` coupling to the creating identity is validated below; a
581
- // decode failure here is not this guard's concern and is left to the
582
- // downstream fail-closed decode in the GroupHandle constructor.
583
- const extensions = [
584
- ...options?.extensions ?? []
585
- ];
586
- const suppliedAnchorExtension = extensions.find((ext)=>ext.extensionType === GROUP_ANCHOR_EXTENSION_TYPE);
587
- if (suppliedAnchorExtension != null) {
588
- const suppliedAnchorData = suppliedAnchorExtension.extensionData;
589
- const suppliedAnchor = suppliedAnchorData instanceof Uint8Array ? decodeGroupAnchor(suppliedAnchorData) : null;
590
- if (suppliedAnchor != null && normalizeDID(suppliedAnchor.creatorDID) !== normalizeDID(identity.id)) {
591
- throw new Error(`createGroup: the anchor's creatorDID (${suppliedAnchor.creatorDID}) must be the creating identity (${identity.id})`);
592
- }
593
- }
594
- if (!extensions.some((ext)=>ext.extensionType === GROUP_ANCHOR_EXTENSION_TYPE)) {
595
- extensions.push(buildCurrentGroupAnchorExtension(identity.id));
596
- }
597
- if (!extensions.some((ext)=>ext.extensionType === LEDGER_HEAD_EXTENSION_TYPE)) {
598
- extensions.push(buildLedgerHeadExtension(genesisHead(groupID)));
599
- }
600
- const statePromise = generateKeyPackageWithKey({
601
- credential: makeMLSCredential(identity),
602
- signatureKeyPair: {
603
- signKey: identity.privateKey,
604
- publicKey: identity.publicKey
605
- },
606
- cipherSuite: context.cipherSuite,
607
- capabilities: buildLeafCapabilities(extensions, options?.capabilities)
608
- }).then((keyPackage)=>{
609
- return mlsCreateGroup({
610
- context,
611
- groupId: new TextEncoder().encode(groupID),
612
- keyPackage: keyPackage.publicPackage,
613
- privateKeyPackage: keyPackage.privatePackage,
614
- extensions
615
- });
616
- });
617
- const state = await statePromise;
618
- const credential = {
619
- id: identity.id,
620
- groupID
621
- };
622
- const group = new GroupHandle({
623
- state,
624
- credential,
625
- context,
626
- cache,
627
- resolver: options?.resolver,
628
- commitPolicy: options?.commitPolicy,
629
- resolveLedgerEntries: options?.resolveLedgerEntries,
630
- onLedgerEntries: options?.onLedgerEntries
631
- });
632
- return {
633
- group,
634
- credential
635
- };
636
- }
637
- export async function restoreGroup(params) {
638
- const cache = params.options?.cache ?? createInMemoryDIDCache();
639
- // Construction reseeds `{creator: 'admin'}` from the anchor in the restored
640
- // state — an anchorless state throws here, the same fail-closed guard.
641
- const group = new GroupHandle({
642
- state: params.state,
643
- credential: params.credential,
644
- context: await resolveMlsContext(params.options),
645
- cache,
646
- resolver: params.options?.resolver,
647
- commitPolicy: params.options?.commitPolicy,
648
- resolveLedgerEntries: params.options?.resolveLedgerEntries,
649
- onLedgerEntries: params.options?.onLedgerEntries
650
- });
651
- await group.applyLedgerEntries(params.ledgerEntries ?? []);
652
- return group;
653
- }
654
- /**
655
- * Create an invite for a new member.
656
- * Does NOT add them to the group — call commitInvite with their key package to do that.
657
- *
658
- * Only an admin may invite: a role entry from a non-admin issuer is dropped by every
659
- * receiver's fold, so refusing here turns a silent downstream commit rejection into a
660
- * local error.
661
- */ export async function createInvite(params) {
662
- const { group, identity, recipientDID, permission } = params;
663
- if (group.roster.roles.get(normalizeDID(identity.id)) !== 'admin') {
664
- throw new Error('createInvite: the inviter must be an admin in the group roster');
665
- }
666
- // The role entry naming the invitee. Its issuer is the inviter (authenticated by
667
- // the token signature) and its value is the permission granted.
668
- const roleToken = await signLedgerEntry(identity, {
669
- type: ROLE_ENTRY_TYPE,
670
- groupID: group.groupID,
671
- subject: recipientDID,
672
- value: permission
673
- });
674
- const invite = {
675
- groupID: group.groupID,
676
- inviterID: identity.id,
677
- // The whole log, the new role entry last: a joiner handed only its own entry
678
- // would never learn of a role change made before its invite, and would reject
679
- // every commit by an admin promoted in the meantime — a permanent fork nothing
680
- // in the protocol re-sends. The new entry must fold after the history it depends
681
- // on, hence last. Re-granting a role the log already carries appends that entry a
682
- // second time, which is a legal re-enactment, not a duplicate to elide. The joiner
683
- // still folds from the anchor, so the inviter cannot promote anyone by padding
684
- // this list.
685
- ledgerEntries: [
686
- ...group.ledgerTokens,
687
- roleToken
688
- ]
689
- };
690
- return {
691
- invite
692
- };
693
- }
694
- /**
695
- * The GroupContext extension list a commit installs when it enacts `entryIDs`: the
696
- * group's current list with only the ledger-head extension replaced by the head
697
- * extended by those ids, in envelope order. Every other extension — the anchor above
698
- * all — is the verbatim object out of the current GroupContext, never a re-encode of
699
- * a decoded value, because the receiving policy byte-compares the anchor.
700
- */ function extensionsWithHead(group, entryIDs) {
701
- const current = readLedgerHead(group);
702
- if (current == null) {
703
- throw new Error('group has no ledger head extension; it cannot enact ledger entries');
704
- }
705
- const next = buildLedgerHeadExtension(extendHead(current.head, entryIDs));
706
- return group.state.groupContext.extensions.map((ext)=>ext.extensionType === LEDGER_HEAD_EXTENSION_TYPE ? next : ext);
707
- }
708
- /** Build the CommitPolicyContext both the receive gate and the send-side pending
709
- * filter judge against, so the two always agree. `entryIDs` are the ledger entry
710
- * ids this commit enacts (drives the expected head); `candidateRoster` is the
711
- * post-fold roster receivers install. */ function buildCommitPolicyContext(handle, args) {
712
- const leafToDID = new Map();
713
- for (const member of handle.listMembers())leafToDID.set(member.leafIndex, member.id);
714
- const headExt = readLedgerHeadExtension(handle);
715
- const currentHead = headExt != null && headExt.extensionData instanceof Uint8Array ? decodeLedgerHead(headExt.extensionData) : null;
716
- const expectedHeadExtensionData = currentHead == null ? new Uint8Array() : encodeLedgerHead(extendHead(currentHead.head, args.entryIDs));
717
- return {
718
- baseRoster: args.baseRoster,
719
- candidateRoster: args.candidateRoster,
720
- didOfLeaf: (leafIndex)=>leafToDID.get(leafIndex),
721
- currentExtensions: handle.state.groupContext.extensions,
722
- expectedHeadExtensionData,
723
- commitEnactsEntries: args.entryIDs.length > 0,
724
- ...args.externalCommitDID !== undefined && {
725
- externalCommitDID: args.externalCommitDID
726
- }
727
- };
728
- }
729
- /**
730
- * The one place a commit carrying control-ledger entries is built: `commitInvite`,
731
- * `removeMember`, and `commitLedgerEntries` all route through it, so the envelope and
732
- * the head can never drift apart.
733
- *
734
- * `enacted` is exactly what this commit enacts — the caller decides, and the caller is
735
- * the only one that can: entries are enacted by *position* in the log, so an entry whose
736
- * content the log already carries is a legitimate re-enactment (a demotion back to a
737
- * previously-held role is precisely that) and must not be filtered out by content.
738
- *
739
- * The envelope names only what this commit enacts, never the whole history: replaying the
740
- * history would re-judge every past entry against the present roster, and a grant issued
741
- * by a since-demoted admin would read as coming from a non-admin, freezing every group
742
- * that ever rotated its admins.
743
- *
744
- * When `enacted` is non-empty the commit also carries a group-context-extensions proposal
745
- * advancing the ledger head by exactly those ids, in envelope order. An empty list moves
746
- * no head and carries no envelope.
747
- */ async function commitWithEntries(group, extraProposals, enacted, ratchetTreeExtension = false) {
748
- // Same reason createInvite guards the inviter: a non-admin's commit is rejected by
749
- // every receiver, so fail here rather than emitting a commit nobody will apply.
750
- if (group.roster.roles.get(normalizeDID(group.credential.id)) !== 'admin') {
751
- throw new Error('the committer must be an admin in the group roster');
752
- }
753
- // Fold the entries exactly as every receiver will, and refuse to author a commit the
754
- // group would reject. Without this the write path fails *open*: the committer advances
755
- // its own log and head while every receiver rejects the commit, forking itself off the
756
- // group. Being an admin is not enough — an entry's own issuer must still hold authority
757
- // at the position it lands in, so a token signed by a since-demoted admin is dead paper
758
- // no matter who commits it.
759
- const inputs = [];
760
- for (const token of enacted){
761
- const verified = await verifyLedgerEntry(token);
762
- if (verified == null) {
763
- throw new Error('cannot enact a ledger entry whose signature does not verify');
764
- }
765
- inputs.push({
766
- verified,
767
- entryID: ledgerEntryDigest(token)
768
- });
769
- }
770
- const fold = foldEnvelope(group.roster, inputs, group.groupID);
771
- if (!fold.ok) {
772
- throw new Error(`cannot enact ledger entry ${fold.entryID}: ${fold.reason}`);
773
- }
774
- const entryIDs = enacted.map(ledgerEntryDigest);
775
- // Filter the pending-proposal set the committer would otherwise absorb: ts-mls folds every
776
- // unappliedProposal into the commit, so a non-admin's pending proposal would ride this commit
777
- // and every peer would reject the whole thing — a single member could stall the group. Judge
778
- // each pending proposal against the same defaultCommitPolicy and the same context receivers
779
- // build for this commit, dropping any the group would reject.
780
- const filterContext = buildCommitPolicyContext(group, {
781
- baseRoster: group.roster,
782
- candidateRoster: fold.roster,
783
- entryIDs
784
- });
785
- const keptPending = {};
786
- for (const [ref, pws] of Object.entries(group.state.unappliedProposals)){
787
- if (defaultCommitPolicy({
788
- kind: 'proposal',
789
- proposal: pws
790
- }, filterContext) !== 'reject') {
791
- keptPending[ref] = pws;
792
- }
793
- }
794
- const commitState = {
795
- ...group.state,
796
- unappliedProposals: keptPending
797
- };
798
- const proposals = [
799
- ...extraProposals
800
- ];
801
- if (entryIDs.length > 0) {
802
- proposals.push({
803
- proposalType: defaultProposalTypes.group_context_extensions,
804
- groupContextExtensions: {
805
- extensions: extensionsWithHead(group, entryIDs)
806
- }
807
- });
808
- }
809
- return await createCommit({
810
- context: group.context,
811
- state: commitState,
812
- extraProposals: proposals,
813
- ...ratchetTreeExtension && {
814
- ratchetTreeExtension: true
815
- },
816
- ...entryIDs.length > 0 && {
817
- authenticatedData: encodeControlEnvelope({
818
- v: 1,
819
- entries: entryIDs
820
- })
821
- }
822
- });
823
- }
824
- /**
825
- * The entries an invite adds beyond the committer's own log: everything past the log's
826
- * length. Positional, never by content — a re-granted role is the same token the log
827
- * already carries at an earlier position, and narrowing by content would drop the very
828
- * entry the invite exists to enact.
829
- *
830
- * Positional narrowing is only sound when the invite's list *begins with* the
831
- * committer's log, so that is asserted rather than assumed: an invite built against a
832
- * different history would mis-slice, and the commit would move the head by ids that do
833
- * not follow the group's own — corrupting the chain for every receiver.
834
- */ function entriesAddedByInvite(group, invite) {
835
- const held = group.ledgerTokens;
836
- if (invite.ledgerEntries.length < held.length || held.some((token, index)=>invite.ledgerEntries[index] !== token)) {
837
- throw new Error("commitInvite: the invite's ledger does not extend this group's own");
838
- }
839
- return invite.ledgerEntries.slice(held.length);
840
- }
841
- /** Build the handle a commit hands back: the post-commit state, everything else inherited. */ function deriveGroup(group, state) {
842
- return new GroupHandle({
843
- state,
844
- credential: group.credential,
845
- context: group.context,
846
- ledger: group.ledger,
847
- cache: group.cache,
848
- resolver: group.resolver,
849
- commitPolicy: group.commitPolicy,
850
- resolveLedgerEntries: group.resolveLedgerEntries,
851
- onLedgerEntries: group.onLedgerEntries
852
- });
853
- }
854
- /**
855
- * The admin write path for the control ledger: a commit that carries no membership
856
- * proposal, only the entries it enacts and the head move that covers them. This is how
857
- * an admin promotes, demotes, or writes any other entry type — an entry that never
858
- * rides a commit is invisible to the head, and a joiner recomputing the head would
859
- * read the group's history as doctored.
860
- *
861
- * Enacts exactly `tokens`, at the end of the log — including one whose content the log
862
- * already carries, which is how an admin is demoted back to a role they previously held.
863
- * Rejects an empty `tokens` list: a commit that enacts nothing has no reason to be
864
- * authored here.
865
- *
866
- * Reads `group`'s state and returns a NEW derived handle (`newGroup`); it never
867
- * advances `group` itself. The caller must adopt `newGroup` — never reuse `group` —
868
- * before issuing the next commit: two commits issued from the same source handle
869
- * both frame at that handle's epoch and diverge. The per-handle mutex only
870
- * serializes concurrent calls against one handle; it does not make it safe to
871
- * produce a second commit from a handle a prior commit has already superseded.
872
- */ export async function commitLedgerEntries(group, tokens) {
873
- return mutexFor(group).run(async ()=>{
874
- if (tokens.length === 0) {
875
- throw new Error('commitLedgerEntries: no ledger entries to commit');
876
- }
877
- const result = await commitWithEntries(group, [], tokens);
878
- const newGroup = deriveGroup(group, result.newState);
879
- await newGroup.applyLedgerEntries(tokens);
880
- return {
881
- commitMessage: encode(mlsMessageEncoder, result.commit),
882
- newGroup,
883
- epoch: newGroup.epoch
884
- };
885
- });
886
- }
887
- /**
888
- * Commit an invite by adding the invitee's key package to the group.
889
- * Produces an MLS Commit + Welcome.
890
- *
891
- * The invite's ledger entries are enacted by this commit: their content ids ride in
892
- * the commit's control envelope and the commit advances the ledger head by exactly
893
- * those ids, so every receiver folds the invitee's role entry into its roster as it
894
- * applies the Add. The envelope carries ids, not bodies — a receiver that holds
895
- * neither the entry nor a `resolveLedgerEntries` resolver throws
896
- * MissingLedgerEntriesError on this commit.
897
- *
898
- * The invite itself carries the group's whole history — a joiner has nothing to fold
899
- * it onto — but only the entries it adds beyond that history ride the commit; see
900
- * {@link entriesAddedByInvite} and {@link commitWithEntries}.
901
- *
902
- * Reads `group`'s state and returns a NEW derived handle (`newGroup`); it never
903
- * advances `group` itself. The caller must adopt `newGroup` — never reuse `group` —
904
- * before issuing the next commit: two commits issued from the same source handle
905
- * both frame at that handle's epoch and diverge. The per-handle mutex only
906
- * serializes concurrent calls against one handle; it does not make it safe to
907
- * produce a second commit from a handle a prior commit has already superseded.
908
- */ export async function commitInvite(group, keyPackage, invite) {
909
- return mutexFor(group).run(async ()=>{
910
- if (invite.groupID !== group.groupID) {
911
- throw new Error(`commitInvite: invite is for group ${invite.groupID}, not ${group.groupID}`);
912
- }
913
- const enacted = entriesAddedByInvite(group, invite);
914
- const addProposal = {
915
- proposalType: defaultProposalTypes.add,
916
- add: {
917
- keyPackage
918
- }
919
- };
920
- const result = await commitWithEntries(group, [
921
- addProposal
922
- ], enacted, true);
923
- const newGroup = deriveGroup(group, result.newState);
924
- if (result.welcome == null) {
925
- throw new Error('commitInvite: expected a Welcome message for the add proposal');
926
- }
927
- // The entries this commit enacts are now part of the group's ledger.
928
- await newGroup.applyLedgerEntries(enacted);
929
- return {
930
- commitMessage: encode(mlsMessageEncoder, result.commit),
931
- welcomeMessage: encode(mlsMessageEncoder, result.welcome),
932
- newGroup,
933
- epoch: newGroup.epoch
934
- };
935
- });
936
- }
937
- /**
938
- * Process a Welcome message to join a group.
939
- */ export async function processWelcome(params) {
940
- const { identity, invite, welcome, keyPackageBundle, ratchetTree, options } = params;
941
- const cache = options?.cache ?? createInMemoryDIDCache();
942
- const context = await resolveMlsContext(options);
943
- // A Welcome is only this member's when the invite carries a role entry naming
944
- // them: an invite minted for someone else is not an invitation to join.
945
- const selfDID = normalizeDID(identity.id);
946
- let namesSelf = false;
947
- for (const token of invite.ledgerEntries){
948
- const verified = await verifyLedgerEntry(token);
949
- if (verified != null && verified.entry.type === ROLE_ENTRY_TYPE && verified.entry.groupID === invite.groupID && normalizeDID(verified.entry.subject) === selfDID) {
950
- namesSelf = true;
951
- break;
952
- }
953
- }
954
- if (!namesSelf) {
955
- throw new Error('processWelcome: the invite carries no role entry naming this identity');
956
- }
957
- let resolvedWelcome = welcome;
958
- if (welcome instanceof Uint8Array) {
959
- const decoded = decode(mlsMessageDecoder, welcome);
960
- if (decoded == null || decoded.wireformat !== wireformats.mls_welcome) {
961
- throw new Error('processWelcome: expected a framed MLSMessage(Welcome)');
962
- }
963
- resolvedWelcome = decoded.welcome;
964
- }
965
- const sanitizedTree = Array.isArray(ratchetTree) ? sanitizeRatchetTree(ratchetTree) : ratchetTree;
966
- const state = await mlsJoinGroup({
967
- context,
968
- welcome: resolvedWelcome,
969
- keyPackage: keyPackageBundle.publicPackage,
970
- privateKeys: keyPackageBundle.privatePackage,
971
- ...sanitizedTree != null && {
972
- ratchetTree: sanitizedTree
973
- }
974
- });
975
- const credential = {
976
- id: identity.id,
977
- groupID: invite.groupID
978
- };
979
- const group = new GroupHandle({
980
- state,
981
- credential,
982
- context,
983
- cache,
984
- resolver: options?.resolver,
985
- commitPolicy: options?.commitPolicy,
986
- resolveLedgerEntries: options?.resolveLedgerEntries,
987
- onLedgerEntries: options?.onLedgerEntries
988
- });
989
- // Every ledger entry reaches the group inside a commit that extends the head by its
990
- // id, so the head authenticated in the joined GroupContext is the fold from genesis
991
- // over the group's entries, in order. Recompute it over the entries the inviter
992
- // supplied: an omitted, reordered, or truncated list cannot reproduce it. Checked
993
- // before folding, so an incomplete ledger never reaches the roster.
994
- const authenticated = readLedgerHead(group);
995
- if (authenticated == null) {
996
- throw new Error('processWelcome: the group has no ledger head extension');
997
- }
998
- assertHeadMatches(authenticated.head, computeHead(invite.groupID, invite.ledgerEntries.map(ledgerEntryDigest)));
999
- // Fold the invite's entries: the roster is seeded from the anchor, and the fold
1000
- // grants authority only to an admin-so-far, so a member-signed entry cannot
1001
- // promote anyone even though applyLedgerEntries itself is the permissive primitive.
1002
- await group.applyLedgerEntries(invite.ledgerEntries);
1003
- return {
1004
- group,
1005
- credential
1006
- };
1007
- }
1008
- /**
1009
- * Remove a member from the group. Advances the epoch and rotates keys.
1010
- *
1011
- * Removal must demote: a receiver rejects a Remove whose target is still `admin` in
1012
- * the roster the commit's entries fold to. So removing an admin means riding the
1013
- * demotion entry on the same commit — pass it as `ledgerEntries`. The entry is signed
1014
- * by the caller, who holds the identity; this only carries it.
1015
- *
1016
- * Reads `group`'s state and returns a NEW derived handle (`newGroup`); it never
1017
- * advances `group` itself. The caller must adopt `newGroup` — never reuse `group` —
1018
- * before issuing the next commit: two commits issued from the same source handle
1019
- * both frame at that handle's epoch and diverge. The per-handle mutex only
1020
- * serializes concurrent calls against one handle; it does not make it safe to
1021
- * produce a second commit from a handle a prior commit has already superseded.
1022
- */ export async function removeMember(group, leafIndex, ledgerEntries) {
1023
- return mutexFor(group).run(async ()=>{
1024
- const removeProposal = {
1025
- proposalType: defaultProposalTypes.remove,
1026
- remove: {
1027
- removed: leafIndex
1028
- }
1029
- };
1030
- const enacted = ledgerEntries ?? [];
1031
- const result = await commitWithEntries(group, [
1032
- removeProposal
1033
- ], enacted);
1034
- const newGroup = deriveGroup(group, result.newState);
1035
- await newGroup.applyLedgerEntries(enacted);
1036
- return {
1037
- commitMessage: encode(mlsMessageEncoder, result.commit),
1038
- newGroup,
1039
- epoch: newGroup.epoch
1040
- };
1041
- });
1042
- }
1043
- /**
1044
- * Read the MLS epoch from a framed handshake/application message's cleartext
1045
- * header, without decrypting. Advisory only — the header epoch is unauthenticated;
1046
- * use it to drop stale / buffer future messages before the authenticated
1047
- * processMessage. Returns undefined for non-message or undecodable bytes.
1048
- *
1049
- * Total by contract: this is a safe pre-filter over bytes arriving from an
1050
- * untrusted Delivery Service, so it never throws. ts-mls `decode` throws (e.g.
1051
- * CodecError on input larger than its max size) rather than returning undefined
1052
- * for some malformed inputs; that is caught and treated as "not a message".
1053
- */ export function readMessageEpoch(bytes) {
1054
- const message = (()=>{
1055
- try {
1056
- return decode(mlsMessageDecoder, bytes);
1057
- } catch {
1058
- return undefined;
1059
- }
1060
- })();
1061
- if (message == null) return undefined;
1062
- if (message.wireformat === wireformats.mls_private_message) {
1063
- return message.privateMessage.epoch;
1064
- }
1065
- if (message.wireformat === wireformats.mls_public_message) {
1066
- return message.publicMessage.content.epoch;
1067
- }
1068
- return undefined;
1069
- }
1070
- /**
1071
- * Non-destructively inspect a framed MLSMessage(GroupInfo) — read its epoch and
1072
- * ratchet-tree hash without joining or mutating any state. Used to confirm an
1073
- * external-resync Commit was canonically accepted: compare the returned
1074
- * (epoch, treeHash) for equality against the rejoiner's own post-commit state
1075
- * (GroupHandle.epoch / GroupHandle.treeHash). Equal ⟹ this device's Commit won
1076
- * the epoch; unequal ⟹ another Commit won and the rejoin must retry.
1077
- *
1078
- * Structural read only: it does NOT verify the GroupInfo signature. The caller
1079
- * is expected to have obtained the bytes over the group's authorized channel.
1080
- * Unlike readMessageEpoch (a total pre-filter over untrusted DS bytes), this
1081
- * THROWS on malformed input — a malformed already-trusted GroupInfo is a
1082
- * programming error, not expected traffic.
1083
- */ export function inspectGroupInfo(groupInfoBytes) {
1084
- const message = decode(mlsMessageDecoder, groupInfoBytes);
1085
- if (message == null) {
1086
- throw new Error('Invalid groupInfo: failed to decode MLSMessage');
1087
- }
1088
- if (message.wireformat !== wireformats.mls_group_info) {
1089
- throw new Error(`Invalid groupInfo: expected wireformat mls_group_info, got ${String(message.wireformat)}`);
1090
- }
1091
- const { groupContext } = message.groupInfo;
1092
- return {
1093
- epoch: groupContext.epoch,
1094
- treeHash: groupContext.treeHash
1095
- };
1096
- }
1097
- /**
1098
- * Generate a key package for joining groups.
1099
- */ export async function createKeyPackageBundle(identity, options) {
1100
- const { cipherSuite } = await resolveMlsContext(options);
1101
- const result = await generateKeyPackageWithKey({
1102
- credential: makeMLSCredential(identity),
1103
- signatureKeyPair: {
1104
- signKey: identity.privateKey,
1105
- publicKey: identity.publicKey
1106
- },
1107
- cipherSuite,
1108
- // An invitee leaf must advertise the control extension types or ts-mls
1109
- // refuses to add it to an anchored group. An explicit override still wins.
1110
- capabilities: options?.capabilities ?? controlCapabilities()
1111
- });
1112
- return {
1113
- ...result,
1114
- ownerDID: identity.id
1115
- };
1116
- }
1117
- export async function exportGroupInfo(params) {
1118
- const groupInfo = await createGroupInfoWithExternalPubAndRatchetTree(params.group.state, [], params.group.context.cipherSuite);
1119
- const framed = {
1120
- version: protocolVersions.mls10,
1121
- wireformat: wireformats.mls_group_info,
1122
- groupInfo
1123
- };
1124
- return {
1125
- groupInfo: encode(mlsMessageEncoder, framed)
1126
- };
1127
- }
1128
- export async function joinGroupExternal(params) {
1129
- const { identity, groupInfo: groupInfoBytes, credential, resync, options, authenticatedData } = params;
1130
- // Guard: resync replaces the caller's own prior leaf, so the rejoining identity
1131
- // must match the credential it presents. On a mismatch ts-mls rejects the
1132
- // external commit downstream (it finds no prior leaf matching the KeyPackage and
1133
- // throws); reject early here with a clearer error. This is a friendly precheck,
1134
- // not the security boundary — eviction completeness rests on ts-mls requiring a
1135
- // matching prior leaf in the resynced tree, which a removed member no longer has.
1136
- if (normalizeDID(identity.id) !== normalizeDID(credential.id)) {
1137
- throw new Error(`joinGroupExternal: identity.id (${identity.id}) must match credential.id (${credential.id}) for resync`);
1138
- }
1139
- const cache = options?.cache ?? createInMemoryDIDCache();
1140
- const context = await resolveMlsContext(options);
1141
- const message = decode(mlsMessageDecoder, groupInfoBytes);
1142
- if (message == null) {
1143
- throw new Error('Invalid groupInfo: failed to decode MLSMessage');
1144
- }
1145
- if (message.wireformat !== wireformats.mls_group_info) {
1146
- throw new Error(`Invalid groupInfo: expected wireformat mls_group_info, got ${String(message.wireformat)}`);
1147
- }
1148
- // Discriminated-union narrow via the literal wireformat tag — no cast needed.
1149
- const { groupInfo } = message;
1150
- // The rejoining leaf must advertise every GroupContext extension the group
1151
- // uses (e.g. a genesis-anchor extension), or ts-mls rejects the external
1152
- // join with "client does not support every extension in the GroupContext".
1153
- // Derive them from the GroupInfo being resynced against, honoring an explicit
1154
- // capabilities override.
1155
- const keyPackage = await generateKeyPackageWithKey({
1156
- credential: makeMLSCredential(identity),
1157
- signatureKeyPair: {
1158
- signKey: identity.privateKey,
1159
- publicKey: identity.publicKey
1160
- },
1161
- cipherSuite: context.cipherSuite,
1162
- capabilities: buildLeafCapabilities(groupInfo.groupContext.extensions, options?.capabilities)
1163
- });
1164
- const { publicMessage, newState } = await mlsJoinGroupExternal({
1165
- context,
1166
- groupInfo,
1167
- keyPackage: keyPackage.publicPackage,
1168
- privateKeys: keyPackage.privatePackage,
1169
- resync,
1170
- ...authenticatedData != null && {
1171
- authenticatedData
1172
- }
1173
- });
1174
- const framedCommit = {
1175
- version: protocolVersions.mls10,
1176
- wireformat: wireformats.mls_public_message,
1177
- publicMessage
1178
- };
1179
- const commitMessage = encode(mlsMessageEncoder, framedCommit);
1180
- const group = new GroupHandle({
1181
- state: newState,
1182
- credential,
1183
- context,
1184
- cache,
1185
- resolver: options?.resolver,
1186
- commitPolicy: options?.commitPolicy,
1187
- resolveLedgerEntries: options?.resolveLedgerEntries,
1188
- onLedgerEntries: options?.onLedgerEntries
1189
- });
1190
- return {
1191
- commitMessage,
1192
- group
1193
- };
1194
- }
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';