@kumiai/mls 0.12.4 → 0.13.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.
Files changed (66) hide show
  1. package/lib/anchor.d.ts +6 -2
  2. package/lib/anchor.js +1 -1
  3. package/lib/authentication.d.ts +8 -3
  4. package/lib/authentication.js +139 -46
  5. package/lib/capability.js +16 -7
  6. package/lib/controller-ingest.d.ts +14 -2
  7. package/lib/controller-ingest.js +15 -8
  8. package/lib/controller-log.d.ts +12 -6
  9. package/lib/controller-log.js +29 -15
  10. package/lib/crypto.d.ts +8 -1
  11. package/lib/crypto.js +23 -11
  12. package/lib/device-proof.d.ts +2 -1
  13. package/lib/device-proof.js +2 -1
  14. package/lib/embedded-resolver.d.ts +7 -2
  15. package/lib/embedded-resolver.js +16 -6
  16. package/lib/envelope-fold.d.ts +3 -2
  17. package/lib/envelope-fold.js +14 -6
  18. package/lib/fold.d.ts +17 -3
  19. package/lib/fold.js +9 -3
  20. package/lib/group-commit.d.ts +11 -2
  21. package/lib/group-commit.js +76 -32
  22. package/lib/group-context.d.ts +3 -2
  23. package/lib/group-context.js +10 -4
  24. package/lib/group-create.d.ts +5 -1
  25. package/lib/group-create.js +36 -14
  26. package/lib/group-credential.d.ts +13 -3
  27. package/lib/group-credential.js +17 -6
  28. package/lib/group-device.d.ts +32 -22
  29. package/lib/group-device.js +66 -51
  30. package/lib/group-handle.d.ts +84 -30
  31. package/lib/group-handle.js +368 -154
  32. package/lib/group-lifecycle.d.ts +44 -11
  33. package/lib/group-lifecycle.js +193 -85
  34. package/lib/group-membership.d.ts +6 -1
  35. package/lib/group-membership.js +2 -2
  36. package/lib/group-welcome.d.ts +5 -1
  37. package/lib/group-welcome.js +34 -10
  38. package/lib/head.d.ts +25 -5
  39. package/lib/head.js +17 -8
  40. package/lib/history.d.ts +14 -3
  41. package/lib/history.js +8 -5
  42. package/lib/index.d.ts +27 -1
  43. package/lib/key-package-codec.d.ts +4 -1
  44. package/lib/key-package-codec.js +1 -1
  45. package/lib/ledger.d.ts +14 -6
  46. package/lib/ledger.js +56 -19
  47. package/lib/lifecycle-proof.d.ts +5 -4
  48. package/lib/lifecycle-proof.js +111 -51
  49. package/lib/lifecycle.d.ts +18 -9
  50. package/lib/lifecycle.js +184 -81
  51. package/lib/member-root.d.ts +54 -15
  52. package/lib/member-root.js +115 -53
  53. package/lib/policy.d.ts +5 -1
  54. package/lib/policy.js +1 -1
  55. package/lib/recovery-verdict.d.ts +12 -3
  56. package/lib/recovery-verdict.js +56 -22
  57. package/lib/recovery.d.ts +20 -5
  58. package/lib/recovery.js +117 -46
  59. package/lib/registry.d.ts +46 -10
  60. package/lib/registry.js +64 -38
  61. package/lib/roster.d.ts +7 -1
  62. package/lib/roster.js +18 -7
  63. package/lib/secret-tree.d.ts +5 -1
  64. package/lib/secret-tree.js +1 -1
  65. package/lib/types.d.ts +4 -1
  66. package/package.json +9 -5
@@ -27,8 +27,21 @@ import { readSenderLeafIndex } from './sender-data.js';
27
27
  * the handle carries no reference back to it. */ const MUTEXES = new WeakMap();
28
28
  // Module-private construction path: only clone can supply an already-folded snapshot.
29
29
  const CLONE_SOURCE = Symbol('cloneSource');
30
+ const FOLDED_CONTROL = Symbol('foldedControl');
31
+ async function computeAdmission(view) {
32
+ const leaf = leafAt(view.state.ratchetTree, view.state.privatePath.leafIndex);
33
+ const epoch = Number(view.state.groupContext.epoch);
34
+ return Object.freeze(leaf != null && await isLapsed(view, leaf) ? {
35
+ epoch,
36
+ admissible: false,
37
+ reason: 'lapsed'
38
+ } : {
39
+ epoch,
40
+ admissible: true
41
+ });
42
+ }
30
43
  const HISTORICAL_REGISTRIES = new WeakMap();
31
- export function registryAt(group, head) {
44
+ export async function registryAt({ group, head }) {
32
45
  let cache = HISTORICAL_REGISTRIES.get(group);
33
46
  if (cache == null) {
34
47
  cache = new Map();
@@ -40,14 +53,25 @@ export function registryAt(group, head) {
40
53
  let held = genesisHead(group.groupID);
41
54
  let length = 0;
42
55
  for (const entry of group.ledger){
43
- if (headsMatch(held, head)) break;
44
- held = extendHead(held, [
45
- entry.entryID
46
- ]);
56
+ if (headsMatch({
57
+ expected: held,
58
+ actual: head
59
+ })) break;
60
+ held = extendHead({
61
+ head: held,
62
+ entryIDs: [
63
+ entry.entryID
64
+ ]
65
+ });
47
66
  length++;
48
67
  }
49
- if (!headsMatch(held, head)) throw new Error('Unknown epoch ledger head');
50
- const registry = foldLedgerControl(group.ledger.slice(0, length), group.anchor, group.groupID).registry;
68
+ if (!headsMatch({
69
+ expected: held,
70
+ actual: head
71
+ })) throw new Error('Unknown epoch ledger head');
72
+ const registry = (await foldLedgerControl(group.ledger.slice(0, length), group.anchor, group.groupID, {
73
+ crypto: group.crypto
74
+ })).registry;
51
75
  cache.set(key, registry);
52
76
  if (cache.size > 8) {
53
77
  const oldest = cache.keys().next().value;
@@ -116,7 +140,7 @@ export function mutexFor(handle) {
116
140
  #proposals;
117
141
  #senderLeafIndex;
118
142
  #reason;
119
- constructor(proposals, senderLeafIndex, reason = 'policy'){
143
+ constructor({ proposals, senderLeafIndex, reason = 'policy' }){
120
144
  super('Commit rejected by group commit policy');
121
145
  this.name = 'CommitRejectedError';
122
146
  this.#reason = reason;
@@ -239,32 +263,51 @@ export function mutexFor(handle) {
239
263
  const VERIFIED_LEDGER_ENTRIES = new WeakMap();
240
264
  const VERIFIED_LEDGER_TOKENS = new WeakMap();
241
265
  export const VERIFIED_LEDGER_TOKEN_CACHE_SIZE = 4096;
242
- const VERIFIED_LEDGER_TOKEN_CACHE = new Map();
243
- function cachedLedgerEntry(token) {
244
- const verified = VERIFIED_LEDGER_TOKEN_CACHE.get(token);
266
+ const DEFAULT_LEDGER_TOKEN_CACHE = new Map();
267
+ const PROVIDER_LEDGER_TOKEN_CACHES = new WeakMap();
268
+ // A token one provider accepted says nothing about another.
269
+ function ledgerTokenCache(options) {
270
+ const crypto = options?.crypto;
271
+ if (crypto == null) return DEFAULT_LEDGER_TOKEN_CACHE;
272
+ let cache = PROVIDER_LEDGER_TOKEN_CACHES.get(crypto);
273
+ if (cache == null) {
274
+ cache = new Map();
275
+ PROVIDER_LEDGER_TOKEN_CACHES.set(crypto, cache);
276
+ }
277
+ return cache;
278
+ }
279
+ function cachedLedgerEntry(token, options) {
280
+ const cache = ledgerTokenCache(options);
281
+ const verified = cache.get(token);
245
282
  if (verified == null) return undefined;
246
- VERIFIED_LEDGER_TOKEN_CACHE.delete(token);
247
- VERIFIED_LEDGER_TOKEN_CACHE.set(token, verified);
283
+ cache.delete(token);
284
+ cache.set(token, verified);
248
285
  try {
249
- assertTimeClaimsValid(decodeSignedToken(token).payload);
286
+ assertTimeClaimsValid({
287
+ payload: decodeSignedToken(token).payload
288
+ });
250
289
  return structuredClone(verified);
251
290
  } catch {
252
291
  return null;
253
292
  }
254
293
  }
255
- function cacheLedgerEntry(token, verified) {
256
- VERIFIED_LEDGER_TOKEN_CACHE.delete(token);
257
- VERIFIED_LEDGER_TOKEN_CACHE.set(token, structuredClone(verified));
258
- if (VERIFIED_LEDGER_TOKEN_CACHE.size > VERIFIED_LEDGER_TOKEN_CACHE_SIZE) {
259
- const oldest = VERIFIED_LEDGER_TOKEN_CACHE.keys().next().value;
260
- if (oldest != null) VERIFIED_LEDGER_TOKEN_CACHE.delete(oldest);
294
+ function cacheLedgerEntry(token, verified, options) {
295
+ const cache = ledgerTokenCache(options);
296
+ cache.delete(token);
297
+ cache.set(token, structuredClone(verified));
298
+ if (cache.size > VERIFIED_LEDGER_TOKEN_CACHE_SIZE) {
299
+ const oldest = cache.keys().next().value;
300
+ if (oldest != null) cache.delete(oldest);
261
301
  }
262
302
  }
263
- async function verifyCachedLedgerEntry(token) {
264
- const cached = cachedLedgerEntry(token);
303
+ async function verifyCachedLedgerEntry(token, options) {
304
+ const cached = cachedLedgerEntry(token, options);
265
305
  if (cached !== undefined) return cached;
266
- const verified = await verifyLedgerEntry(token);
267
- if (verified != null) cacheLedgerEntry(token, verified);
306
+ const verified = await verifyLedgerEntry({
307
+ token,
308
+ ...options
309
+ });
310
+ if (verified != null) cacheLedgerEntry(token, verified, options);
268
311
  return verified;
269
312
  }
270
313
  // Record provenance before exposing claims; re-enactments keep the original snapshot.
@@ -285,7 +328,7 @@ function ledgerLogEntry(entryID, token, verified) {
285
328
  * a genuine expired post-reset package can activate a leaf for a Welcome joiner or an
286
329
  * external rejoiner adopting a fork existing members reject. Ordinary commit admission
287
330
  * still enforces expiry.
288
- */ function registryWithTreeBindings(registry, tree, anchor) {
331
+ */ async function registryWithTreeBindings(registry, tree, anchor, options) {
289
332
  if (anchor.controller == null) return registry;
290
333
  const devices = new Map(registry.devices);
291
334
  for (const node of tree){
@@ -296,7 +339,7 @@ function ledgerLogEntry(entryID, token, verified) {
296
339
  } catch {
297
340
  continue;
298
341
  }
299
- if (!mayReadmitResetDevice(registry, parsed)) continue;
342
+ if (!await mayReadmitResetDevice(registry, parsed, options)) continue;
300
343
  const did = normalizeDID(parsed.id);
301
344
  const record = devices.get(did);
302
345
  if (record == null) continue;
@@ -317,17 +360,23 @@ function ledgerLogEntry(entryID, token, verified) {
317
360
  * Project a held ledger into BOTH the roster and the device registry in one ordered pass
318
361
  * (see {@link foldControl}), so a role entry's authority resolves against the registry-so-far.
319
362
  * The mixed-type log is fed in whole; foldControl drops every unrelated entry by type.
320
- */ function foldLedgerControl(ledger, anchor, groupID) {
363
+ */ async function foldLedgerControl(ledger, anchor, groupID, options) {
321
364
  const entries = ledger.map(({ verified, entryID })=>({
322
365
  verified,
323
366
  entryID
324
367
  }));
325
- return foldControl(entries, anchor, groupID);
368
+ return await foldControl({
369
+ entries,
370
+ anchor,
371
+ groupID,
372
+ ...options
373
+ });
326
374
  }
327
375
  /** Mutable wrapper around MLS group state + Enkaku credential. */ export class GroupHandle {
328
376
  #state;
329
377
  #credential;
330
378
  #context;
379
+ #crypto;
331
380
  #commitPolicy;
332
381
  #resolveLedgerEntries;
333
382
  #onLedgerEntries;
@@ -341,6 +390,42 @@ function ledgerLogEntry(entryID, token, verified) {
341
390
  #registry;
342
391
  #admission;
343
392
  #pendingControlEvents;
393
+ /**
394
+ * Seed control state from the genesis anchor in the group's GroupContext. This is the single
395
+ * choke no anchorless handle slips through: an absent anchor fails closed rather than
396
+ * installing a permissive roster.
397
+ */ static async create(params) {
398
+ const anchor = readGroupAnchor(params);
399
+ if (anchor == null) {
400
+ throw new Error('group has no anchor extension; cannot seed a control roster');
401
+ }
402
+ const crypto = params.crypto ?? deviceDenyHolderFor(params.context)?.crypto;
403
+ const folded = await foldLedgerControl([
404
+ ...params.ledger ?? []
405
+ ], anchor, params.credential.groupID, {
406
+ crypto
407
+ });
408
+ const registry = await registryWithTreeBindings(folded.registry, params.state.ratchetTree, anchor, {
409
+ crypto
410
+ });
411
+ const admission = await computeAdmission({
412
+ state: params.state,
413
+ anchor,
414
+ registry,
415
+ crypto
416
+ });
417
+ const seeded = {
418
+ ...params,
419
+ crypto,
420
+ [FOLDED_CONTROL]: {
421
+ anchor,
422
+ roster: folded.roster,
423
+ registry,
424
+ admission
425
+ }
426
+ };
427
+ return new GroupHandle(seeded);
428
+ }
344
429
  constructor(params){
345
430
  this.#state = params.state;
346
431
  this.#credential = params.credential;
@@ -348,11 +433,11 @@ function ledgerLogEntry(entryID, token, verified) {
348
433
  // A caller-built context without a client config gets kumiai's, as the context a commit
349
434
  // rebuilds would: in place, since the context is the key of its deny holder.
350
435
  this.#context.clientConfig ??= kumiaiClientConfig();
436
+ this.#crypto = params.crypto;
351
437
  this.#commitPolicy = params.commitPolicy;
352
438
  this.#resolveLedgerEntries = params.resolveLedgerEntries;
353
439
  this.#onLedgerEntries = params.onLedgerEntries;
354
440
  const source = params[CLONE_SOURCE];
355
- let admission;
356
441
  if (source != null) {
357
442
  const snapshot = structuredClone({
358
443
  anchor: source.#anchor,
@@ -367,7 +452,7 @@ function ledgerLogEntry(entryID, token, verified) {
367
452
  this.#entryBodies = snapshot.entryBodies;
368
453
  this.#roster = snapshot.roster;
369
454
  this.#registry = snapshot.registry;
370
- admission = Object.freeze(snapshot.admission);
455
+ this.#admission = Object.freeze(snapshot.admission);
371
456
  // Preserve the trusted snapshot, never promote caller-mutated exposed claims.
372
457
  for (const [index, held] of source.#ledger.entries()){
373
458
  const copied = this.#ledger[index];
@@ -377,14 +462,8 @@ function ledgerLogEntry(entryID, token, verified) {
377
462
  }
378
463
  }
379
464
  } else {
380
- // Seed control state from the genesis anchor in the group's GroupContext. Reading
381
- // it here makes the constructor the single choke no anchorless handle slips
382
- // through: an absent anchor fails closed rather than installing a permissive roster.
383
- const anchor = readGroupAnchor(this);
384
- if (anchor == null) {
385
- throw new Error('group has no anchor extension; cannot seed a control roster');
386
- }
387
- this.#anchor = anchor;
465
+ const control = params[FOLDED_CONTROL];
466
+ this.#anchor = control.anchor;
388
467
  this.#ledger = [
389
468
  ...params.ledger ?? []
390
469
  ];
@@ -395,14 +474,15 @@ function ledgerLogEntry(entryID, token, verified) {
395
474
  verified
396
475
  }
397
476
  ]));
398
- const folded = foldLedgerControl(this.#ledger, anchor, this.groupID);
399
- this.#roster = folded.roster;
400
- this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor);
477
+ this.#roster = control.roster;
478
+ this.#registry = control.registry;
479
+ this.#admission = control.admission;
401
480
  }
402
481
  const anchor = this.#anchor;
403
482
  // Authentication reads only this handle's registry and lifetime limits.
404
483
  const denyHolder = deviceDenyHolderFor(this.#context);
405
484
  if (denyHolder != null) {
485
+ denyHolder.crypto = this.#crypto;
406
486
  denyHolder.provider = ()=>this.currentDenySet();
407
487
  denyHolder.judging = ()=>({
408
488
  registry: anchor.controller == null ? undefined : this.registry,
@@ -414,7 +494,6 @@ function ledgerLogEntry(entryID, token, verified) {
414
494
  }
415
495
  EMITTERS.set(this, params.events ?? new EventEmitter());
416
496
  this.#pendingControlEvents = params.speculative ? [] : undefined;
417
- this.#admission = admission ?? this.#computeAdmission();
418
497
  }
419
498
  /** Copy the current checkpoint without replaying ledger tokens or sharing mutable state.
420
499
  * Pending adoption notifications belong to the source; the copy starts non-speculative. */ clone(options) {
@@ -424,12 +503,15 @@ function ledgerLogEntry(entryID, token, verified) {
424
503
  authService: {
425
504
  validateCredential: this.#context.authService.validateCredential.bind(this.#context.authService)
426
505
  }
427
- } : createMlsContext(this.#context.cipherSuite, this.#anchor);
506
+ } : createMlsContext(this.#context.cipherSuite, this.#anchor, undefined, {
507
+ crypto: this.#crypto
508
+ });
428
509
  const config = this.#context.clientConfig;
429
510
  if (config != null) context.clientConfig = copyClientConfig(config);
430
511
  context.externalPsks = structuredClone(this.#context.externalPsks);
431
512
  const params = {
432
513
  [CLONE_SOURCE]: this,
514
+ crypto: this.#crypto,
433
515
  state: structuredClone(this.#state),
434
516
  credential: structuredClone(this.#credential),
435
517
  context,
@@ -439,18 +521,6 @@ function ledgerLogEntry(entryID, token, verified) {
439
521
  };
440
522
  return new GroupHandle(params);
441
523
  }
442
- #computeAdmission() {
443
- const leaf = leafAt(this.#state.ratchetTree, this.#state.privatePath.leafIndex);
444
- const epoch = Number(this.epoch);
445
- return Object.freeze(leaf != null && isLapsed(this, leaf) ? {
446
- epoch,
447
- admissible: false,
448
- reason: 'lapsed'
449
- } : {
450
- epoch,
451
- admissible: true
452
- });
453
- }
454
524
  sendAdmission() {
455
525
  return this.#admission;
456
526
  }
@@ -477,6 +547,9 @@ function ledgerLogEntry(entryID, token, verified) {
477
547
  get context() {
478
548
  return this.#context;
479
549
  }
550
+ /** The kokuin provider this handle verifies with; carried onto clones and derived handles. */ get crypto() {
551
+ return this.#crypto;
552
+ }
480
553
  /** The commit policy enforced by processMessage, if any. Carried onto
481
554
  * handles derived from this one (commitInvite/removeMember). */ get commitPolicy() {
482
555
  return this.#commitPolicy;
@@ -499,7 +572,10 @@ function ledgerLogEntry(entryID, token, verified) {
499
572
  * Feeds createInvite, restoreGroup, and host persistence. In-process clones inherit
500
573
  * verification through the returned array; serialised tokens must verify afresh. */ get ledgerTokens() {
501
574
  const tokens = this.#ledger.map(({ token })=>token);
502
- VERIFIED_LEDGER_TOKENS.set(tokens, this.#ledger.map(({ verified })=>VERIFIED_LEDGER_ENTRIES.get(verified)));
575
+ VERIFIED_LEDGER_TOKENS.set(tokens, {
576
+ crypto: this.#crypto,
577
+ held: this.#ledger.map(({ verified })=>VERIFIED_LEDGER_ENTRIES.get(verified))
578
+ });
503
579
  return tokens;
504
580
  }
505
581
  /** The control roster folded from the anchor and every applied ledger entry. */ get roster() {
@@ -508,10 +584,16 @@ function ledgerLogEntry(entryID, token, verified) {
508
584
  /** The device registry folded from the anchor and every applied ledger entry. */ get registry() {
509
585
  return this.#registry;
510
586
  }
511
- settleAdvisory() {
587
+ async settleAdvisory() {
512
588
  const controller = this.#anchor.controller;
513
- const log = controller == null ? undefined : recordedLogOf(this.#registry, controller);
514
- return log == null ? 'ok' : settleAdvisory(log);
589
+ const log = controller == null ? undefined : recordedLogOf({
590
+ registry: this.#registry,
591
+ controller
592
+ });
593
+ return log == null ? 'ok' : await settleAdvisory({
594
+ log,
595
+ crypto: this.#crypto
596
+ });
515
597
  }
516
598
  /**
517
599
  * The device deny set the auth service consumes: the DIDs revoked in the CURRENTLY folded
@@ -581,14 +663,20 @@ function ledgerLogEntry(entryID, token, verified) {
581
663
  ] : [])
582
664
  ]){
583
665
  const device = normalizeDID(effect.did);
584
- const record = revocationOf(this, device);
666
+ const record = revocationOf({
667
+ group: this,
668
+ did: device
669
+ });
585
670
  if (record != null) revoked.push({
586
671
  device,
587
672
  ...record
588
673
  });
589
674
  }
590
675
  } else if (value.op === 'revoke') {
591
- const controller = controllerOf(this.#registry, subject);
676
+ const controller = controllerOf({
677
+ registry: this.#registry,
678
+ deviceDID: subject
679
+ });
592
680
  if (controller != null) revoked.push({
593
681
  device: subject,
594
682
  controller
@@ -635,7 +723,8 @@ function ledgerLogEntry(entryID, token, verified) {
635
723
  return mutexFor(this).run(async ()=>{
636
724
  const appended = [];
637
725
  const candidates = [];
638
- const memo = VERIFIED_LEDGER_TOKENS.get(tokens);
726
+ const remembered = VERIFIED_LEDGER_TOKENS.get(tokens);
727
+ const memo = remembered != null && remembered.crypto === this.#crypto ? remembered.held : undefined;
639
728
  const nextMemo = [];
640
729
  for (const [index, token] of tokens.entries()){
641
730
  await maybeYield();
@@ -643,13 +732,17 @@ function ledgerLogEntry(entryID, token, verified) {
643
732
  let verified;
644
733
  if (held?.token === token) {
645
734
  try {
646
- assertTimeClaimsValid(decodeSignedToken(token).payload);
735
+ assertTimeClaimsValid({
736
+ payload: decodeSignedToken(token).payload
737
+ });
647
738
  } catch {
648
739
  continue;
649
740
  }
650
741
  verified = structuredClone(held.verified);
651
742
  } else {
652
- verified = await verifyCachedLedgerEntry(token);
743
+ verified = await verifyCachedLedgerEntry(token, {
744
+ crypto: this.#crypto
745
+ });
653
746
  }
654
747
  if (verified == null || verified.entry.groupID !== this.groupID) continue;
655
748
  const entryID = ledgerEntryDigest(token);
@@ -662,8 +755,18 @@ function ledgerLogEntry(entryID, token, verified) {
662
755
  ...this.#ledger,
663
756
  ...candidates
664
757
  ];
665
- const folded = foldLedgerControl(ledger, this.#anchor, this.groupID);
666
- const registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor);
758
+ const folded = await foldLedgerControl(ledger, this.#anchor, this.groupID, {
759
+ crypto: this.#crypto
760
+ });
761
+ const registry = await registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor, {
762
+ crypto: this.#crypto
763
+ });
764
+ const admission = await computeAdmission({
765
+ state: this.#state,
766
+ anchor: this.#anchor,
767
+ registry,
768
+ crypto: this.#crypto
769
+ });
667
770
  this.#ledger = ledger;
668
771
  for (const { entryID, token, verified } of candidates){
669
772
  this.#entryBodies.set(entryID, {
@@ -671,10 +774,13 @@ function ledgerLogEntry(entryID, token, verified) {
671
774
  verified
672
775
  });
673
776
  }
674
- VERIFIED_LEDGER_TOKENS.set(tokens, nextMemo);
777
+ VERIFIED_LEDGER_TOKENS.set(tokens, {
778
+ crypto: this.#crypto,
779
+ held: nextMemo
780
+ });
675
781
  this.#roster = folded.roster;
676
782
  this.#registry = registry;
677
- this.#admission = this.#computeAdmission();
783
+ this.#admission = admission;
678
784
  if (this.#pendingControlEvents != null) {
679
785
  this.emitControlEvents(appended.filter(({ entry })=>entry.type === DEVICE_ENTRY_TYPE));
680
786
  }
@@ -702,7 +808,13 @@ function ledgerLogEntry(entryID, token, verified) {
702
808
  // Report incomplete and let bootstrap fail loudly.
703
809
  return false;
704
810
  }
705
- return headsMatch(authenticated.head, computeHead(this.groupID, this.#ledger.map(({ entryID })=>entryID)));
811
+ return headsMatch({
812
+ expected: authenticated.head,
813
+ actual: computeHead({
814
+ groupID: this.groupID,
815
+ entryIDs: this.#ledger.map(({ entryID })=>entryID)
816
+ })
817
+ });
706
818
  });
707
819
  }
708
820
  /**
@@ -735,7 +847,7 @@ function ledgerLogEntry(entryID, token, verified) {
735
847
  * responder and tries the next. `persist` runs under this handle's mutex and must not
736
848
  * call back into it. It must write atomically: rejection means nothing was stored.
737
849
  * Host callbacks run after successful persist; a callback throw does not undo bootstrap.
738
- */ async bootstrapLedger(tokens, opts) {
850
+ */ async bootstrapLedger({ tokens, ...opts }) {
739
851
  return mutexFor(this).run(async ()=>{
740
852
  const authenticated = readLedgerHead(this);
741
853
  if (authenticated == null) {
@@ -744,12 +856,20 @@ function ledgerLogEntry(entryID, token, verified) {
744
856
  // The gate. Nothing below touches the handle until the last three statements,
745
857
  // and nothing above reads the tokens except for their content ids.
746
858
  const entryIDs = tokens.map(ledgerEntryDigest);
747
- assertHeadMatches(authenticated.head, computeHead(this.groupID, entryIDs));
859
+ assertHeadMatches({
860
+ expected: authenticated.head,
861
+ actual: computeHead({
862
+ groupID: this.groupID,
863
+ entryIDs
864
+ })
865
+ });
748
866
  const log = [];
749
867
  for(let index = 0; index < tokens.length; index++){
750
868
  await maybeYield();
751
869
  const token = tokens[index];
752
- const verified = await verifyCachedLedgerEntry(token);
870
+ const verified = await verifyCachedLedgerEntry(token, {
871
+ crypto: this.#crypto
872
+ });
753
873
  if (verified == null || verified.entry.groupID !== this.groupID) {
754
874
  // Unreachable past the gate — the chain digests the token bytes, so an
755
875
  // unverifiable or cross-group token cannot sit at a position the head
@@ -772,7 +892,18 @@ function ledgerLogEntry(entryID, token, verified) {
772
892
  registry: this.#registry,
773
893
  admission: this.#admission
774
894
  };
775
- const folded = foldLedgerControl(log, this.#anchor, this.groupID);
895
+ const folded = await foldLedgerControl(log, this.#anchor, this.groupID, {
896
+ crypto: this.#crypto
897
+ });
898
+ const registry = await registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor, {
899
+ crypto: this.#crypto
900
+ });
901
+ const admission = await computeAdmission({
902
+ state: this.#state,
903
+ anchor: this.#anchor,
904
+ registry,
905
+ crypto: this.#crypto
906
+ });
776
907
  this.#ledger = log;
777
908
  this.#entryBodies = new Map(log.map(({ entryID, token, verified })=>[
778
909
  entryID,
@@ -782,8 +913,8 @@ function ledgerLogEntry(entryID, token, verified) {
782
913
  }
783
914
  ]));
784
915
  this.#roster = folded.roster;
785
- this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor);
786
- this.#admission = this.#computeAdmission();
916
+ this.#registry = registry;
917
+ this.#admission = admission;
787
918
  try {
788
919
  await opts?.persist?.(this);
789
920
  } catch (error) {
@@ -828,7 +959,10 @@ function ledgerLogEntry(entryID, token, verified) {
828
959
  // rejects any peer:4 leaf lacking one before it can enter a ratchet tree. restore
829
960
  // trusts the host's own persisted state, so neither gate runs on that path.
830
961
  const controller = parsed.controller ? parsed.controller.id : undefined;
831
- const beacon = controller != null ? beaconOf(this.#registry, controller) : undefined;
962
+ const beacon = controller != null ? beaconOf({
963
+ registry: this.#registry,
964
+ controllerDID: controller
965
+ }) : undefined;
832
966
  // A KeyPackage leaf node is unique to its KeyPackage by its fresh HPKE key, and stays
833
967
  // in the tree only until the member's own path or Update replaces it.
834
968
  const admission = node.leaf.leafNodeSource === leafNodeSources.key_package ? toB64(node.leaf.hpkePublicKey) : undefined;
@@ -917,7 +1051,7 @@ function ledgerLogEntry(entryID, token, verified) {
917
1051
  * replaced only after resolution returns, so a read from in there sees the PRE-commit epoch's
918
1052
  * exporter secret, which is the epoch the blob being opened was sealed under. Both are silent
919
1053
  * consequences of this method's plainness; wrapping it "for consistency" breaks both.
920
- */ async exportSecret(label, context, length = 32) {
1054
+ */ async exportSecret({ label, context, length = 32 }) {
921
1055
  return await mlsExporter(this.#state.keySchedule.exporterSecret, label, context, length, this.#context.cipherSuite);
922
1056
  }
923
1057
  /**
@@ -944,7 +1078,7 @@ function ledgerLogEntry(entryID, token, verified) {
944
1078
  enactedDeviceEntries: []
945
1079
  })
946
1080
  });
947
- gate.check({
1081
+ await gate.check({
948
1082
  kind: 'proposal',
949
1083
  proposal: {
950
1084
  proposal,
@@ -974,10 +1108,10 @@ function ledgerLogEntry(entryID, token, verified) {
974
1108
  * `opts.aad` becomes the frame's MLS `authenticated_data` — bound into the AEAD but
975
1109
  * carried in the clear, so a caller reading it back (or comparing via `decrypt`'s
976
1110
  * `expectedAAD`) needs no key. Defaults to empty.
977
- */ async encrypt(plaintext, opts) {
1111
+ */ async encrypt({ plaintext, ...opts }) {
978
1112
  return mutexFor(this).run(async ()=>{
979
1113
  const own = leafAt(this.#state.ratchetTree, this.#state.privatePath.leafIndex);
980
- if (own != null && isLapsed(this, own)) throw new LeafLapsedError('lapsed');
1114
+ if (own != null && await isLapsed(this, own)) throw new LeafLapsedError('lapsed');
981
1115
  const { newState, message, consumed } = await createApplicationMessage({
982
1116
  context: this.#context,
983
1117
  state: this.#state,
@@ -1013,7 +1147,7 @@ function ledgerLogEntry(entryID, token, verified) {
1013
1147
  * Refuses exactly as {@link encrypt} would: a lapsed leaf, unapplied proposals, a
1014
1148
  * removed or suspended member. `target` must be below 0xffffffff, the last generation.
1015
1149
  * On any throw the handle state is unchanged and the secrets derived so far are zeroed.
1016
- */ async advanceSenderGeneration(target, opts) {
1150
+ */ async advanceSenderGeneration({ target, ...opts }) {
1017
1151
  // 0xffffffff is the last uint32 generation: no frame could follow it.
1018
1152
  if (!Number.isInteger(target) || target < 0 || target >= 0xffffffff) {
1019
1153
  throw new RangeError(`advanceSenderGeneration: ${target} is not a sendable uint32 generation`);
@@ -1024,7 +1158,7 @@ function ledgerLogEntry(entryID, token, verified) {
1024
1158
  }
1025
1159
  return mutexFor(this).run(async ()=>{
1026
1160
  const own = leafAt(this.#state.ratchetTree, this.#state.privatePath.leafIndex);
1027
- if (own != null && isLapsed(this, own)) throw new LeafLapsedError('lapsed');
1161
+ if (own != null && await isLapsed(this, own)) throw new LeafLapsedError('lapsed');
1028
1162
  checkCanSendApplicationMessages(this.#state);
1029
1163
  const node = Number(this.#state.privatePath.leafIndex) * 2;
1030
1164
  const current = this.#state.secretTree.leafNodes[node]?.application.generation ?? 0;
@@ -1205,7 +1339,7 @@ function ledgerLogEntry(entryID, token, verified) {
1205
1339
  * `authenticatedData` BEFORE `mlsProcessMessage` runs — a mismatch throws having consumed
1206
1340
  * no ratchet generation, so a wrong-topic frame costs nothing to reject. The frame's AAD
1207
1341
  * is always returned, whether or not `expectedAAD` was given.
1208
- */ async decrypt(message, opts) {
1342
+ */ async decrypt({ message, ...opts }) {
1209
1343
  const decoded = decode(mlsMessageDecoder, message);
1210
1344
  if (decoded == null) throw new Error('decrypt: failed to decode MLSMessage');
1211
1345
  return mutexFor(this).run(async ()=>{
@@ -1221,7 +1355,7 @@ function ledgerLogEntry(entryID, token, verified) {
1221
1355
  const historical = this.#state.historicalReceiverData.get(pm.epoch);
1222
1356
  const epochTree = historical?.ratchetTree ?? this.#state.ratchetTree;
1223
1357
  const leafIndex = await readSenderLeafIndex(this.#context, historical?.senderDataSecret ?? this.#state.keySchedule.senderDataSecret, pm);
1224
- assertSenderNotLapsed({
1358
+ await assertSenderNotLapsed({
1225
1359
  group: this,
1226
1360
  tree: epochTree,
1227
1361
  leafIndex,
@@ -1253,7 +1387,7 @@ function ledgerLogEntry(entryID, token, verified) {
1253
1387
  * The callback runs under this handle's mutex and must store `stagedState` as the
1254
1388
  * group's handle state. It must not call this handle or the peer. If opening or
1255
1389
  * persistence fails, the live state and its ratchet secrets remain untouched.
1256
- */ async decryptStaged(message, opts, persist) {
1390
+ */ async decryptStaged({ message, opts, persist }) {
1257
1391
  const decoded = decode(mlsMessageDecoder, message);
1258
1392
  if (decoded == null) throw new Error('decryptStaged: failed to decode MLSMessage');
1259
1393
  return mutexFor(this).run(async ()=>{
@@ -1265,7 +1399,7 @@ function ledgerLogEntry(entryID, token, verified) {
1265
1399
  const historical = this.#state.historicalReceiverData.get(pm.epoch);
1266
1400
  const epochTree = historical?.ratchetTree ?? this.#state.ratchetTree;
1267
1401
  const leafIndex = await readSenderLeafIndex(this.#context, historical?.senderDataSecret ?? this.#state.keySchedule.senderDataSecret, pm);
1268
- assertSenderNotLapsed({
1402
+ await assertSenderNotLapsed({
1269
1403
  group: this,
1270
1404
  tree: epochTree,
1271
1405
  leafIndex,
@@ -1355,7 +1489,9 @@ function ledgerLogEntry(entryID, token, verified) {
1355
1489
  const id = ledgerEntryDigest(token);
1356
1490
  // Content-addressing binds the untrusted body to the requested id.
1357
1491
  if (resolved.has(id) || !missing.includes(id)) continue;
1358
- const verified = await verifyCachedLedgerEntry(token);
1492
+ const verified = await verifyCachedLedgerEntry(token, {
1493
+ crypto: this.#crypto
1494
+ });
1359
1495
  if (verified == null) continue;
1360
1496
  resolved.set(id, ledgerLogEntry(id, token, verified));
1361
1497
  }
@@ -1371,7 +1507,8 @@ function ledgerLogEntry(entryID, token, verified) {
1371
1507
  ]);
1372
1508
  return input;
1373
1509
  });
1374
- const foldResult = foldEnvelope({
1510
+ const foldResult = await foldEnvelope({
1511
+ crypto: this.#crypto,
1375
1512
  baseRoster: this.#roster,
1376
1513
  baseRegistry: this.#registry,
1377
1514
  entries: ordered,
@@ -1391,14 +1528,19 @@ function ledgerLogEntry(entryID, token, verified) {
1391
1528
  acceptedEntries = ordered;
1392
1529
  const proofCtx = {
1393
1530
  bindingOfDID: (d)=>this.bindingOfDID(d),
1394
- controllerOf: (d)=>controllerOf(this.#registry, d)
1531
+ controllerOf: (d)=>controllerOf({
1532
+ registry: this.#registry,
1533
+ deviceDID: d
1534
+ })
1395
1535
  };
1396
1536
  for (const { verified } of acceptedEntries){
1397
1537
  if (verified.entry.type !== DEVICE_ENTRY_TYPE) continue;
1398
1538
  if (this.#anchor.controller != null && verified.entry.value.op !== 'beacon') {
1399
1539
  continue;
1400
1540
  }
1401
- const ok = await verifyDeviceEntry(verified, proofCtx);
1541
+ const ok = await verifyDeviceEntry(verified, proofCtx, {
1542
+ crypto: this.#crypto
1543
+ });
1402
1544
  if (!ok) {
1403
1545
  precomputedReject = true;
1404
1546
  break;
@@ -1438,6 +1580,20 @@ function ledgerLogEntry(entryID, token, verified) {
1438
1580
  if (error instanceof RevokeProofError) capture.proofError = error;
1439
1581
  if (error instanceof LeafBindingError) capture.bindingError = error;
1440
1582
  }
1583
+ let judged;
1584
+ let gateRejection;
1585
+ // ts-mls calls its callback synchronously, so the gate judges ahead of the pass that applies.
1586
+ const prejudge = async (incoming)=>{
1587
+ judged = incoming;
1588
+ if (precomputedReject) return;
1589
+ try {
1590
+ await gate?.check(incoming);
1591
+ } catch (error) {
1592
+ gateRejection = {
1593
+ error
1594
+ };
1595
+ }
1596
+ };
1441
1597
  const combined = (incoming)=>{
1442
1598
  // A decode/fold failure is a hard reject even under a caller policy: the
1443
1599
  // ledger the commit depends on is unresolvable or malformed.
@@ -1445,35 +1601,60 @@ function ledgerLogEntry(entryID, token, verified) {
1445
1601
  capture.reason ??= capture.proofError == null ? 'invalid' : rejectionReason(capture.proofError);
1446
1602
  return 'reject';
1447
1603
  }
1448
- try {
1449
- gate?.check(incoming);
1450
- } catch (error) {
1604
+ // Fail closed: nothing reaches acceptance without the gate having judged this kind of message.
1605
+ if (judged?.kind !== incoming.kind) {
1606
+ capture.reason ??= 'invalid';
1607
+ return 'reject';
1608
+ }
1609
+ if (gateRejection != null) {
1610
+ const { error } = gateRejection;
1451
1611
  capture.reason = rejectionReason(error);
1452
1612
  if (error instanceof RevokeProofError) capture.proofError = error;
1453
1613
  if (error instanceof LeafBindingError) capture.bindingError = error;
1454
1614
  return 'reject';
1455
1615
  }
1456
1616
  if (callerPolicy != null) return callerPolicy(incoming);
1457
- return this.#anchor.controller == null ? defaultCommitPolicy(incoming, context) : 'accept';
1617
+ return this.#anchor.controller == null ? defaultCommitPolicy({
1618
+ incoming,
1619
+ context
1620
+ }) : 'accept';
1458
1621
  };
1459
- const applyOnAccept = (notify = true)=>{
1622
+ const applyOnAccept = async (notify = true)=>{
1460
1623
  // Appended, never deduped: the log records what this commit enacted, at the
1461
1624
  // position the head chained it.
1625
+ const ledger = [
1626
+ ...this.#ledger
1627
+ ];
1462
1628
  for (const { token, verified, entryID } of acceptedEntries){
1463
- this.#ledger.push({
1629
+ ledger.push({
1464
1630
  entryID,
1465
1631
  token,
1466
1632
  verified
1467
1633
  });
1634
+ }
1635
+ const folded = await foldLedgerControl(ledger, this.#anchor, this.groupID, {
1636
+ crypto: this.#crypto
1637
+ });
1638
+ const registry = await registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor, {
1639
+ crypto: this.#crypto
1640
+ });
1641
+ const admission = await computeAdmission({
1642
+ state: this.#state,
1643
+ anchor: this.#anchor,
1644
+ registry,
1645
+ crypto: this.#crypto
1646
+ });
1647
+ // Published together: readers between the folds still see the previous epoch's control state.
1648
+ this.#ledger = ledger;
1649
+ for (const { token, verified, entryID } of acceptedEntries){
1468
1650
  this.#entryBodies.set(entryID, {
1469
1651
  token,
1470
1652
  verified
1471
1653
  });
1472
1654
  }
1473
1655
  this.#roster = candidateRoster;
1474
- const folded = foldLedgerControl(this.#ledger, this.#anchor, this.groupID);
1475
- this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor);
1476
- this.#admission = this.#computeAdmission();
1656
+ this.#registry = registry;
1657
+ this.#admission = admission;
1477
1658
  const emit = ()=>{
1478
1659
  this.#notifyAccepted(surfaced, acceptedEntries.filter(({ verified })=>verified.entry.type === DEVICE_ENTRY_TYPE).map(({ verified })=>verified));
1479
1660
  };
@@ -1483,6 +1664,7 @@ function ledgerLogEntry(entryID, token, verified) {
1483
1664
  return {
1484
1665
  candidateRegistry,
1485
1666
  callback: wrapCommitPolicy(combined, capture),
1667
+ prejudge,
1486
1668
  capture,
1487
1669
  applyOnAccept,
1488
1670
  postApply: async (state)=>{
@@ -1687,7 +1869,7 @@ function ledgerLogEntry(entryID, token, verified) {
1687
1869
  * receive ratchet. It runs under this handle's mutex and must not call back into it.
1688
1870
  * It must write atomically: rejection means nothing was stored. Host callbacks run
1689
1871
  * after successful persist; a callback throw does not undo an advance.
1690
- */ async processMessage(message, opts) {
1872
+ */ async processMessage({ message, ...opts }) {
1691
1873
  let decoded = message;
1692
1874
  if (message instanceof Uint8Array) {
1693
1875
  const parsed = decode(mlsMessageDecoder, message);
@@ -1702,14 +1884,14 @@ function ledgerLogEntry(entryID, token, verified) {
1702
1884
  const proposalEpoch = privateProposal?.epoch ?? (frame.wireformat === wireformats.mls_public_message && frame.publicMessage.content.contentType === contentTypes.proposal ? frame.publicMessage.content.epoch : undefined);
1703
1885
  // Past proposals cannot be enacted at this epoch and need no ratchet or ledger work.
1704
1886
  if (proposalEpoch != null && proposalEpoch < this.epoch) return null;
1705
- const { callback, capture, applyOnAccept, postApply, candidateRegistry } = await this.#prepareCommitPipeline(decoded, opts);
1887
+ const { callback, prejudge, capture, applyOnAccept, postApply, candidateRegistry } = await this.#prepareCommitPipeline(decoded, opts);
1706
1888
  const previousState = this.#state;
1707
1889
  const previousAdmission = this.#admission;
1708
1890
  const application = readPrivateFrame(decoded, contentTypes.application);
1709
1891
  if (application != null) {
1710
1892
  const historical = this.#state.historicalReceiverData.get(application.epoch);
1711
1893
  const index = await readSenderLeafIndex(this.#context, historical?.senderDataSecret ?? this.#state.keySchedule.senderDataSecret, application);
1712
- assertSenderNotLapsed({
1894
+ await assertSenderNotLapsed({
1713
1895
  group: this,
1714
1896
  tree: historical?.ratchetTree ?? this.#state.ratchetTree,
1715
1897
  leafIndex: index,
@@ -1718,61 +1900,83 @@ function ledgerLogEntry(entryID, token, verified) {
1718
1900
  }
1719
1901
  let result;
1720
1902
  try {
1721
- result = await mlsProcessMessage({
1722
- context: {
1723
- ...this.#context,
1724
- authService: {
1725
- validateCredential: async (credential, key)=>{
1726
- try {
1727
- // Referenced Updates authenticate before the commit callback runs.
1728
- const proposed = (capture.rejected?.proposals ?? Object.values(this.#state.unappliedProposals)).find(({ proposal })=>{
1729
- if (!isDefaultProposal(proposal)) return false;
1730
- if (proposal.proposalType === defaultProposalTypes.add) return proposal.add.keyPackage.leafNode.credential === credential;
1731
- return proposal.proposalType === defaultProposalTypes.update && proposal.update.leafNode.credential === credential;
1732
- });
1733
- const index = proposed == null ? capture.committerLeafIndex : proposed.proposal.proposalType === defaultProposalTypes.update ? proposed.senderLeafIndex : undefined;
1734
- const retained = index != null && isUnchangedLeaf(this.#state.ratchetTree, index, {
1735
- credential,
1736
- signaturePublicKey: key
1737
- });
1738
- await verifyLeafCredential(credential, key, {
1739
- deviceDenySet: ()=>denySetOf(candidateRegistry),
1740
- judging: ()=>({
1741
- registry: this.#anchor.controller == null ? undefined : candidateRegistry,
1742
- stage: 'full',
1743
- mode: retained ? 'retain' : 'admit'
1744
- }),
1745
- // MLS re-validates the committer's path leaf after its proposals are judged:
1746
- // an evidenced child keeps a denied issuer only with the credential it
1747
- // already holds at that leaf.
1748
- mayKeepDeniedIssuer: ()=>this.#anchor.controller != null && retained,
1749
- leafLifetime: ()=>this.#anchor.controller == null ? undefined : this.#anchor.leafLifetime ?? 86_400,
1750
- trustedGrantLifetime: ()=>this.#anchor.controller == null ? undefined : this.#anchor.trustedGrantLifetime ?? 2_592_000
1751
- });
1752
- return true;
1753
- } catch (error) {
1754
- capture.reason = rejectionReason(error);
1755
- if (error instanceof LeafBindingError) capture.bindingError = error;
1756
- return false;
1903
+ // Both passes read one state, so the gate judges what the real pass applies.
1904
+ const state = this.#state;
1905
+ const run = async (action)=>await mlsProcessMessage({
1906
+ context: {
1907
+ ...this.#context,
1908
+ authService: {
1909
+ validateCredential: async (credential, key)=>{
1910
+ try {
1911
+ // Referenced Updates authenticate before the commit callback runs.
1912
+ const proposed = (capture.rejected?.proposals ?? Object.values(this.#state.unappliedProposals)).find(({ proposal })=>{
1913
+ if (!isDefaultProposal(proposal)) return false;
1914
+ if (proposal.proposalType === defaultProposalTypes.add) return proposal.add.keyPackage.leafNode.credential === credential;
1915
+ return proposal.proposalType === defaultProposalTypes.update && proposal.update.leafNode.credential === credential;
1916
+ });
1917
+ const index = proposed == null ? capture.committerLeafIndex : proposed.proposal.proposalType === defaultProposalTypes.update ? proposed.senderLeafIndex : undefined;
1918
+ const retained = index != null && isUnchangedLeaf(this.#state.ratchetTree, index, {
1919
+ credential,
1920
+ signaturePublicKey: key
1921
+ });
1922
+ await verifyLeafCredential(credential, key, {
1923
+ crypto: this.#crypto,
1924
+ deviceDenySet: ()=>denySetOf(candidateRegistry),
1925
+ judging: ()=>({
1926
+ registry: this.#anchor.controller == null ? undefined : candidateRegistry,
1927
+ stage: 'full',
1928
+ mode: retained ? 'retain' : 'admit'
1929
+ }),
1930
+ // MLS re-validates the committer's path leaf after its proposals are judged:
1931
+ // an evidenced child keeps a denied issuer only with the credential it
1932
+ // already holds at that leaf.
1933
+ mayKeepDeniedIssuer: ()=>this.#anchor.controller != null && retained,
1934
+ leafLifetime: ()=>this.#anchor.controller == null ? undefined : this.#anchor.leafLifetime ?? 86_400,
1935
+ trustedGrantLifetime: ()=>this.#anchor.controller == null ? undefined : this.#anchor.trustedGrantLifetime ?? 2_592_000
1936
+ });
1937
+ return true;
1938
+ } catch (error) {
1939
+ capture.reason = rejectionReason(error);
1940
+ if (error instanceof LeafBindingError) capture.bindingError = error;
1941
+ return false;
1942
+ }
1757
1943
  }
1758
1944
  }
1945
+ },
1946
+ state,
1947
+ message: decoded,
1948
+ ...action != null && {
1949
+ callback: action
1759
1950
  }
1760
- },
1761
- state: this.#state,
1762
- message: decoded,
1763
- ...callback != null && {
1764
- callback
1765
- }
1766
- });
1951
+ });
1952
+ // Rejecting leaves the state as it was and consumes nothing; application messages ratchet
1953
+ // and never reach the callback.
1954
+ if (application == null && callback != null) {
1955
+ let incoming;
1956
+ await run((seen)=>{
1957
+ incoming = seen;
1958
+ return 'reject';
1959
+ });
1960
+ if (incoming != null) await prejudge(incoming);
1961
+ }
1962
+ result = await run(callback);
1767
1963
  } catch (error) {
1768
1964
  if (application != null) throw error;
1769
- const rejection = new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex, capture.reason ?? 'invalid');
1965
+ const rejection = new CommitRejectedError({
1966
+ proposals: capture.rejected?.proposals ?? [],
1967
+ senderLeafIndex: capture.rejected?.senderLeafIndex,
1968
+ reason: capture.reason ?? 'invalid'
1969
+ });
1770
1970
  rejection.cause = capture.bindingError ?? error;
1771
1971
  if (error instanceof Error) rejection.message += `: ${error.message}`;
1772
1972
  throw rejection;
1773
1973
  }
1774
1974
  if (result.kind === 'newState' && result.actionTaken === 'reject') {
1775
- const rejection = new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex, capture.reason ?? 'policy');
1975
+ const rejection = new CommitRejectedError({
1976
+ proposals: capture.rejected?.proposals ?? [],
1977
+ senderLeafIndex: capture.rejected?.senderLeafIndex,
1978
+ reason: capture.reason ?? 'policy'
1979
+ });
1776
1980
  const cause = capture.proofError ?? capture.bindingError;
1777
1981
  if (cause != null) rejection.cause = cause;
1778
1982
  throw rejection;
@@ -1781,7 +1985,11 @@ function ledgerLogEntry(entryID, token, verified) {
1781
1985
  try {
1782
1986
  await postApply(result.newState);
1783
1987
  } catch (error) {
1784
- const rejection = new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex, rejectionReason(error));
1988
+ const rejection = new CommitRejectedError({
1989
+ proposals: capture.rejected?.proposals ?? [],
1990
+ senderLeafIndex: capture.rejected?.senderLeafIndex,
1991
+ reason: rejectionReason(error)
1992
+ });
1785
1993
  rejection.cause = error;
1786
1994
  throw rejection;
1787
1995
  }
@@ -1802,7 +2010,7 @@ function ledgerLogEntry(entryID, token, verified) {
1802
2010
  ...previousLedger
1803
2011
  ];
1804
2012
  this.#entryBodies = new Map(previousEntryBodies);
1805
- const notify = applyOnAccept(false);
2013
+ const notify = await applyOnAccept(false);
1806
2014
  try {
1807
2015
  await opts.persist(this);
1808
2016
  } catch (error) {
@@ -1818,7 +2026,7 @@ function ledgerLogEntry(entryID, token, verified) {
1818
2026
  notify();
1819
2027
  } else {
1820
2028
  zeroAll(result.consumed);
1821
- applyOnAccept();
2029
+ await applyOnAccept();
1822
2030
  }
1823
2031
  return null;
1824
2032
  });
@@ -1829,7 +2037,10 @@ function ledgerLogEntry(entryID, token, verified) {
1829
2037
  for (const member of handle.listMembers())leafToDID.set(member.leafIndex, member.id);
1830
2038
  const headExt = readLedgerHeadExtension(handle);
1831
2039
  const currentHead = headExt != null && headExt.extensionData instanceof Uint8Array ? decodeLedgerHead(headExt.extensionData) : null;
1832
- const expectedHeadExtensionData = currentHead == null ? new Uint8Array() : encodeLedgerHead(extendHead(currentHead.head, args.entryIDs));
2040
+ const expectedHeadExtensionData = currentHead == null ? new Uint8Array() : encodeLedgerHead(extendHead({
2041
+ head: currentHead.head,
2042
+ entryIDs: args.entryIDs
2043
+ }));
1833
2044
  return {
1834
2045
  baseRoster: args.baseRoster,
1835
2046
  candidateRoster: args.candidateRoster,
@@ -1853,12 +2064,15 @@ function ledgerLogEntry(entryID, token, verified) {
1853
2064
  }
1854
2065
  };
1855
2066
  }
1856
- /** Build the handle a commit hands back: the post-commit state, everything else inherited. */ export function deriveGroup(group, state) {
1857
- return new GroupHandle({
2067
+ /** Build the handle a commit hands back: the post-commit state, everything else inherited. */ export async function deriveGroup(group, state) {
2068
+ return await GroupHandle.create({
1858
2069
  state,
1859
2070
  credential: group.credential,
1860
2071
  // The post-commit handle keeps the source's receive retention, not ts-mls's defaults.
1861
- context: createMlsContext(group.context.cipherSuite, group.anchor, group.context.clientConfig),
2072
+ context: createMlsContext(group.context.cipherSuite, group.anchor, group.context.clientConfig, {
2073
+ crypto: group.crypto
2074
+ }),
2075
+ crypto: group.crypto,
1862
2076
  ledger: group.ledger,
1863
2077
  commitPolicy: group.commitPolicy,
1864
2078
  resolveLedgerEntries: group.resolveLedgerEntries,