@kumiai/mls 0.2.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.
@@ -0,0 +1,613 @@
1
+ import { normalizeDID } from '@kokuin/token';
2
+ import { contentTypes, createApplicationMessage, decode, encode, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, wireformats } from 'ts-mls';
3
+ import { readGroupAnchor } from './anchor.js';
4
+ import { parseMLSCredentialIdentity } from './credential.js';
5
+ import { decodeControlEnvelope } from './envelope.js';
6
+ import { foldEnvelope } from './envelope-fold.js';
7
+ import { assertHeadMatches, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, headsMatch, readLedgerHead, readLedgerHeadExtension } from './head.js';
8
+ import { ledgerEntryDigest, verifyLedgerEntry } from './ledger.js';
9
+ import { createMutex } from './mutex.js';
10
+ import { defaultCommitPolicy, MissingLedgerEntriesError } from './policy.js';
11
+ import { foldRoster } from './roster.js';
12
+ /** One serializer per live handle, so its state-mutating operations run one at a
13
+ * time in issue order. Keyed weakly: the entry is collected with the handle, and
14
+ * the handle carries no reference back to it. */ const MUTEXES = new WeakMap();
15
+ export function mutexFor(handle) {
16
+ let mutex = MUTEXES.get(handle);
17
+ if (mutex === undefined) {
18
+ mutex = createMutex();
19
+ MUTEXES.set(handle, mutex);
20
+ }
21
+ return mutex;
22
+ }
23
+ /** Overwrite retired secret buffers ts-mls hands back as `consumed`, so key
24
+ * material does not linger in the heap after the state that used it is replaced. */ function zeroAll(buffers) {
25
+ for (const buffer of buffers)buffer.fill(0);
26
+ }
27
+ /** Thrown by GroupHandle.processMessage when the commit policy rejects an incoming
28
+ * commit. The handle is left at its pre-commit epoch. */ export class CommitRejectedError extends Error {
29
+ #proposals;
30
+ #senderLeafIndex;
31
+ constructor(proposals, senderLeafIndex){
32
+ super('Commit rejected by group commit policy');
33
+ this.name = 'CommitRejectedError';
34
+ this.#proposals = proposals;
35
+ this.#senderLeafIndex = senderLeafIndex;
36
+ }
37
+ get proposals() {
38
+ return this.#proposals;
39
+ }
40
+ get senderLeafIndex() {
41
+ return this.#senderLeafIndex;
42
+ }
43
+ }
44
+ /**
45
+ * Wrap a consumer commit policy to capture a rejected commit's proposals for
46
+ * CommitRejectedError. ts-mls does not surface them on its result, so record them
47
+ * from the callback's own argument on the 'reject' path. Undefined when no policy.
48
+ */ function wrapCommitPolicy(callback, capture) {
49
+ if (callback == null) return undefined;
50
+ return (incoming)=>{
51
+ const action = callback(incoming);
52
+ if (action === 'reject' && incoming.kind === 'commit') {
53
+ capture.rejected = {
54
+ proposals: incoming.proposals,
55
+ senderLeafIndex: incoming.senderLeafIndex == null ? undefined : Number(incoming.senderLeafIndex)
56
+ };
57
+ }
58
+ return action;
59
+ };
60
+ }
61
+ /**
62
+ * Read a PrivateMessage commit's cleartext `authenticatedData`, available before
63
+ * any epoch secret. Returns undefined for anything that is not a PrivateMessage of
64
+ * contentType commit (those keep the pre-envelope path). Narrows the `unknown`
65
+ * frame structurally, not by cast.
66
+ */ function readPrivateCommit(decoded) {
67
+ if (decoded == null || typeof decoded !== 'object') return undefined;
68
+ const frame = decoded;
69
+ if (frame.wireformat !== wireformats.mls_private_message) return undefined;
70
+ const pm = frame.privateMessage;
71
+ if (pm == null || pm.contentType !== contentTypes.commit) return undefined;
72
+ const data = pm.authenticatedData;
73
+ return {
74
+ authenticatedData: data instanceof Uint8Array ? data : new Uint8Array()
75
+ };
76
+ }
77
+ /**
78
+ * Read the DID an external-join commit proves control of. An external join is a
79
+ * PublicMessage from a joining non-member (senderType new_member_commit) carrying a
80
+ * commit; the committer holds no pre-commit leaf, so its DID rides the commit's own
81
+ * UpdatePath leaf credential. Returns undefined for anything else (keeps the
82
+ * pre-envelope path). Returns `{ did: undefined }` when the UpdatePath is absent or
83
+ * the leaf credential does not resolve to a basic-credential DID — cannot be a valid
84
+ * resync, so the caller rejects it. Narrows structurally.
85
+ */ function readExternalCommit(decoded) {
86
+ if (decoded == null || typeof decoded !== 'object') return undefined;
87
+ const frame = decoded;
88
+ if (frame.wireformat !== wireformats.mls_public_message) return undefined;
89
+ const pm = frame.publicMessage;
90
+ if (pm == null || pm.senderType !== senderTypes.new_member_commit) return undefined;
91
+ const content = pm.content;
92
+ if (content == null || content.contentType !== contentTypes.commit) return undefined;
93
+ const commit = content.commit;
94
+ const path = commit?.path;
95
+ if (path == null) return {
96
+ did: undefined
97
+ };
98
+ const leafNode = path.leafNode;
99
+ const credential = leafNode?.credential;
100
+ if (credential == null || !(credential.identity instanceof Uint8Array)) {
101
+ return {
102
+ did: undefined
103
+ };
104
+ }
105
+ try {
106
+ return {
107
+ did: parseMLSCredentialIdentity(credential.identity).id
108
+ };
109
+ } catch {
110
+ return {
111
+ did: undefined
112
+ };
113
+ }
114
+ }
115
+ /**
116
+ * Project a held ledger into the roster. foldRoster drops every non-`group.role`
117
+ * entry by type, so the mixed-type log is fed in whole. Replayed in order, repeats
118
+ * and all: a claim re-enacted at a later position must undo what came between.
119
+ */ function foldLedgerRoster(ledger, anchor, groupID) {
120
+ const entries = ledger.map(({ verified, entryID })=>({
121
+ verified,
122
+ entryID
123
+ }));
124
+ return foldRoster(entries, anchor, groupID);
125
+ }
126
+ /** Mutable wrapper around MLS group state + Enkaku credential. */ export class GroupHandle {
127
+ #state;
128
+ #credential;
129
+ #context;
130
+ #cache;
131
+ #resolver;
132
+ #commitPolicy;
133
+ #resolveLedgerEntries;
134
+ #onLedgerEntries;
135
+ #anchor;
136
+ /** The ordered log of enactments — the ledger as the head chains it. A content id
137
+ * may appear more than once: re-enacting a claim at a later position undoes what
138
+ * came between, which is how a demotion back to a previously-held role works. */ #ledger;
139
+ /** Entry bodies by content id, for resolving the ids an envelope names. A body is
140
+ * the same wherever it appears in the log, so this store is keyed. */ #entryBodies;
141
+ #roster;
142
+ constructor(params){
143
+ this.#state = params.state;
144
+ this.#credential = params.credential;
145
+ this.#context = params.context;
146
+ this.#cache = params.cache;
147
+ this.#resolver = params.resolver;
148
+ this.#commitPolicy = params.commitPolicy;
149
+ this.#resolveLedgerEntries = params.resolveLedgerEntries;
150
+ this.#onLedgerEntries = params.onLedgerEntries;
151
+ // Seed control state from the genesis anchor in the group's GroupContext. Reading
152
+ // it here makes the constructor the single choke no anchorless handle slips
153
+ // through: an absent anchor fails closed rather than installing a permissive roster.
154
+ const anchor = readGroupAnchor(this);
155
+ if (anchor == null) {
156
+ throw new Error('group has no anchor extension; cannot seed a control roster');
157
+ }
158
+ this.#anchor = anchor;
159
+ this.#ledger = [
160
+ ...params.ledger ?? []
161
+ ];
162
+ this.#entryBodies = new Map(this.#ledger.map(({ entryID, token, verified })=>[
163
+ entryID,
164
+ {
165
+ token,
166
+ verified
167
+ }
168
+ ]));
169
+ this.#roster = foldLedgerRoster(this.#ledger, anchor, this.groupID);
170
+ }
171
+ get groupID() {
172
+ return this.#credential.groupID;
173
+ }
174
+ get epoch() {
175
+ return this.#state.groupContext.epoch;
176
+ }
177
+ get treeHash() {
178
+ return this.#state.groupContext.treeHash;
179
+ }
180
+ get credential() {
181
+ return this.#credential;
182
+ }
183
+ get state() {
184
+ return this.#state;
185
+ }
186
+ get context() {
187
+ return this.#context;
188
+ }
189
+ get cache() {
190
+ return this.#cache;
191
+ }
192
+ get resolver() {
193
+ return this.#resolver;
194
+ }
195
+ /** The commit policy enforced by processMessage, if any. Carried onto
196
+ * handles derived from this one (commitInvite/removeMember). */ get commitPolicy() {
197
+ return this.#commitPolicy;
198
+ }
199
+ /** The ledger-entry resolver, carried onto handles derived from this one. */ get resolveLedgerEntries() {
200
+ return this.#resolveLedgerEntries;
201
+ }
202
+ /** The accepted-commit entry sink, carried onto handles derived from this one. */ get onLedgerEntries() {
203
+ return this.#onLedgerEntries;
204
+ }
205
+ /** The genesis anchor seeded into this handle at construction. */ get anchor() {
206
+ return this.#anchor;
207
+ }
208
+ /** The control-ledger log this handle holds, in enactment order, repeats and
209
+ * all. Carried onto handles derived from this one (commitInvite/removeMember). */ get ledger() {
210
+ return this.#ledger;
211
+ }
212
+ /** The ordered signed tokens this handle holds, repeats included — the ledger's
213
+ * canonical persistent/wire form, and the list the authenticated head folds over.
214
+ * Feeds createInvite, restoreGroup, and host persistence. The verified entries are
215
+ * a derived cache with no export form: the only way in is applyLedgerEntries,
216
+ * which re-verifies. */ get ledgerTokens() {
217
+ return this.#ledger.map(({ token })=>token);
218
+ }
219
+ /** The control roster folded from the anchor and every applied ledger entry. */ get roster() {
220
+ return this.#roster;
221
+ }
222
+ /**
223
+ * Verify signed ledger tokens, append the valid ones in the order given, and
224
+ * refold the roster. Tokens that fail verification or whose groupID mismatches are
225
+ * dropped (defensive — the strict admin-issuer enforcement is the commit pre-pass).
226
+ * Every token is re-verified on the way in: no entry enters a ledger unverified,
227
+ * whatever the import path.
228
+ *
229
+ * A token the log already holds is appended again, not skipped: the log records
230
+ * what each commit enacted, not a set of claims, and a repeat is the only way to
231
+ * express a demotion back to a previously-held role. Nothing replays a commit into
232
+ * it (MLS applies each once, restoreGroup replays a token list once, processWelcome
233
+ * folds an invite once). Serialized on the handle's mutex.
234
+ */ async applyLedgerEntries(tokens) {
235
+ return mutexFor(this).run(async ()=>{
236
+ for (const token of tokens){
237
+ const verified = await verifyLedgerEntry(token);
238
+ if (verified == null || verified.entry.groupID !== this.groupID) continue;
239
+ const entryID = ledgerEntryDigest(token);
240
+ this.#ledger.push({
241
+ entryID,
242
+ token,
243
+ verified
244
+ });
245
+ this.#entryBodies.set(entryID, {
246
+ token,
247
+ verified
248
+ });
249
+ }
250
+ this.#roster = foldLedgerRoster(this.#ledger, this.#anchor, this.groupID);
251
+ });
252
+ }
253
+ /**
254
+ * Whether the ledger this handle holds is the whole ledger its GroupContext
255
+ * attests to: the head folded from the ids it holds, in order, against the
256
+ * authenticated `ledger_head`.
257
+ *
258
+ * Purely local — reads this handle's ledger and GroupContext, consults no peer.
259
+ * False means incomplete (e.g. an external-commit rejoin arrives with an *empty*
260
+ * ledger against a live, non-genesis head), and {@link bootstrapLedger} must run
261
+ * before the handle can be trusted to fold a roster or judge a commit.
262
+ *
263
+ * A group with no entries reads true, non-vacuously: the empty fold is the genesis
264
+ * head (a real 32-byte digest bound to this group), which matches only a head that
265
+ * has never moved — exactly a genuinely empty ledger.
266
+ */ async isLedgerComplete() {
267
+ return mutexFor(this).run(async ()=>{
268
+ const authenticated = readLedgerHead(this);
269
+ if (authenticated == null) {
270
+ // No head extension attests to no ledger, so nothing can be shown complete.
271
+ // Report incomplete and let bootstrap fail loudly.
272
+ return false;
273
+ }
274
+ return headsMatch(authenticated.head, computeHead(this.groupID, this.#ledger.map(({ entryID })=>entryID)));
275
+ });
276
+ }
277
+ /**
278
+ * The whole ordered ledger this handle holds, as signed tokens — what a responder
279
+ * serves to a bootstrapping peer. Order is load-bearing: the head is a chain
280
+ * digest, so a permuted list folds to a different head and is rejected.
281
+ */ async getLedger() {
282
+ return mutexFor(this).run(async ()=>this.ledgerTokens);
283
+ }
284
+ /**
285
+ * Install a gathered ledger, verified against the authenticated head before a
286
+ * single entry is folded.
287
+ *
288
+ * The gathered list is the group's WHOLE ledger from genesis, not a delta: a list
289
+ * that reproduces the head this GroupContext carries *is* the entire ledger, in
290
+ * order, and replaces whatever this handle held.
291
+ *
292
+ * Check before fold, structurally: the head is recomputed over the incoming
293
+ * `tokens` while the handle's ledger, entry bodies, and roster are untouched, and
294
+ * the fold's results are installed in one assignment at the end. A rejected ledger
295
+ * writes nothing — no half-applied window, no rollback.
296
+ *
297
+ * Signatures alone do not cover this: a lying responder can hand back genuinely
298
+ * signed, correctly scoped tokens with one demotion omitted or two transposed —
299
+ * every signature verifies, yet the folded roster contains an admin the group
300
+ * demoted. Omission and reordering are exactly what the head chain protects and
301
+ * signatures do not. The bound: **a lying responder can withhold, never rewrite.**
302
+ *
303
+ * Throws {@link LedgerIncompleteError} on a head mismatch; the caller drops that
304
+ * responder and tries the next.
305
+ */ async bootstrapLedger(tokens) {
306
+ return mutexFor(this).run(async ()=>{
307
+ const authenticated = readLedgerHead(this);
308
+ if (authenticated == null) {
309
+ throw new Error('bootstrapLedger: the group has no ledger head extension');
310
+ }
311
+ // The gate. Nothing below touches the handle until the last three statements,
312
+ // and nothing above reads the tokens except for their content ids.
313
+ const entryIDs = tokens.map(ledgerEntryDigest);
314
+ assertHeadMatches(authenticated.head, computeHead(this.groupID, entryIDs));
315
+ const log = [];
316
+ for(let index = 0; index < tokens.length; index++){
317
+ const token = tokens[index];
318
+ const verified = await verifyLedgerEntry(token);
319
+ if (verified == null || verified.entry.groupID !== this.groupID) {
320
+ // Unreachable past the gate — the chain digests the token bytes, so an
321
+ // unverifiable or cross-group token cannot sit at a position the head
322
+ // covers. Fails closed anyway.
323
+ throw new Error('bootstrapLedger: the gathered ledger holds an unverifiable or cross-group entry');
324
+ }
325
+ log.push({
326
+ entryID: entryIDs[index],
327
+ token,
328
+ verified
329
+ });
330
+ }
331
+ this.#ledger = log;
332
+ this.#entryBodies = new Map(log.map(({ entryID, token, verified })=>[
333
+ entryID,
334
+ {
335
+ token,
336
+ verified
337
+ }
338
+ ]));
339
+ this.#roster = foldLedgerRoster(log, this.#anchor, this.groupID);
340
+ });
341
+ }
342
+ get memberCount() {
343
+ return this.#state.ratchetTree.filter((node)=>node != null && node.nodeType === nodeTypes.leaf).length;
344
+ }
345
+ *#iterateMembers() {
346
+ const tree = this.#state.ratchetTree;
347
+ for(let i = 0; i < tree.length; i++){
348
+ const node = tree[i];
349
+ if (node != null && node.nodeType === nodeTypes.leaf) {
350
+ const credential = node.leaf.credential;
351
+ if ('identity' in credential) {
352
+ let parsed;
353
+ try {
354
+ parsed = parseMLSCredentialIdentity(credential.identity);
355
+ } catch {
356
+ continue;
357
+ }
358
+ yield {
359
+ leafIndex: i / 2,
360
+ id: parsed.id
361
+ };
362
+ }
363
+ }
364
+ }
365
+ }
366
+ findMemberLeafIndex(id) {
367
+ const targetNorm = normalizeDID(id);
368
+ for (const member of this.#iterateMembers()){
369
+ if (normalizeDID(member.id) === targetNorm) return member.leafIndex;
370
+ }
371
+ return undefined;
372
+ }
373
+ /**
374
+ * The group's current members from the ratchet tree, in ascending leaf-index
375
+ * order. Leaves whose credential identity fails to parse are skipped (like
376
+ * findMemberLeafIndex). Reflects current #state — call before and after
377
+ * processMessage to diff a commit's membership change.
378
+ */ listMembers() {
379
+ return [
380
+ ...this.#iterateMembers()
381
+ ];
382
+ }
383
+ /**
384
+ * Encrypt an application message for the group at this handle's current epoch,
385
+ * returning framed wire bytes. A handle a commit has already superseded (see
386
+ * {@link commitInvite}, {@link removeMember}, {@link commitLedgerEntries}) must not
387
+ * be reused to send — it silently emits at the now-stale epoch. Adopt the commit's
388
+ * `newGroup` and encrypt on that.
389
+ */ async encrypt(plaintext) {
390
+ return mutexFor(this).run(async ()=>{
391
+ const { newState, message, consumed } = await createApplicationMessage({
392
+ context: this.#context,
393
+ state: this.#state,
394
+ message: plaintext
395
+ });
396
+ this.#state = newState;
397
+ zeroAll(consumed);
398
+ return encode(mlsMessageEncoder, message);
399
+ });
400
+ }
401
+ /**
402
+ * The async pre-pass feeding the synchronous ts-mls commit callback, run before
403
+ * mlsProcessMessage. For anything that is not a PrivateMessage commit it just
404
+ * resolves the caller policy, wraps it for rejected-proposal capture, and applies
405
+ * nothing on accept.
406
+ *
407
+ * For a PrivateMessage commit it decodes the control envelope, resolves and
408
+ * verifies the entry bodies it names, folds a candidate roster off the pre-commit
409
+ * state, and precomputes the pure inputs the sync callback reads. That callback is
410
+ * a pure lookup: decode/fold failure is a hard reject; else a caller policy wins,
411
+ * and with none the anchored default policy runs. Missing entry bodies with no
412
+ * resolver throw MissingLedgerEntriesError HERE — before mlsProcessMessage — so the
413
+ * handle stays at its pre-commit epoch.
414
+ */ async #prepareCommitPipeline(decoded, opts) {
415
+ const callerPolicy = opts?.commitPolicy ?? this.#commitPolicy;
416
+ const capture = {};
417
+ const commit = readPrivateCommit(decoded);
418
+ let externalCommitDID;
419
+ let isCommitMessage = commit != null;
420
+ if (commit == null) {
421
+ const external = readExternalCommit(decoded);
422
+ if (external != null) {
423
+ externalCommitDID = external.did;
424
+ isCommitMessage = true;
425
+ }
426
+ // else: a standalone by-reference Proposal (or an application message / a
427
+ // frame ts-mls will not call back on). Fall through with the roster unchanged
428
+ // so `combined` judges a kind:'proposal' incoming under the same
429
+ // defaultCommitPolicy rows applied to a commit's proposals; a non-admin's
430
+ // authority-bearing proposal is rejected on receipt and never stored.
431
+ // Application messages never reach the callback, so this is inert for them.
432
+ }
433
+ let precomputedReject = false;
434
+ let candidateRoster = this.#roster;
435
+ let surfaced = [];
436
+ let acceptedEntries = [];
437
+ let envelopeIDs = [];
438
+ if (isCommitMessage) {
439
+ if (commit == null) {
440
+ // An external-join commit carries no control envelope: resolves nothing,
441
+ // folds nothing, never moves the head; candidate roster is unchanged. Its
442
+ // only precomputed reject is an unresolvable committer DID (no UpdatePath /
443
+ // bad credential), which cannot be a valid resync.
444
+ precomputedReject = externalCommitDID === undefined;
445
+ } else {
446
+ const env = decodeControlEnvelope(commit.authenticatedData);
447
+ if (!env.ok) {
448
+ precomputedReject = true;
449
+ } else {
450
+ const ids = env.envelope.entries ?? [];
451
+ envelopeIDs = ids;
452
+ const resolved = new Map();
453
+ const missing = [];
454
+ for (const id of ids){
455
+ const held = this.#entryBodies.get(id);
456
+ if (held != null) {
457
+ resolved.set(id, {
458
+ ...held,
459
+ entryID: id
460
+ });
461
+ } else {
462
+ missing.push(id);
463
+ }
464
+ }
465
+ if (missing.length > 0) {
466
+ if (this.#resolveLedgerEntries == null) {
467
+ throw new MissingLedgerEntriesError(missing);
468
+ }
469
+ const tokens = await this.#resolveLedgerEntries(missing);
470
+ for (const token of tokens){
471
+ const id = ledgerEntryDigest(token);
472
+ // Content-addressing binds the untrusted body to the requested id.
473
+ if (resolved.has(id) || !missing.includes(id)) continue;
474
+ const verified = await verifyLedgerEntry(token);
475
+ if (verified == null) continue;
476
+ resolved.set(id, {
477
+ token,
478
+ verified,
479
+ entryID: id
480
+ });
481
+ }
482
+ const stillMissing = missing.filter((id)=>!resolved.has(id));
483
+ if (stillMissing.length > 0) {
484
+ throw new MissingLedgerEntriesError(stillMissing);
485
+ }
486
+ }
487
+ const ordered = ids.map((id)=>{
488
+ const input = resolved.get(id);
489
+ if (input == null) throw new MissingLedgerEntriesError([
490
+ id
491
+ ]);
492
+ return input;
493
+ });
494
+ const foldResult = foldEnvelope(this.#roster, ordered, this.groupID);
495
+ if (!foldResult.ok) {
496
+ precomputedReject = true;
497
+ } else {
498
+ candidateRoster = foldResult.roster;
499
+ surfaced = foldResult.surfaced;
500
+ acceptedEntries = ordered;
501
+ }
502
+ }
503
+ }
504
+ }
505
+ const context = buildCommitPolicyContext(this, {
506
+ baseRoster: this.#roster,
507
+ candidateRoster,
508
+ entryIDs: envelopeIDs,
509
+ ...externalCommitDID !== undefined && {
510
+ externalCommitDID
511
+ }
512
+ });
513
+ const combined = (incoming)=>{
514
+ // A decode/fold failure is a hard reject even under a caller policy: the
515
+ // ledger the commit depends on is unresolvable or malformed.
516
+ if (precomputedReject) return 'reject';
517
+ if (callerPolicy != null) return callerPolicy(incoming);
518
+ return defaultCommitPolicy(incoming, context);
519
+ };
520
+ const applyOnAccept = ()=>{
521
+ // Appended, never deduped: the log records what this commit enacted, at the
522
+ // position the head chained it.
523
+ for (const { token, verified, entryID } of acceptedEntries){
524
+ this.#ledger.push({
525
+ entryID,
526
+ token,
527
+ verified
528
+ });
529
+ this.#entryBodies.set(entryID, {
530
+ token,
531
+ verified
532
+ });
533
+ }
534
+ this.#roster = candidateRoster;
535
+ if (surfaced.length > 0) this.#onLedgerEntries?.(surfaced);
536
+ };
537
+ return {
538
+ callback: wrapCommitPolicy(combined, capture),
539
+ capture,
540
+ applyOnAccept
541
+ };
542
+ }
543
+ /**
544
+ * Process a received MLS message (Commit, Proposal, or application). Accepts
545
+ * wire-form bytes (preferred, e.g. from commitInvite/removeMember) or a pre-decoded
546
+ * ts-mls object (legacy). Param widens to `unknown` because `Uint8Array | unknown`
547
+ * collapses to `unknown`; the runtime `instanceof` selects the decode path.
548
+ */ async processMessage(message, opts) {
549
+ let decoded = message;
550
+ if (message instanceof Uint8Array) {
551
+ const parsed = decode(mlsMessageDecoder, message);
552
+ if (parsed == null) {
553
+ throw new Error('processMessage: failed to decode MLSMessage');
554
+ }
555
+ decoded = parsed;
556
+ }
557
+ return mutexFor(this).run(async ()=>{
558
+ const { callback, capture, applyOnAccept } = await this.#prepareCommitPipeline(decoded, opts);
559
+ const result = await mlsProcessMessage({
560
+ context: this.#context,
561
+ state: this.#state,
562
+ message: decoded,
563
+ ...callback != null && {
564
+ callback
565
+ }
566
+ });
567
+ this.#state = result.newState;
568
+ zeroAll(result.consumed);
569
+ if (result.kind === 'newState' && result.actionTaken === 'reject') {
570
+ throw new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex);
571
+ }
572
+ if (result.kind === 'applicationMessage') {
573
+ return result.message;
574
+ }
575
+ applyOnAccept();
576
+ return null;
577
+ });
578
+ }
579
+ }
580
+ /** Build the CommitPolicyContext both the receive gate and the send-side pending
581
+ * filter judge against, so the two always agree. `entryIDs` are the ledger entry
582
+ * ids this commit enacts (drives the expected head); `candidateRoster` is the
583
+ * post-fold roster receivers install. */ export function buildCommitPolicyContext(handle, args) {
584
+ const leafToDID = new Map();
585
+ for (const member of handle.listMembers())leafToDID.set(member.leafIndex, member.id);
586
+ const headExt = readLedgerHeadExtension(handle);
587
+ const currentHead = headExt != null && headExt.extensionData instanceof Uint8Array ? decodeLedgerHead(headExt.extensionData) : null;
588
+ const expectedHeadExtensionData = currentHead == null ? new Uint8Array() : encodeLedgerHead(extendHead(currentHead.head, args.entryIDs));
589
+ return {
590
+ baseRoster: args.baseRoster,
591
+ candidateRoster: args.candidateRoster,
592
+ didOfLeaf: (leafIndex)=>leafToDID.get(leafIndex),
593
+ currentExtensions: handle.state.groupContext.extensions,
594
+ expectedHeadExtensionData,
595
+ commitEnactsEntries: args.entryIDs.length > 0,
596
+ ...args.externalCommitDID !== undefined && {
597
+ externalCommitDID: args.externalCommitDID
598
+ }
599
+ };
600
+ }
601
+ /** Build the handle a commit hands back: the post-commit state, everything else inherited. */ export function deriveGroup(group, state) {
602
+ return new GroupHandle({
603
+ state,
604
+ credential: group.credential,
605
+ context: group.context,
606
+ ledger: group.ledger,
607
+ cache: group.cache,
608
+ resolver: group.resolver,
609
+ commitPolicy: group.commitPolicy,
610
+ resolveLedgerEntries: group.resolveLedgerEntries,
611
+ onLedgerEntries: group.onLedgerEntries
612
+ });
613
+ }
@@ -0,0 +1,57 @@
1
+ import type { GroupHandle } from './group-handle.js';
2
+ /**
3
+ * Read the MLS epoch from a framed message's cleartext header without decrypting.
4
+ * Advisory only — the header epoch is unauthenticated; use it to drop stale / buffer
5
+ * future messages before the authenticated processMessage. Returns undefined for
6
+ * non-message or undecodable bytes.
7
+ *
8
+ * Total by contract (a safe pre-filter over untrusted Delivery Service bytes): never
9
+ * throws. ts-mls `decode` throws on some malformed inputs (e.g. oversized); that is
10
+ * caught and treated as "not a message".
11
+ */
12
+ export declare function readMessageEpoch(bytes: Uint8Array): bigint | undefined;
13
+ export type InspectGroupInfoResult = {
14
+ /** The GroupInfo's epoch, read from its groupContext. */
15
+ epoch: bigint;
16
+ /** The GroupInfo's ratchet-tree hash, read from its groupContext. Compare for
17
+ * equality against a known post-commit state's treeHash to confirm canonical
18
+ * convergence (same epoch + same treeHash ⟺ same group state). */
19
+ treeHash: Uint8Array;
20
+ };
21
+ /**
22
+ * Read a framed MLSMessage(GroupInfo)'s epoch and ratchet-tree hash without joining
23
+ * or mutating state. Used to confirm an external-resync Commit was canonically
24
+ * accepted: compare the returned (epoch, treeHash) against the rejoiner's own
25
+ * post-commit state. Equal ⟹ this device's Commit won the epoch; unequal ⟹ another
26
+ * won and the rejoin must retry.
27
+ *
28
+ * Structural read only — does NOT verify the GroupInfo signature; the caller obtains
29
+ * the bytes over the group's authorized channel. Unlike readMessageEpoch, this THROWS
30
+ * on malformed input: an already-trusted malformed GroupInfo is a programming error.
31
+ */
32
+ export declare function inspectGroupInfo(groupInfoBytes: Uint8Array): InspectGroupInfoResult;
33
+ export type GroupInfoBinding = {
34
+ /** The group id the GroupInfo's GroupContext names, decoded from its bytes. */
35
+ groupID: string;
36
+ /** The genesis-anchor GroupContext extension's raw data, or null when absent.
37
+ * Byte-compared against the requester's own immutable anchor, never re-encoded. */
38
+ anchorExtensionData: Uint8Array | null;
39
+ };
40
+ /**
41
+ * Read a framed MLSMessage(GroupInfo)'s group-identifying bindings without joining:
42
+ * the group id its GroupContext names and the raw genesis-anchor extension bytes. A
43
+ * recovering peer compares both against the group it believes it is healing, so a
44
+ * GroupInfo for another group or with a different anchor is refused before it can
45
+ * steer an external join. Structural read only; does not verify the signature. Throws
46
+ * on malformed input, like {@link inspectGroupInfo}.
47
+ */
48
+ export declare function readGroupInfoBinding(groupInfoBytes: Uint8Array): GroupInfoBinding;
49
+ export type ExportGroupInfoParams = {
50
+ group: GroupHandle;
51
+ };
52
+ export type ExportGroupInfoResult = {
53
+ /** Framed MLSMessage(GroupInfo) bytes. Self-describing with protocol
54
+ * version + wireformat + GroupInfo (external_pub + ratchet tree embedded). */
55
+ groupInfo: Uint8Array;
56
+ };
57
+ export declare function exportGroupInfo(params: ExportGroupInfoParams): Promise<ExportGroupInfoResult>;