@kumiai/mls 0.12.3 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) 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/device-proof.d.ts +2 -1
  11. package/lib/device-proof.js +2 -1
  12. package/lib/embedded-resolver.d.ts +7 -2
  13. package/lib/embedded-resolver.js +16 -6
  14. package/lib/envelope-fold.d.ts +3 -2
  15. package/lib/envelope-fold.js +14 -6
  16. package/lib/fold.d.ts +17 -3
  17. package/lib/fold.js +9 -3
  18. package/lib/group-commit.d.ts +11 -2
  19. package/lib/group-commit.js +76 -32
  20. package/lib/group-context.d.ts +37 -3
  21. package/lib/group-context.js +65 -4
  22. package/lib/group-create.d.ts +5 -1
  23. package/lib/group-create.js +36 -14
  24. package/lib/group-credential.d.ts +13 -3
  25. package/lib/group-credential.js +17 -6
  26. package/lib/group-device.d.ts +32 -22
  27. package/lib/group-device.js +66 -51
  28. package/lib/group-handle.d.ts +87 -31
  29. package/lib/group-handle.js +377 -168
  30. package/lib/group-lifecycle.d.ts +44 -11
  31. package/lib/group-lifecycle.js +193 -85
  32. package/lib/group-membership.d.ts +6 -1
  33. package/lib/group-membership.js +2 -2
  34. package/lib/group-welcome.d.ts +5 -1
  35. package/lib/group-welcome.js +34 -10
  36. package/lib/head.d.ts +25 -5
  37. package/lib/head.js +17 -8
  38. package/lib/history.d.ts +14 -3
  39. package/lib/history.js +8 -5
  40. package/lib/index.d.ts +28 -1
  41. package/lib/index.js +1 -0
  42. package/lib/key-package-codec.d.ts +4 -1
  43. package/lib/key-package-codec.js +1 -1
  44. package/lib/ledger.d.ts +14 -6
  45. package/lib/ledger.js +56 -19
  46. package/lib/lifecycle-proof.d.ts +5 -4
  47. package/lib/lifecycle-proof.js +111 -51
  48. package/lib/lifecycle.d.ts +18 -9
  49. package/lib/lifecycle.js +184 -81
  50. package/lib/member-root.d.ts +54 -15
  51. package/lib/member-root.js +115 -53
  52. package/lib/policy.d.ts +5 -1
  53. package/lib/policy.js +1 -1
  54. package/lib/recovery-verdict.d.ts +12 -3
  55. package/lib/recovery-verdict.js +56 -22
  56. package/lib/recovery.d.ts +20 -5
  57. package/lib/recovery.js +117 -46
  58. package/lib/registry.d.ts +46 -10
  59. package/lib/registry.js +64 -38
  60. package/lib/roster.d.ts +7 -1
  61. package/lib/roster.js +18 -7
  62. package/lib/secret-tree.d.ts +5 -1
  63. package/lib/secret-tree.js +1 -1
  64. package/lib/types.d.ts +3 -0
  65. package/package.json +9 -5
@@ -11,7 +11,7 @@ import { verifyDeviceEntry } from './device-proof.js';
11
11
  import { decodeControlEnvelope } from './envelope.js';
12
12
  import { foldEnvelope, GROUP_TYPE_PREFIX } from './envelope-fold.js';
13
13
  import { HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
14
- import { createMlsContext, deviceDenyHolderFor } from './group-context.js';
14
+ import { copyClientConfig, createMlsContext, deviceDenyHolderFor, kumiaiClientConfig } from './group-context.js';
15
15
  import { readMessageEpoch } from './group-info.js';
16
16
  import { assertHeadMatches, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, readLedgerHead, readLedgerHeadExtension } from './head.js';
17
17
  import { settleAdvisory } from './history.js';
@@ -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,15 +390,54 @@ 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;
347
432
  this.#context = params.context;
433
+ // A caller-built context without a client config gets kumiai's, as the context a commit
434
+ // rebuilds would: in place, since the context is the key of its deny holder.
435
+ this.#context.clientConfig ??= kumiaiClientConfig();
436
+ this.#crypto = params.crypto;
348
437
  this.#commitPolicy = params.commitPolicy;
349
438
  this.#resolveLedgerEntries = params.resolveLedgerEntries;
350
439
  this.#onLedgerEntries = params.onLedgerEntries;
351
440
  const source = params[CLONE_SOURCE];
352
- let admission;
353
441
  if (source != null) {
354
442
  const snapshot = structuredClone({
355
443
  anchor: source.#anchor,
@@ -364,7 +452,7 @@ function ledgerLogEntry(entryID, token, verified) {
364
452
  this.#entryBodies = snapshot.entryBodies;
365
453
  this.#roster = snapshot.roster;
366
454
  this.#registry = snapshot.registry;
367
- admission = Object.freeze(snapshot.admission);
455
+ this.#admission = Object.freeze(snapshot.admission);
368
456
  // Preserve the trusted snapshot, never promote caller-mutated exposed claims.
369
457
  for (const [index, held] of source.#ledger.entries()){
370
458
  const copied = this.#ledger[index];
@@ -374,14 +462,8 @@ function ledgerLogEntry(entryID, token, verified) {
374
462
  }
375
463
  }
376
464
  } else {
377
- // Seed control state from the genesis anchor in the group's GroupContext. Reading
378
- // it here makes the constructor the single choke no anchorless handle slips
379
- // through: an absent anchor fails closed rather than installing a permissive roster.
380
- const anchor = readGroupAnchor(this);
381
- if (anchor == null) {
382
- throw new Error('group has no anchor extension; cannot seed a control roster');
383
- }
384
- this.#anchor = anchor;
465
+ const control = params[FOLDED_CONTROL];
466
+ this.#anchor = control.anchor;
385
467
  this.#ledger = [
386
468
  ...params.ledger ?? []
387
469
  ];
@@ -392,14 +474,15 @@ function ledgerLogEntry(entryID, token, verified) {
392
474
  verified
393
475
  }
394
476
  ]));
395
- const folded = foldLedgerControl(this.#ledger, anchor, this.groupID);
396
- this.#roster = folded.roster;
397
- 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;
398
480
  }
399
481
  const anchor = this.#anchor;
400
482
  // Authentication reads only this handle's registry and lifetime limits.
401
483
  const denyHolder = deviceDenyHolderFor(this.#context);
402
484
  if (denyHolder != null) {
485
+ denyHolder.crypto = this.#crypto;
403
486
  denyHolder.provider = ()=>this.currentDenySet();
404
487
  denyHolder.judging = ()=>({
405
488
  registry: anchor.controller == null ? undefined : this.registry,
@@ -411,7 +494,6 @@ function ledgerLogEntry(entryID, token, verified) {
411
494
  }
412
495
  EMITTERS.set(this, params.events ?? new EventEmitter());
413
496
  this.#pendingControlEvents = params.speculative ? [] : undefined;
414
- this.#admission = admission ?? this.#computeAdmission();
415
497
  }
416
498
  /** Copy the current checkpoint without replaying ledger tokens or sharing mutable state.
417
499
  * Pending adoption notifications belong to the source; the copy starts non-speculative. */ clone(options) {
@@ -421,23 +503,15 @@ function ledgerLogEntry(entryID, token, verified) {
421
503
  authService: {
422
504
  validateCredential: this.#context.authService.validateCredential.bind(this.#context.authService)
423
505
  }
424
- } : createMlsContext(this.#context.cipherSuite, this.#anchor);
506
+ } : createMlsContext(this.#context.cipherSuite, this.#anchor, undefined, {
507
+ crypto: this.#crypto
508
+ });
425
509
  const config = this.#context.clientConfig;
426
- if (config != null) {
427
- const equality = config.keyPackageEqualityConfig;
428
- context.clientConfig = {
429
- keyRetentionConfig: structuredClone(config.keyRetentionConfig),
430
- lifetimeConfig: structuredClone(config.lifetimeConfig),
431
- paddingConfig: structuredClone(config.paddingConfig),
432
- keyPackageEqualityConfig: {
433
- compareKeyPackages: equality.compareKeyPackages.bind(equality),
434
- compareKeyPackageToLeafNode: equality.compareKeyPackageToLeafNode.bind(equality)
435
- }
436
- };
437
- }
510
+ if (config != null) context.clientConfig = copyClientConfig(config);
438
511
  context.externalPsks = structuredClone(this.#context.externalPsks);
439
512
  const params = {
440
513
  [CLONE_SOURCE]: this,
514
+ crypto: this.#crypto,
441
515
  state: structuredClone(this.#state),
442
516
  credential: structuredClone(this.#credential),
443
517
  context,
@@ -447,18 +521,6 @@ function ledgerLogEntry(entryID, token, verified) {
447
521
  };
448
522
  return new GroupHandle(params);
449
523
  }
450
- #computeAdmission() {
451
- const leaf = leafAt(this.#state.ratchetTree, this.#state.privatePath.leafIndex);
452
- const epoch = Number(this.epoch);
453
- return Object.freeze(leaf != null && isLapsed(this, leaf) ? {
454
- epoch,
455
- admissible: false,
456
- reason: 'lapsed'
457
- } : {
458
- epoch,
459
- admissible: true
460
- });
461
- }
462
524
  sendAdmission() {
463
525
  return this.#admission;
464
526
  }
@@ -485,6 +547,9 @@ function ledgerLogEntry(entryID, token, verified) {
485
547
  get context() {
486
548
  return this.#context;
487
549
  }
550
+ /** The kokuin provider this handle verifies with; carried onto clones and derived handles. */ get crypto() {
551
+ return this.#crypto;
552
+ }
488
553
  /** The commit policy enforced by processMessage, if any. Carried onto
489
554
  * handles derived from this one (commitInvite/removeMember). */ get commitPolicy() {
490
555
  return this.#commitPolicy;
@@ -507,7 +572,10 @@ function ledgerLogEntry(entryID, token, verified) {
507
572
  * Feeds createInvite, restoreGroup, and host persistence. In-process clones inherit
508
573
  * verification through the returned array; serialised tokens must verify afresh. */ get ledgerTokens() {
509
574
  const tokens = this.#ledger.map(({ token })=>token);
510
- 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
+ });
511
579
  return tokens;
512
580
  }
513
581
  /** The control roster folded from the anchor and every applied ledger entry. */ get roster() {
@@ -516,10 +584,16 @@ function ledgerLogEntry(entryID, token, verified) {
516
584
  /** The device registry folded from the anchor and every applied ledger entry. */ get registry() {
517
585
  return this.#registry;
518
586
  }
519
- settleAdvisory() {
587
+ async settleAdvisory() {
520
588
  const controller = this.#anchor.controller;
521
- const log = controller == null ? undefined : recordedLogOf(this.#registry, controller);
522
- 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
+ });
523
597
  }
524
598
  /**
525
599
  * The device deny set the auth service consumes: the DIDs revoked in the CURRENTLY folded
@@ -589,14 +663,20 @@ function ledgerLogEntry(entryID, token, verified) {
589
663
  ] : [])
590
664
  ]){
591
665
  const device = normalizeDID(effect.did);
592
- const record = revocationOf(this, device);
666
+ const record = revocationOf({
667
+ group: this,
668
+ did: device
669
+ });
593
670
  if (record != null) revoked.push({
594
671
  device,
595
672
  ...record
596
673
  });
597
674
  }
598
675
  } else if (value.op === 'revoke') {
599
- const controller = controllerOf(this.#registry, subject);
676
+ const controller = controllerOf({
677
+ registry: this.#registry,
678
+ deviceDID: subject
679
+ });
600
680
  if (controller != null) revoked.push({
601
681
  device: subject,
602
682
  controller
@@ -643,7 +723,8 @@ function ledgerLogEntry(entryID, token, verified) {
643
723
  return mutexFor(this).run(async ()=>{
644
724
  const appended = [];
645
725
  const candidates = [];
646
- 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;
647
728
  const nextMemo = [];
648
729
  for (const [index, token] of tokens.entries()){
649
730
  await maybeYield();
@@ -651,13 +732,17 @@ function ledgerLogEntry(entryID, token, verified) {
651
732
  let verified;
652
733
  if (held?.token === token) {
653
734
  try {
654
- assertTimeClaimsValid(decodeSignedToken(token).payload);
735
+ assertTimeClaimsValid({
736
+ payload: decodeSignedToken(token).payload
737
+ });
655
738
  } catch {
656
739
  continue;
657
740
  }
658
741
  verified = structuredClone(held.verified);
659
742
  } else {
660
- verified = await verifyCachedLedgerEntry(token);
743
+ verified = await verifyCachedLedgerEntry(token, {
744
+ crypto: this.#crypto
745
+ });
661
746
  }
662
747
  if (verified == null || verified.entry.groupID !== this.groupID) continue;
663
748
  const entryID = ledgerEntryDigest(token);
@@ -670,8 +755,18 @@ function ledgerLogEntry(entryID, token, verified) {
670
755
  ...this.#ledger,
671
756
  ...candidates
672
757
  ];
673
- const folded = foldLedgerControl(ledger, this.#anchor, this.groupID);
674
- 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
+ });
675
770
  this.#ledger = ledger;
676
771
  for (const { entryID, token, verified } of candidates){
677
772
  this.#entryBodies.set(entryID, {
@@ -679,10 +774,13 @@ function ledgerLogEntry(entryID, token, verified) {
679
774
  verified
680
775
  });
681
776
  }
682
- VERIFIED_LEDGER_TOKENS.set(tokens, nextMemo);
777
+ VERIFIED_LEDGER_TOKENS.set(tokens, {
778
+ crypto: this.#crypto,
779
+ held: nextMemo
780
+ });
683
781
  this.#roster = folded.roster;
684
782
  this.#registry = registry;
685
- this.#admission = this.#computeAdmission();
783
+ this.#admission = admission;
686
784
  if (this.#pendingControlEvents != null) {
687
785
  this.emitControlEvents(appended.filter(({ entry })=>entry.type === DEVICE_ENTRY_TYPE));
688
786
  }
@@ -710,7 +808,13 @@ function ledgerLogEntry(entryID, token, verified) {
710
808
  // Report incomplete and let bootstrap fail loudly.
711
809
  return false;
712
810
  }
713
- 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
+ });
714
818
  });
715
819
  }
716
820
  /**
@@ -743,7 +847,7 @@ function ledgerLogEntry(entryID, token, verified) {
743
847
  * responder and tries the next. `persist` runs under this handle's mutex and must not
744
848
  * call back into it. It must write atomically: rejection means nothing was stored.
745
849
  * Host callbacks run after successful persist; a callback throw does not undo bootstrap.
746
- */ async bootstrapLedger(tokens, opts) {
850
+ */ async bootstrapLedger({ tokens, ...opts }) {
747
851
  return mutexFor(this).run(async ()=>{
748
852
  const authenticated = readLedgerHead(this);
749
853
  if (authenticated == null) {
@@ -752,12 +856,20 @@ function ledgerLogEntry(entryID, token, verified) {
752
856
  // The gate. Nothing below touches the handle until the last three statements,
753
857
  // and nothing above reads the tokens except for their content ids.
754
858
  const entryIDs = tokens.map(ledgerEntryDigest);
755
- assertHeadMatches(authenticated.head, computeHead(this.groupID, entryIDs));
859
+ assertHeadMatches({
860
+ expected: authenticated.head,
861
+ actual: computeHead({
862
+ groupID: this.groupID,
863
+ entryIDs
864
+ })
865
+ });
756
866
  const log = [];
757
867
  for(let index = 0; index < tokens.length; index++){
758
868
  await maybeYield();
759
869
  const token = tokens[index];
760
- const verified = await verifyCachedLedgerEntry(token);
870
+ const verified = await verifyCachedLedgerEntry(token, {
871
+ crypto: this.#crypto
872
+ });
761
873
  if (verified == null || verified.entry.groupID !== this.groupID) {
762
874
  // Unreachable past the gate — the chain digests the token bytes, so an
763
875
  // unverifiable or cross-group token cannot sit at a position the head
@@ -780,7 +892,18 @@ function ledgerLogEntry(entryID, token, verified) {
780
892
  registry: this.#registry,
781
893
  admission: this.#admission
782
894
  };
783
- 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
+ });
784
907
  this.#ledger = log;
785
908
  this.#entryBodies = new Map(log.map(({ entryID, token, verified })=>[
786
909
  entryID,
@@ -790,8 +913,8 @@ function ledgerLogEntry(entryID, token, verified) {
790
913
  }
791
914
  ]));
792
915
  this.#roster = folded.roster;
793
- this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor);
794
- this.#admission = this.#computeAdmission();
916
+ this.#registry = registry;
917
+ this.#admission = admission;
795
918
  try {
796
919
  await opts?.persist?.(this);
797
920
  } catch (error) {
@@ -836,7 +959,10 @@ function ledgerLogEntry(entryID, token, verified) {
836
959
  // rejects any peer:4 leaf lacking one before it can enter a ratchet tree. restore
837
960
  // trusts the host's own persisted state, so neither gate runs on that path.
838
961
  const controller = parsed.controller ? parsed.controller.id : undefined;
839
- const beacon = controller != null ? beaconOf(this.#registry, controller) : undefined;
962
+ const beacon = controller != null ? beaconOf({
963
+ registry: this.#registry,
964
+ controllerDID: controller
965
+ }) : undefined;
840
966
  // A KeyPackage leaf node is unique to its KeyPackage by its fresh HPKE key, and stays
841
967
  // in the tree only until the member's own path or Update replaces it.
842
968
  const admission = node.leaf.leafNodeSource === leafNodeSources.key_package ? toB64(node.leaf.hpkePublicKey) : undefined;
@@ -925,7 +1051,7 @@ function ledgerLogEntry(entryID, token, verified) {
925
1051
  * replaced only after resolution returns, so a read from in there sees the PRE-commit epoch's
926
1052
  * exporter secret, which is the epoch the blob being opened was sealed under. Both are silent
927
1053
  * consequences of this method's plainness; wrapping it "for consistency" breaks both.
928
- */ async exportSecret(label, context, length = 32) {
1054
+ */ async exportSecret({ label, context, length = 32 }) {
929
1055
  return await mlsExporter(this.#state.keySchedule.exporterSecret, label, context, length, this.#context.cipherSuite);
930
1056
  }
931
1057
  /**
@@ -952,7 +1078,7 @@ function ledgerLogEntry(entryID, token, verified) {
952
1078
  enactedDeviceEntries: []
953
1079
  })
954
1080
  });
955
- gate.check({
1081
+ await gate.check({
956
1082
  kind: 'proposal',
957
1083
  proposal: {
958
1084
  proposal,
@@ -982,10 +1108,10 @@ function ledgerLogEntry(entryID, token, verified) {
982
1108
  * `opts.aad` becomes the frame's MLS `authenticated_data` — bound into the AEAD but
983
1109
  * carried in the clear, so a caller reading it back (or comparing via `decrypt`'s
984
1110
  * `expectedAAD`) needs no key. Defaults to empty.
985
- */ async encrypt(plaintext, opts) {
1111
+ */ async encrypt({ plaintext, ...opts }) {
986
1112
  return mutexFor(this).run(async ()=>{
987
1113
  const own = leafAt(this.#state.ratchetTree, this.#state.privatePath.leafIndex);
988
- if (own != null && isLapsed(this, own)) throw new LeafLapsedError('lapsed');
1114
+ if (own != null && await isLapsed(this, own)) throw new LeafLapsedError('lapsed');
989
1115
  const { newState, message, consumed } = await createApplicationMessage({
990
1116
  context: this.#context,
991
1117
  state: this.#state,
@@ -1009,7 +1135,9 @@ function ledgerLogEntry(entryID, token, verified) {
1009
1135
  * For a host that restores a persisted state and must not reuse a generation it may have
1010
1136
  * sent from before a crash. Each skipped generation costs one KDF step, not an encrypt.
1011
1137
  * Receivers must still cross the gap: ts-mls refuses a jump beyond its forward-ratchet
1012
- * window (`maximumForwardRatchetSteps`, 200 by default).
1138
+ * window (`maximumForwardRatchetSteps`: 512 for a kumiai context, see
1139
+ * `KUMIAI_KEY_RETENTION_CONFIG`; 200 in ts-mls's default, which a peer on an older
1140
+ * release still applies).
1013
1141
  *
1014
1142
  * No cap by default: a host catching up a stored high-water mark may legitimately step
1015
1143
  * far past any receiver's position (a receiver's window counts from the last generation
@@ -1019,7 +1147,7 @@ function ledgerLogEntry(entryID, token, verified) {
1019
1147
  * Refuses exactly as {@link encrypt} would: a lapsed leaf, unapplied proposals, a
1020
1148
  * removed or suspended member. `target` must be below 0xffffffff, the last generation.
1021
1149
  * On any throw the handle state is unchanged and the secrets derived so far are zeroed.
1022
- */ async advanceSenderGeneration(target, opts) {
1150
+ */ async advanceSenderGeneration({ target, ...opts }) {
1023
1151
  // 0xffffffff is the last uint32 generation: no frame could follow it.
1024
1152
  if (!Number.isInteger(target) || target < 0 || target >= 0xffffffff) {
1025
1153
  throw new RangeError(`advanceSenderGeneration: ${target} is not a sendable uint32 generation`);
@@ -1030,7 +1158,7 @@ function ledgerLogEntry(entryID, token, verified) {
1030
1158
  }
1031
1159
  return mutexFor(this).run(async ()=>{
1032
1160
  const own = leafAt(this.#state.ratchetTree, this.#state.privatePath.leafIndex);
1033
- if (own != null && isLapsed(this, own)) throw new LeafLapsedError('lapsed');
1161
+ if (own != null && await isLapsed(this, own)) throw new LeafLapsedError('lapsed');
1034
1162
  checkCanSendApplicationMessages(this.#state);
1035
1163
  const node = Number(this.#state.privatePath.leafIndex) * 2;
1036
1164
  const current = this.#state.secretTree.leafNodes[node]?.application.generation ?? 0;
@@ -1211,7 +1339,7 @@ function ledgerLogEntry(entryID, token, verified) {
1211
1339
  * `authenticatedData` BEFORE `mlsProcessMessage` runs — a mismatch throws having consumed
1212
1340
  * no ratchet generation, so a wrong-topic frame costs nothing to reject. The frame's AAD
1213
1341
  * is always returned, whether or not `expectedAAD` was given.
1214
- */ async decrypt(message, opts) {
1342
+ */ async decrypt({ message, ...opts }) {
1215
1343
  const decoded = decode(mlsMessageDecoder, message);
1216
1344
  if (decoded == null) throw new Error('decrypt: failed to decode MLSMessage');
1217
1345
  return mutexFor(this).run(async ()=>{
@@ -1227,7 +1355,7 @@ function ledgerLogEntry(entryID, token, verified) {
1227
1355
  const historical = this.#state.historicalReceiverData.get(pm.epoch);
1228
1356
  const epochTree = historical?.ratchetTree ?? this.#state.ratchetTree;
1229
1357
  const leafIndex = await readSenderLeafIndex(this.#context, historical?.senderDataSecret ?? this.#state.keySchedule.senderDataSecret, pm);
1230
- assertSenderNotLapsed({
1358
+ await assertSenderNotLapsed({
1231
1359
  group: this,
1232
1360
  tree: epochTree,
1233
1361
  leafIndex,
@@ -1259,7 +1387,7 @@ function ledgerLogEntry(entryID, token, verified) {
1259
1387
  * The callback runs under this handle's mutex and must store `stagedState` as the
1260
1388
  * group's handle state. It must not call this handle or the peer. If opening or
1261
1389
  * persistence fails, the live state and its ratchet secrets remain untouched.
1262
- */ async decryptStaged(message, opts, persist) {
1390
+ */ async decryptStaged({ message, opts, persist }) {
1263
1391
  const decoded = decode(mlsMessageDecoder, message);
1264
1392
  if (decoded == null) throw new Error('decryptStaged: failed to decode MLSMessage');
1265
1393
  return mutexFor(this).run(async ()=>{
@@ -1271,7 +1399,7 @@ function ledgerLogEntry(entryID, token, verified) {
1271
1399
  const historical = this.#state.historicalReceiverData.get(pm.epoch);
1272
1400
  const epochTree = historical?.ratchetTree ?? this.#state.ratchetTree;
1273
1401
  const leafIndex = await readSenderLeafIndex(this.#context, historical?.senderDataSecret ?? this.#state.keySchedule.senderDataSecret, pm);
1274
- assertSenderNotLapsed({
1402
+ await assertSenderNotLapsed({
1275
1403
  group: this,
1276
1404
  tree: epochTree,
1277
1405
  leafIndex,
@@ -1361,7 +1489,9 @@ function ledgerLogEntry(entryID, token, verified) {
1361
1489
  const id = ledgerEntryDigest(token);
1362
1490
  // Content-addressing binds the untrusted body to the requested id.
1363
1491
  if (resolved.has(id) || !missing.includes(id)) continue;
1364
- const verified = await verifyCachedLedgerEntry(token);
1492
+ const verified = await verifyCachedLedgerEntry(token, {
1493
+ crypto: this.#crypto
1494
+ });
1365
1495
  if (verified == null) continue;
1366
1496
  resolved.set(id, ledgerLogEntry(id, token, verified));
1367
1497
  }
@@ -1377,7 +1507,8 @@ function ledgerLogEntry(entryID, token, verified) {
1377
1507
  ]);
1378
1508
  return input;
1379
1509
  });
1380
- const foldResult = foldEnvelope({
1510
+ const foldResult = await foldEnvelope({
1511
+ crypto: this.#crypto,
1381
1512
  baseRoster: this.#roster,
1382
1513
  baseRegistry: this.#registry,
1383
1514
  entries: ordered,
@@ -1397,14 +1528,19 @@ function ledgerLogEntry(entryID, token, verified) {
1397
1528
  acceptedEntries = ordered;
1398
1529
  const proofCtx = {
1399
1530
  bindingOfDID: (d)=>this.bindingOfDID(d),
1400
- controllerOf: (d)=>controllerOf(this.#registry, d)
1531
+ controllerOf: (d)=>controllerOf({
1532
+ registry: this.#registry,
1533
+ deviceDID: d
1534
+ })
1401
1535
  };
1402
1536
  for (const { verified } of acceptedEntries){
1403
1537
  if (verified.entry.type !== DEVICE_ENTRY_TYPE) continue;
1404
1538
  if (this.#anchor.controller != null && verified.entry.value.op !== 'beacon') {
1405
1539
  continue;
1406
1540
  }
1407
- const ok = await verifyDeviceEntry(verified, proofCtx);
1541
+ const ok = await verifyDeviceEntry(verified, proofCtx, {
1542
+ crypto: this.#crypto
1543
+ });
1408
1544
  if (!ok) {
1409
1545
  precomputedReject = true;
1410
1546
  break;
@@ -1444,6 +1580,20 @@ function ledgerLogEntry(entryID, token, verified) {
1444
1580
  if (error instanceof RevokeProofError) capture.proofError = error;
1445
1581
  if (error instanceof LeafBindingError) capture.bindingError = error;
1446
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
+ };
1447
1597
  const combined = (incoming)=>{
1448
1598
  // A decode/fold failure is a hard reject even under a caller policy: the
1449
1599
  // ledger the commit depends on is unresolvable or malformed.
@@ -1451,35 +1601,60 @@ function ledgerLogEntry(entryID, token, verified) {
1451
1601
  capture.reason ??= capture.proofError == null ? 'invalid' : rejectionReason(capture.proofError);
1452
1602
  return 'reject';
1453
1603
  }
1454
- try {
1455
- gate?.check(incoming);
1456
- } 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;
1457
1611
  capture.reason = rejectionReason(error);
1458
1612
  if (error instanceof RevokeProofError) capture.proofError = error;
1459
1613
  if (error instanceof LeafBindingError) capture.bindingError = error;
1460
1614
  return 'reject';
1461
1615
  }
1462
1616
  if (callerPolicy != null) return callerPolicy(incoming);
1463
- return this.#anchor.controller == null ? defaultCommitPolicy(incoming, context) : 'accept';
1617
+ return this.#anchor.controller == null ? defaultCommitPolicy({
1618
+ incoming,
1619
+ context
1620
+ }) : 'accept';
1464
1621
  };
1465
- const applyOnAccept = (notify = true)=>{
1622
+ const applyOnAccept = async (notify = true)=>{
1466
1623
  // Appended, never deduped: the log records what this commit enacted, at the
1467
1624
  // position the head chained it.
1625
+ const ledger = [
1626
+ ...this.#ledger
1627
+ ];
1468
1628
  for (const { token, verified, entryID } of acceptedEntries){
1469
- this.#ledger.push({
1629
+ ledger.push({
1470
1630
  entryID,
1471
1631
  token,
1472
1632
  verified
1473
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){
1474
1650
  this.#entryBodies.set(entryID, {
1475
1651
  token,
1476
1652
  verified
1477
1653
  });
1478
1654
  }
1479
1655
  this.#roster = candidateRoster;
1480
- const folded = foldLedgerControl(this.#ledger, this.#anchor, this.groupID);
1481
- this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor);
1482
- this.#admission = this.#computeAdmission();
1656
+ this.#registry = registry;
1657
+ this.#admission = admission;
1483
1658
  const emit = ()=>{
1484
1659
  this.#notifyAccepted(surfaced, acceptedEntries.filter(({ verified })=>verified.entry.type === DEVICE_ENTRY_TYPE).map(({ verified })=>verified));
1485
1660
  };
@@ -1489,6 +1664,7 @@ function ledgerLogEntry(entryID, token, verified) {
1489
1664
  return {
1490
1665
  candidateRegistry,
1491
1666
  callback: wrapCommitPolicy(combined, capture),
1667
+ prejudge,
1492
1668
  capture,
1493
1669
  applyOnAccept,
1494
1670
  postApply: async (state)=>{
@@ -1693,7 +1869,7 @@ function ledgerLogEntry(entryID, token, verified) {
1693
1869
  * receive ratchet. It runs under this handle's mutex and must not call back into it.
1694
1870
  * It must write atomically: rejection means nothing was stored. Host callbacks run
1695
1871
  * after successful persist; a callback throw does not undo an advance.
1696
- */ async processMessage(message, opts) {
1872
+ */ async processMessage({ message, ...opts }) {
1697
1873
  let decoded = message;
1698
1874
  if (message instanceof Uint8Array) {
1699
1875
  const parsed = decode(mlsMessageDecoder, message);
@@ -1708,14 +1884,14 @@ function ledgerLogEntry(entryID, token, verified) {
1708
1884
  const proposalEpoch = privateProposal?.epoch ?? (frame.wireformat === wireformats.mls_public_message && frame.publicMessage.content.contentType === contentTypes.proposal ? frame.publicMessage.content.epoch : undefined);
1709
1885
  // Past proposals cannot be enacted at this epoch and need no ratchet or ledger work.
1710
1886
  if (proposalEpoch != null && proposalEpoch < this.epoch) return null;
1711
- const { callback, capture, applyOnAccept, postApply, candidateRegistry } = await this.#prepareCommitPipeline(decoded, opts);
1887
+ const { callback, prejudge, capture, applyOnAccept, postApply, candidateRegistry } = await this.#prepareCommitPipeline(decoded, opts);
1712
1888
  const previousState = this.#state;
1713
1889
  const previousAdmission = this.#admission;
1714
1890
  const application = readPrivateFrame(decoded, contentTypes.application);
1715
1891
  if (application != null) {
1716
1892
  const historical = this.#state.historicalReceiverData.get(application.epoch);
1717
1893
  const index = await readSenderLeafIndex(this.#context, historical?.senderDataSecret ?? this.#state.keySchedule.senderDataSecret, application);
1718
- assertSenderNotLapsed({
1894
+ await assertSenderNotLapsed({
1719
1895
  group: this,
1720
1896
  tree: historical?.ratchetTree ?? this.#state.ratchetTree,
1721
1897
  leafIndex: index,
@@ -1724,61 +1900,83 @@ function ledgerLogEntry(entryID, token, verified) {
1724
1900
  }
1725
1901
  let result;
1726
1902
  try {
1727
- result = await mlsProcessMessage({
1728
- context: {
1729
- ...this.#context,
1730
- authService: {
1731
- validateCredential: async (credential, key)=>{
1732
- try {
1733
- // Referenced Updates authenticate before the commit callback runs.
1734
- const proposed = (capture.rejected?.proposals ?? Object.values(this.#state.unappliedProposals)).find(({ proposal })=>{
1735
- if (!isDefaultProposal(proposal)) return false;
1736
- if (proposal.proposalType === defaultProposalTypes.add) return proposal.add.keyPackage.leafNode.credential === credential;
1737
- return proposal.proposalType === defaultProposalTypes.update && proposal.update.leafNode.credential === credential;
1738
- });
1739
- const index = proposed == null ? capture.committerLeafIndex : proposed.proposal.proposalType === defaultProposalTypes.update ? proposed.senderLeafIndex : undefined;
1740
- const retained = index != null && isUnchangedLeaf(this.#state.ratchetTree, index, {
1741
- credential,
1742
- signaturePublicKey: key
1743
- });
1744
- await verifyLeafCredential(credential, key, {
1745
- deviceDenySet: ()=>denySetOf(candidateRegistry),
1746
- judging: ()=>({
1747
- registry: this.#anchor.controller == null ? undefined : candidateRegistry,
1748
- stage: 'full',
1749
- mode: retained ? 'retain' : 'admit'
1750
- }),
1751
- // MLS re-validates the committer's path leaf after its proposals are judged:
1752
- // an evidenced child keeps a denied issuer only with the credential it
1753
- // already holds at that leaf.
1754
- mayKeepDeniedIssuer: ()=>this.#anchor.controller != null && retained,
1755
- leafLifetime: ()=>this.#anchor.controller == null ? undefined : this.#anchor.leafLifetime ?? 86_400,
1756
- trustedGrantLifetime: ()=>this.#anchor.controller == null ? undefined : this.#anchor.trustedGrantLifetime ?? 2_592_000
1757
- });
1758
- return true;
1759
- } catch (error) {
1760
- capture.reason = rejectionReason(error);
1761
- if (error instanceof LeafBindingError) capture.bindingError = error;
1762
- 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
+ }
1763
1943
  }
1764
1944
  }
1945
+ },
1946
+ state,
1947
+ message: decoded,
1948
+ ...action != null && {
1949
+ callback: action
1765
1950
  }
1766
- },
1767
- state: this.#state,
1768
- message: decoded,
1769
- ...callback != null && {
1770
- callback
1771
- }
1772
- });
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);
1773
1963
  } catch (error) {
1774
1964
  if (application != null) throw error;
1775
- 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
+ });
1776
1970
  rejection.cause = capture.bindingError ?? error;
1777
1971
  if (error instanceof Error) rejection.message += `: ${error.message}`;
1778
1972
  throw rejection;
1779
1973
  }
1780
1974
  if (result.kind === 'newState' && result.actionTaken === 'reject') {
1781
- 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
+ });
1782
1980
  const cause = capture.proofError ?? capture.bindingError;
1783
1981
  if (cause != null) rejection.cause = cause;
1784
1982
  throw rejection;
@@ -1787,7 +1985,11 @@ function ledgerLogEntry(entryID, token, verified) {
1787
1985
  try {
1788
1986
  await postApply(result.newState);
1789
1987
  } catch (error) {
1790
- 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
+ });
1791
1993
  rejection.cause = error;
1792
1994
  throw rejection;
1793
1995
  }
@@ -1808,7 +2010,7 @@ function ledgerLogEntry(entryID, token, verified) {
1808
2010
  ...previousLedger
1809
2011
  ];
1810
2012
  this.#entryBodies = new Map(previousEntryBodies);
1811
- const notify = applyOnAccept(false);
2013
+ const notify = await applyOnAccept(false);
1812
2014
  try {
1813
2015
  await opts.persist(this);
1814
2016
  } catch (error) {
@@ -1824,7 +2026,7 @@ function ledgerLogEntry(entryID, token, verified) {
1824
2026
  notify();
1825
2027
  } else {
1826
2028
  zeroAll(result.consumed);
1827
- applyOnAccept();
2029
+ await applyOnAccept();
1828
2030
  }
1829
2031
  return null;
1830
2032
  });
@@ -1835,7 +2037,10 @@ function ledgerLogEntry(entryID, token, verified) {
1835
2037
  for (const member of handle.listMembers())leafToDID.set(member.leafIndex, member.id);
1836
2038
  const headExt = readLedgerHeadExtension(handle);
1837
2039
  const currentHead = headExt != null && headExt.extensionData instanceof Uint8Array ? decodeLedgerHead(headExt.extensionData) : null;
1838
- 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
+ }));
1839
2044
  return {
1840
2045
  baseRoster: args.baseRoster,
1841
2046
  candidateRoster: args.candidateRoster,
@@ -1859,11 +2064,15 @@ function ledgerLogEntry(entryID, token, verified) {
1859
2064
  }
1860
2065
  };
1861
2066
  }
1862
- /** Build the handle a commit hands back: the post-commit state, everything else inherited. */ export function deriveGroup(group, state) {
1863
- 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({
1864
2069
  state,
1865
2070
  credential: group.credential,
1866
- context: createMlsContext(group.context.cipherSuite, group.anchor),
2071
+ // The post-commit handle keeps the source's receive retention, not ts-mls's defaults.
2072
+ context: createMlsContext(group.context.cipherSuite, group.anchor, group.context.clientConfig, {
2073
+ crypto: group.crypto
2074
+ }),
2075
+ crypto: group.crypto,
1867
2076
  ledger: group.ledger,
1868
2077
  commitPolicy: group.commitPolicy,
1869
2078
  resolveLedgerEntries: group.resolveLedgerEntries,