@kumiai/mls 0.10.0 → 0.10.2

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 (53) hide show
  1. package/lib/anchor.d.ts +10 -4
  2. package/lib/anchor.js +26 -2
  3. package/lib/authentication.d.ts +24 -12
  4. package/lib/authentication.js +192 -83
  5. package/lib/capability.d.ts +37 -0
  6. package/lib/capability.js +141 -0
  7. package/lib/credential.d.ts +7 -7
  8. package/lib/credential.js +15 -10
  9. package/lib/device-proof.d.ts +2 -0
  10. package/lib/device-proof.js +8 -12
  11. package/lib/envelope-fold.d.ts +16 -1
  12. package/lib/envelope-fold.js +49 -9
  13. package/lib/errors.d.ts +18 -0
  14. package/lib/errors.js +33 -0
  15. package/lib/group-commit.d.ts +24 -35
  16. package/lib/group-commit.js +139 -110
  17. package/lib/group-context.d.ts +6 -2
  18. package/lib/group-context.js +11 -4
  19. package/lib/group-create.js +56 -11
  20. package/lib/group-credential.d.ts +3 -1
  21. package/lib/group-credential.js +17 -3
  22. package/lib/group-device.js +34 -21
  23. package/lib/group-handle.d.ts +31 -8
  24. package/lib/group-handle.js +275 -58
  25. package/lib/group-lifecycle.d.ts +49 -0
  26. package/lib/group-lifecycle.js +341 -0
  27. package/lib/group-membership.js +7 -3
  28. package/lib/group-welcome.d.ts +11 -2
  29. package/lib/group-welcome.js +122 -22
  30. package/lib/group.d.ts +2 -1
  31. package/lib/group.js +1 -0
  32. package/lib/history.d.ts +6 -0
  33. package/lib/history.js +26 -0
  34. package/lib/index.d.ts +12 -5
  35. package/lib/index.js +10 -3
  36. package/lib/lifecycle-proof.d.ts +33 -0
  37. package/lib/lifecycle-proof.js +218 -0
  38. package/lib/lifecycle.d.ts +46 -0
  39. package/lib/lifecycle.js +410 -0
  40. package/lib/policy.d.ts +20 -0
  41. package/lib/policy.js +8 -5
  42. package/lib/recovery-verdict.d.ts +43 -0
  43. package/lib/recovery-verdict.js +135 -0
  44. package/lib/recovery.d.ts +70 -0
  45. package/lib/recovery.js +110 -36
  46. package/lib/registry.d.ts +34 -7
  47. package/lib/registry.js +113 -15
  48. package/lib/roster.d.ts +1 -1
  49. package/lib/roster.js +2 -2
  50. package/lib/secret-tree.d.ts +3 -0
  51. package/lib/secret-tree.js +60 -0
  52. package/lib/types.d.ts +13 -8
  53. package/package.json +5 -5
@@ -1,19 +1,22 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
2
  import { EventEmitter } from '@sozai/event';
3
- import { contentTypes, createApplicationMessage, decode, encode, mlsExporter, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, wireformats } from 'ts-mls';
3
+ import { contentTypes, createApplicationMessage, createProposal, decode, defaultProposalTypes, encode, mlsExporter, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, wireformats } from 'ts-mls';
4
4
  import { readGroupAnchor } from './anchor.js';
5
+ import { verifyLeafCredential } from './authentication.js';
5
6
  import { encodeClientState } from './codec.js';
6
- import { parseMLSCredentialIdentity } from './credential.js';
7
+ import { didFromCredential, parseMLSCredentialIdentity } from './credential.js';
7
8
  import { verifyDeviceEntry } from './device-proof.js';
8
9
  import { decodeControlEnvelope } from './envelope.js';
9
10
  import { foldEnvelope, GROUP_TYPE_PREFIX } from './envelope-fold.js';
10
- import { deviceDenyHolderFor } from './group-context.js';
11
+ import { LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
12
+ import { createMlsContext, deviceDenyHolderFor } from './group-context.js';
11
13
  import { readMessageEpoch } from './group-info.js';
12
14
  import { assertHeadMatches, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, headsMatch, readLedgerHead, readLedgerHeadExtension } from './head.js';
13
15
  import { ledgerEntryDigest, verifyLedgerEntry } from './ledger.js';
16
+ import { assertSenderNotLapsed, isLapsed, isUnchangedLeaf, leafAt, prepareLifecycleGate, rejectionReason } from './lifecycle.js';
14
17
  import { createMutex } from './mutex.js';
15
18
  import { defaultCommitPolicy, MissingLedgerEntriesError } from './policy.js';
16
- import { beaconOf, controllerOf, DEVICE_ENTRY_TYPE, denySetOf, foldControl, isDeviceValue } from './registry.js';
19
+ import { beaconOf, controllerOf, DEVICE_ENTRY_TYPE, denySetOf, foldControl, isDeviceValue, revocationOf } from './registry.js';
17
20
  import { readSenderLeafIndex } from './sender-data.js';
18
21
  /** One serializer per live handle, so its state-mutating operations run one at a
19
22
  * time in issue order. Keyed weakly: the entry is collected with the handle, and
@@ -47,12 +50,17 @@ export function mutexFor(handle) {
47
50
  * commit. The handle is left at its pre-commit epoch. */ export class CommitRejectedError extends Error {
48
51
  #proposals;
49
52
  #senderLeafIndex;
50
- constructor(proposals, senderLeafIndex){
53
+ #reason;
54
+ constructor(proposals, senderLeafIndex, reason = 'policy'){
51
55
  super('Commit rejected by group commit policy');
52
56
  this.name = 'CommitRejectedError';
57
+ this.#reason = reason;
53
58
  this.#proposals = proposals;
54
59
  this.#senderLeafIndex = senderLeafIndex;
55
60
  }
61
+ get reason() {
62
+ return this.#reason;
63
+ }
56
64
  get proposals() {
57
65
  return this.#proposals;
58
66
  }
@@ -63,16 +71,18 @@ export function mutexFor(handle) {
63
71
  /**
64
72
  * Wrap a consumer commit policy to capture a rejected commit's proposals for
65
73
  * CommitRejectedError. ts-mls does not surface them on its result, so record them
66
- * from the callback's own argument on the 'reject' path. Undefined when no policy.
74
+ * before either the proposal or path gate can reject. Undefined when no policy.
67
75
  */ function wrapCommitPolicy(callback, capture) {
68
76
  if (callback == null) return undefined;
69
77
  return (incoming)=>{
70
78
  const action = callback(incoming);
71
- if (action === 'reject' && incoming.kind === 'commit') {
79
+ if (incoming.kind === 'commit') {
80
+ const senderLeafIndex = incoming.senderLeafIndex == null ? undefined : Number(incoming.senderLeafIndex);
72
81
  capture.rejected = {
73
82
  proposals: incoming.proposals,
74
- senderLeafIndex: incoming.senderLeafIndex == null ? undefined : Number(incoming.senderLeafIndex)
83
+ senderLeafIndex
75
84
  };
85
+ capture.committerLeafIndex = senderLeafIndex;
76
86
  }
77
87
  return action;
78
88
  };
@@ -187,6 +197,8 @@ export function mutexFor(handle) {
187
197
  * the same wherever it appears in the log, so this store is keyed. */ #entryBodies;
188
198
  #roster;
189
199
  #registry;
200
+ #admission;
201
+ #pendingControlEvents;
190
202
  constructor(params){
191
203
  this.#state = params.state;
192
204
  this.#credential = params.credential;
@@ -215,12 +227,36 @@ export function mutexFor(handle) {
215
227
  const folded = foldLedgerControl(this.#ledger, anchor, this.groupID);
216
228
  this.#roster = folded.roster;
217
229
  this.#registry = folded.registry;
218
- // Point this context's deny holder at THIS handle. deriveGroup shares the context object, so a
219
- // derived (post-commit) handle re-points it to itself — always the newest, live registry. A
220
- // context not built by resolveMlsContext (none in the codebase) simply has no holder.
230
+ // Authentication reads only this handle's registry and lifetime limits.
221
231
  const denyHolder = deviceDenyHolderFor(this.#context);
222
- if (denyHolder != null) denyHolder.provider = ()=>this.currentDenySet();
232
+ if (denyHolder != null) {
233
+ denyHolder.provider = ()=>this.currentDenySet();
234
+ denyHolder.leafLifetime = anchor.controller == null ? undefined : anchor.leafLifetime ?? 86_400;
235
+ denyHolder.trustedGrantLifetime = anchor.controller == null ? undefined : anchor.trustedGrantLifetime ?? 2_592_000;
236
+ }
223
237
  EMITTERS.set(this, params.events ?? new EventEmitter());
238
+ this.#pendingControlEvents = params.speculative ? [] : undefined;
239
+ this.#admission = this.#computeAdmission();
240
+ }
241
+ #computeAdmission() {
242
+ const leaf = leafAt(this.#state.ratchetTree, this.#state.privatePath.leafIndex);
243
+ const epoch = Number(this.epoch);
244
+ return Object.freeze(leaf != null && isLapsed(this, leaf) ? {
245
+ epoch,
246
+ admissible: false,
247
+ reason: 'lapsed'
248
+ } : {
249
+ epoch,
250
+ admissible: true
251
+ });
252
+ }
253
+ sendAdmission() {
254
+ return this.#admission;
255
+ }
256
+ confirmAdopted() {
257
+ const pending = this.#pendingControlEvents;
258
+ this.#pendingControlEvents = undefined;
259
+ if (pending != null) this.emitControlEvents(pending);
224
260
  }
225
261
  get groupID() {
226
262
  return this.#credential.groupID;
@@ -301,19 +337,31 @@ export function mutexFor(handle) {
301
337
  }
302
338
  /**
303
339
  * @internal Fire notification events for the device entries just enacted in one operation.
304
- * Called from the commit path, from bootstrapLedger, and from the local write APIs — NEVER from
340
+ * Called after acceptance or adoption — NEVER from
305
341
  * the constructor or a fresh-join applyLedgerEntries, so a joiner is not replayed the whole
306
342
  * history as live events (it reads revokedDevices()/beaconOf for current state instead). Uses
307
- * `fire`: a throwing listener is swallowed and cannot break the fold. Reads controllerOf on the
308
- * POST-fold registry.
343
+ * `fire`: a throwing listener is swallowed and cannot break the fold. Reads the post-fold registry.
309
344
  */ emitControlEvents(enacted) {
345
+ if (this.#pendingControlEvents != null) {
346
+ this.#pendingControlEvents.push(...enacted);
347
+ return;
348
+ }
310
349
  const emitter = emitterOf(this);
311
350
  const revoked = [];
312
351
  for (const { entry } of enacted){
313
352
  if (entry.type !== DEVICE_ENTRY_TYPE || !isDeviceValue(entry.value)) continue;
314
353
  const value = entry.value;
315
354
  const subject = normalizeDID(entry.subject);
316
- if (value.op === 'revoke') {
355
+ if (this.#anchor.controller != null && (value.op === 'revoke' || value.op === 'reset')) {
356
+ for (const effect of value.revoked ?? []){
357
+ const device = normalizeDID(effect.did);
358
+ const record = revocationOf(this, device);
359
+ if (record != null) revoked.push({
360
+ device,
361
+ ...record
362
+ });
363
+ }
364
+ } else if (value.op === 'revoke') {
317
365
  const controller = controllerOf(this.#registry, subject);
318
366
  if (controller != null) revoked.push({
319
367
  device: subject,
@@ -377,6 +425,10 @@ export function mutexFor(handle) {
377
425
  const folded = foldLedgerControl(this.#ledger, this.#anchor, this.groupID);
378
426
  this.#roster = folded.roster;
379
427
  this.#registry = folded.registry;
428
+ this.#admission = this.#computeAdmission();
429
+ if (this.#pendingControlEvents != null) {
430
+ this.emitControlEvents(appended.filter(({ entry })=>entry.type === DEVICE_ENTRY_TYPE));
431
+ }
380
432
  return appended;
381
433
  });
382
434
  }
@@ -471,7 +523,8 @@ export function mutexFor(handle) {
471
523
  ledger: this.#ledger,
472
524
  entryBodies: this.#entryBodies,
473
525
  roster: this.#roster,
474
- registry: this.#registry
526
+ registry: this.#registry,
527
+ admission: this.#admission
475
528
  };
476
529
  const folded = foldLedgerControl(log, this.#anchor, this.groupID);
477
530
  this.#ledger = log;
@@ -484,6 +537,7 @@ export function mutexFor(handle) {
484
537
  ]));
485
538
  this.#roster = folded.roster;
486
539
  this.#registry = folded.registry;
540
+ this.#admission = this.#computeAdmission();
487
541
  try {
488
542
  await opts?.persist?.(this);
489
543
  } catch (error) {
@@ -492,6 +546,7 @@ export function mutexFor(handle) {
492
546
  this.#entryBodies = previous.entryBodies;
493
547
  this.#roster = previous.roster;
494
548
  this.#registry = previous.registry;
549
+ this.#admission = previous.admission;
495
550
  throw error;
496
551
  }
497
552
  // SURFACED HERE TOO, not only on the commit path. A heal is how a peer that missed commits
@@ -614,6 +669,50 @@ export function mutexFor(handle) {
614
669
  return await mlsExporter(this.#state.keySchedule.exporterSecret, label, context, length, this.#context.cipherSuite);
615
670
  }
616
671
  /**
672
+ * Author and retain an authenticated self-removal proposal under the handle mutex.
673
+ * Once a member processes a pending self-removal, application encrypt throws until
674
+ * a commit lands. Callers should commit pending self-removals promptly.
675
+ */ async proposeSelfRemoval() {
676
+ return mutexFor(this).run(async ()=>{
677
+ const senderLeafIndex = this.#state.privatePath.leafIndex;
678
+ const proposal = {
679
+ proposalType: defaultProposalTypes.remove,
680
+ remove: {
681
+ removed: senderLeafIndex
682
+ }
683
+ };
684
+ const gate = await prepareLifecycleGate({
685
+ group: this,
686
+ entries: [],
687
+ candidateRegistry: this.#registry,
688
+ context: buildCommitPolicyContext(this, {
689
+ baseRoster: this.#roster,
690
+ candidateRoster: this.#roster,
691
+ entryIDs: [],
692
+ enactedDeviceEntries: []
693
+ })
694
+ });
695
+ gate.check({
696
+ kind: 'proposal',
697
+ proposal: {
698
+ proposal,
699
+ senderLeafIndex
700
+ }
701
+ });
702
+ const result = await createProposal({
703
+ context: this.#context,
704
+ state: this.#state,
705
+ proposal
706
+ });
707
+ this.#state = result.newState;
708
+ zeroAll(result.consumed);
709
+ return {
710
+ frame: encode(mlsMessageEncoder, result.message),
711
+ epoch: this.epoch
712
+ };
713
+ });
714
+ }
715
+ /**
617
716
  * Encrypt an application message for the group at this handle's current epoch,
618
717
  * returning framed wire bytes. A handle a commit has already superseded (see
619
718
  * {@link commitInvite}, {@link removeMember}, {@link commitLedgerEntries}) must not
@@ -625,6 +724,8 @@ export function mutexFor(handle) {
625
724
  * `expectedAAD`) needs no key. Defaults to empty.
626
725
  */ async encrypt(plaintext, opts) {
627
726
  return mutexFor(this).run(async ()=>{
727
+ const own = leafAt(this.#state.ratchetTree, this.#state.privatePath.leafIndex);
728
+ if (own != null && isLapsed(this, own)) throw new LeafLapsedError('lapsed');
628
729
  const { newState, message, consumed } = await createApplicationMessage({
629
730
  context: this.#context,
630
731
  state: this.#state,
@@ -675,7 +776,15 @@ export function mutexFor(handle) {
675
776
  }
676
777
  // Read the sender BEFORE opening: the sender-data secret is epoch-level and this
677
778
  // consumes no ratchet key, so a frame that then fails to open has cost nothing.
678
- const leafIndex = await readSenderLeafIndex(this.#context, this.#state.keySchedule.senderDataSecret, pm);
779
+ const historical = this.#state.historicalReceiverData.get(pm.epoch);
780
+ const epochTree = historical?.ratchetTree ?? this.#state.ratchetTree;
781
+ const leafIndex = await readSenderLeafIndex(this.#context, historical?.senderDataSecret ?? this.#state.keySchedule.senderDataSecret, pm);
782
+ assertSenderNotLapsed({
783
+ group: this,
784
+ tree: epochTree,
785
+ leafIndex,
786
+ extensions: (historical?.groupContext ?? this.#state.groupContext).extensions
787
+ });
679
788
  const result = await mlsProcessMessage({
680
789
  context: this.#context,
681
790
  state: this.#state,
@@ -686,7 +795,8 @@ export function mutexFor(handle) {
686
795
  if (result.kind !== 'applicationMessage') {
687
796
  throw new Error('decrypt: frame was not an application message');
688
797
  }
689
- const senderDID = leafIndex == null ? undefined : this.#didOfLeaf(leafIndex);
798
+ const senderLeaf = leafIndex == null ? undefined : leafAt(epochTree, leafIndex);
799
+ const senderDID = senderLeaf == null ? undefined : didFromCredential(senderLeaf.credential);
690
800
  return {
691
801
  payload: result.message,
692
802
  aad: result.aad,
@@ -710,7 +820,15 @@ export function mutexFor(handle) {
710
820
  if (opts.expectedAAD != null && !bytesEqual(pm.authenticatedData, opts.expectedAAD)) {
711
821
  throw new Error('decryptStaged: frame authenticated data does not match expected AAD');
712
822
  }
713
- const leafIndex = await readSenderLeafIndex(this.#context, this.#state.keySchedule.senderDataSecret, pm);
823
+ const historical = this.#state.historicalReceiverData.get(pm.epoch);
824
+ const epochTree = historical?.ratchetTree ?? this.#state.ratchetTree;
825
+ const leafIndex = await readSenderLeafIndex(this.#context, historical?.senderDataSecret ?? this.#state.keySchedule.senderDataSecret, pm);
826
+ assertSenderNotLapsed({
827
+ group: this,
828
+ tree: epochTree,
829
+ leafIndex,
830
+ extensions: (historical?.groupContext ?? this.#state.groupContext).extensions
831
+ });
714
832
  const result = await mlsProcessMessage({
715
833
  context: this.#context,
716
834
  state: this.#state,
@@ -719,7 +837,8 @@ export function mutexFor(handle) {
719
837
  if (result.kind !== 'applicationMessage') {
720
838
  throw new Error('decryptStaged: frame was not an application message');
721
839
  }
722
- const senderDID = leafIndex == null ? undefined : this.#didOfLeaf(leafIndex);
840
+ const senderLeaf = leafIndex == null ? undefined : leafAt(epochTree, leafIndex);
841
+ const senderDID = senderLeaf == null ? undefined : didFromCredential(senderLeaf.credential);
723
842
  if (senderDID == null) throw new Error('decryptStaged: unnamed sender');
724
843
  const opened = {
725
844
  payload: result.message,
@@ -732,20 +851,7 @@ export function mutexFor(handle) {
732
851
  return opened;
733
852
  });
734
853
  }
735
- /**
736
- * The async pre-pass feeding the synchronous ts-mls commit callback, run before
737
- * mlsProcessMessage. For anything that is not a PrivateMessage commit it just
738
- * resolves the caller policy, wraps it for rejected-proposal capture, and applies
739
- * nothing on accept.
740
- *
741
- * For a PrivateMessage commit it decodes the control envelope, resolves and
742
- * verifies the entry bodies it names, folds a candidate roster off the pre-commit
743
- * state, and precomputes the pure inputs the sync callback reads. That callback is
744
- * a pure lookup: decode/fold failure is a hard reject; else a caller policy wins,
745
- * and with none the anchored default policy runs. Missing entry bodies with no
746
- * resolver throw MissingLedgerEntriesError HERE — before mlsProcessMessage — so the
747
- * handle stays at its pre-commit epoch.
748
- */ async #prepareCommitPipeline(decoded, opts) {
854
+ /** Resolve ledger inputs before MLS, then run mandatory gates before caller role policy. */ async #prepareCommitPipeline(decoded, opts) {
749
855
  const callerPolicy = opts?.commitPolicy ?? this.#commitPolicy;
750
856
  const capture = {};
751
857
  const commit = readPrivateCommit(decoded);
@@ -826,9 +932,19 @@ export function mutexFor(handle) {
826
932
  ]);
827
933
  return input;
828
934
  });
829
- const foldResult = foldEnvelope(this.#roster, this.#registry, ordered, this.groupID);
935
+ const foldResult = foldEnvelope({
936
+ baseRoster: this.#roster,
937
+ baseRegistry: this.#registry,
938
+ entries: ordered,
939
+ groupID: this.groupID,
940
+ context: this.#anchor.controller == null ? undefined : {
941
+ controllerID: this.#anchor.controller,
942
+ memberController: (did)=>this.bindingOfDID(did)?.controller
943
+ }
944
+ });
830
945
  if (!foldResult.ok) {
831
946
  precomputedReject = true;
947
+ capture.proofError = foldResult.error;
832
948
  } else {
833
949
  candidateRoster = foldResult.roster;
834
950
  candidateRegistry = foldResult.registry;
@@ -840,6 +956,9 @@ export function mutexFor(handle) {
840
956
  };
841
957
  for (const { verified } of acceptedEntries){
842
958
  if (verified.entry.type !== DEVICE_ENTRY_TYPE) continue;
959
+ if (this.#anchor.controller != null && verified.entry.value.op !== 'beacon') {
960
+ continue;
961
+ }
843
962
  const ok = await verifyDeviceEntry(verified, proofCtx);
844
963
  if (!ok) {
845
964
  precomputedReject = true;
@@ -863,12 +982,40 @@ export function mutexFor(handle) {
863
982
  externalCommitDID
864
983
  }
865
984
  });
985
+ let gate;
986
+ try {
987
+ const frame = decoded;
988
+ const externalLeaf = frame.wireformat === wireformats.mls_public_message && frame.publicMessage.content.contentType === contentTypes.commit && frame.publicMessage.senderType === senderTypes.new_member_commit ? frame.publicMessage.content.commit.path?.leafNode : undefined;
989
+ gate = await prepareLifecycleGate({
990
+ group: this,
991
+ entries: acceptedEntries.map(({ verified })=>verified),
992
+ candidateRegistry,
993
+ context,
994
+ externalLeaf
995
+ });
996
+ } catch (error) {
997
+ precomputedReject = true;
998
+ capture.reason = rejectionReason(error);
999
+ if (error instanceof RevokeProofError) capture.proofError = error;
1000
+ if (error instanceof LeafBindingError) capture.bindingError = error;
1001
+ }
866
1002
  const combined = (incoming)=>{
867
1003
  // A decode/fold failure is a hard reject even under a caller policy: the
868
1004
  // ledger the commit depends on is unresolvable or malformed.
869
- if (precomputedReject) return 'reject';
1005
+ if (precomputedReject) {
1006
+ capture.reason ??= capture.proofError == null ? 'invalid' : rejectionReason(capture.proofError);
1007
+ return 'reject';
1008
+ }
1009
+ try {
1010
+ gate?.check(incoming);
1011
+ } catch (error) {
1012
+ capture.reason = rejectionReason(error);
1013
+ if (error instanceof RevokeProofError) capture.proofError = error;
1014
+ if (error instanceof LeafBindingError) capture.bindingError = error;
1015
+ return 'reject';
1016
+ }
870
1017
  if (callerPolicy != null) return callerPolicy(incoming);
871
- return defaultCommitPolicy(incoming, context);
1018
+ return this.#anchor.controller == null ? defaultCommitPolicy(incoming, context) : 'accept';
872
1019
  };
873
1020
  const applyOnAccept = (notify = true)=>{
874
1021
  // Appended, never deduped: the log records what this commit enacted, at the
@@ -886,6 +1033,7 @@ export function mutexFor(handle) {
886
1033
  }
887
1034
  this.#roster = candidateRoster;
888
1035
  this.#registry = candidateRegistry;
1036
+ this.#admission = this.#computeAdmission();
889
1037
  const emit = ()=>{
890
1038
  this.#notifyAccepted(surfaced, acceptedEntries.filter(({ verified })=>verified.entry.type === DEVICE_ENTRY_TYPE).map(({ verified })=>verified));
891
1039
  };
@@ -895,7 +1043,10 @@ export function mutexFor(handle) {
895
1043
  return {
896
1044
  callback: wrapCommitPolicy(combined, capture),
897
1045
  capture,
898
- applyOnAccept
1046
+ applyOnAccept,
1047
+ postApply: async (state)=>{
1048
+ await gate?.postApply(state);
1049
+ }
899
1050
  };
900
1051
  }
901
1052
  /**
@@ -971,7 +1122,11 @@ export function mutexFor(handle) {
971
1122
  leafKey: node.leaf.signaturePublicKey,
972
1123
  ...parsed.controller != null ? {
973
1124
  controller: parsed.controller.id,
974
- prefix: parsed.controller.prefix
1125
+ prefix: parsed.controller.prefix,
1126
+ capability: parsed.controller.capability,
1127
+ ...parsed.controller.holderGrant == null ? {} : {
1128
+ holderGrant: parsed.controller.holderGrant
1129
+ }
975
1130
  } : {}
976
1131
  };
977
1132
  }
@@ -1080,6 +1235,7 @@ export function mutexFor(handle) {
1080
1235
  * Process a received MLS message (Commit, Proposal, or application). Accepts
1081
1236
  * wire-form bytes (preferred, e.g. from commitInvite/removeMember) or a pre-decoded
1082
1237
  * ts-mls framed message (legacy). The runtime `instanceof` selects the decode path.
1238
+ * A proposal from a past epoch is ignored (returns null, nothing persisted).
1083
1239
  * `persist` covers accepted commits and proposals, not application messages or their
1084
1240
  * receive ratchet. It runs under this handle's mutex and must not call back into it.
1085
1241
  * It must write atomically: rejection means nothing was stored. Host callbacks run
@@ -1094,21 +1250,83 @@ export function mutexFor(handle) {
1094
1250
  decoded = parsed;
1095
1251
  }
1096
1252
  return mutexFor(this).run(async ()=>{
1097
- const { callback, capture, applyOnAccept } = await this.#prepareCommitPipeline(decoded, opts);
1253
+ const privateProposal = readPrivateFrame(decoded, contentTypes.proposal);
1254
+ const frame = decoded;
1255
+ const proposalEpoch = privateProposal?.epoch ?? (frame.wireformat === wireformats.mls_public_message && frame.publicMessage.content.contentType === contentTypes.proposal ? frame.publicMessage.content.epoch : undefined);
1256
+ // Past proposals cannot be enacted at this epoch and need no ratchet or ledger work.
1257
+ if (proposalEpoch != null && proposalEpoch < this.epoch) return null;
1258
+ const { callback, capture, applyOnAccept, postApply } = await this.#prepareCommitPipeline(decoded, opts);
1098
1259
  const previousState = this.#state;
1099
- const result = await mlsProcessMessage({
1100
- context: this.#context,
1101
- state: this.#state,
1102
- message: decoded,
1103
- ...callback != null && {
1104
- callback
1105
- }
1106
- });
1107
- this.#state = result.newState;
1260
+ const previousAdmission = this.#admission;
1261
+ const application = readPrivateFrame(decoded, contentTypes.application);
1262
+ if (application != null) {
1263
+ const historical = this.#state.historicalReceiverData.get(application.epoch);
1264
+ const index = await readSenderLeafIndex(this.#context, historical?.senderDataSecret ?? this.#state.keySchedule.senderDataSecret, application);
1265
+ assertSenderNotLapsed({
1266
+ group: this,
1267
+ tree: historical?.ratchetTree ?? this.#state.ratchetTree,
1268
+ leafIndex: index,
1269
+ extensions: (historical?.groupContext ?? this.#state.groupContext).extensions
1270
+ });
1271
+ }
1272
+ let result;
1273
+ try {
1274
+ result = await mlsProcessMessage({
1275
+ context: {
1276
+ ...this.#context,
1277
+ authService: {
1278
+ validateCredential: async (credential, key)=>{
1279
+ try {
1280
+ await verifyLeafCredential(credential, key, {
1281
+ deviceDenySet: ()=>this.currentDenySet(),
1282
+ // MLS re-validates the committer's path leaf after its proposals are judged:
1283
+ // an evidenced child keeps a denied issuer only with the credential it
1284
+ // already holds at that leaf.
1285
+ mayKeepDeniedIssuer: (leafCredential, leafKey)=>this.#anchor.controller != null && capture.committerLeafIndex != null && isUnchangedLeaf(this.#state.ratchetTree, capture.committerLeafIndex, {
1286
+ credential: leafCredential,
1287
+ signaturePublicKey: leafKey
1288
+ }),
1289
+ leafLifetime: ()=>this.#anchor.controller == null ? undefined : this.#anchor.leafLifetime ?? 86_400,
1290
+ trustedGrantLifetime: ()=>this.#anchor.controller == null ? undefined : this.#anchor.trustedGrantLifetime ?? 2_592_000
1291
+ });
1292
+ return true;
1293
+ } catch (error) {
1294
+ capture.reason = rejectionReason(error);
1295
+ if (error instanceof LeafBindingError) capture.bindingError = error;
1296
+ return false;
1297
+ }
1298
+ }
1299
+ }
1300
+ },
1301
+ state: this.#state,
1302
+ message: decoded,
1303
+ ...callback != null && {
1304
+ callback
1305
+ }
1306
+ });
1307
+ } catch (error) {
1308
+ if (application != null) throw error;
1309
+ const rejection = new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex, capture.reason ?? 'invalid');
1310
+ rejection.cause = capture.bindingError ?? error;
1311
+ if (error instanceof Error) rejection.message += `: ${error.message}`;
1312
+ throw rejection;
1313
+ }
1108
1314
  if (result.kind === 'newState' && result.actionTaken === 'reject') {
1109
- zeroAll(result.consumed);
1110
- throw new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex);
1315
+ const rejection = new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex, capture.reason ?? 'policy');
1316
+ const cause = capture.proofError ?? capture.bindingError;
1317
+ if (cause != null) rejection.cause = cause;
1318
+ throw rejection;
1319
+ }
1320
+ if (result.kind === 'newState') {
1321
+ try {
1322
+ await postApply(result.newState);
1323
+ } catch (error) {
1324
+ const rejection = new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex, rejectionReason(error));
1325
+ rejection.cause = error;
1326
+ throw rejection;
1327
+ }
1111
1328
  }
1329
+ this.#state = result.newState;
1112
1330
  if (result.kind === 'applicationMessage') {
1113
1331
  zeroAll(result.consumed);
1114
1332
  return result.message;
@@ -1133,6 +1351,7 @@ export function mutexFor(handle) {
1133
1351
  this.#entryBodies = previousEntryBodies;
1134
1352
  this.#roster = previousRoster;
1135
1353
  this.#registry = previousRegistry;
1354
+ this.#admission = previousAdmission;
1136
1355
  throw error;
1137
1356
  }
1138
1357
  zeroAll(result.consumed);
@@ -1145,10 +1364,7 @@ export function mutexFor(handle) {
1145
1364
  });
1146
1365
  }
1147
1366
  }
1148
- /** Build the CommitPolicyContext both the receive gate and the send-side pending
1149
- * filter judge against, so the two always agree. `entryIDs` are the ledger entry
1150
- * ids this commit enacts (drives the expected head); `candidateRoster` is the
1151
- * post-fold roster receivers install. */ export function buildCommitPolicyContext(handle, args) {
1367
+ /** Build policy inputs shared by author and receiver gates. Entry ids drive the expected head. */ export function buildCommitPolicyContext(handle, args) {
1152
1368
  const leafToDID = new Map();
1153
1369
  for (const member of handle.listMembers())leafToDID.set(member.leafIndex, member.id);
1154
1370
  const headExt = readLedgerHeadExtension(handle);
@@ -1181,11 +1397,12 @@ export function mutexFor(handle) {
1181
1397
  return new GroupHandle({
1182
1398
  state,
1183
1399
  credential: group.credential,
1184
- context: group.context,
1400
+ context: createMlsContext(group.context.cipherSuite, group.anchor),
1185
1401
  ledger: group.ledger,
1186
1402
  commitPolicy: group.commitPolicy,
1187
1403
  resolveLedgerEntries: group.resolveLedgerEntries,
1188
1404
  onLedgerEntries: group.onLedgerEntries,
1189
- events: emitterOf(group)
1405
+ events: emitterOf(group),
1406
+ speculative: true
1190
1407
  });
1191
1408
  }
@@ -0,0 +1,49 @@
1
+ import { type SignedEvent } from '@kokuin/controller';
2
+ import { type ControllerBinding } from './credential.js';
3
+ import { type RevokeProofReason } from './errors.js';
4
+ import type { DeviceWriteResult } from './group-device.js';
5
+ import { type GroupHandle } from './group-handle.js';
6
+ export type CommitResult = DeviceWriteResult;
7
+ /**
8
+ * Author a by-reference Remove for this handle's own leaf at its current epoch.
9
+ * Once a member processes a pending self-removal, application encrypt throws until
10
+ * a commit lands. Callers should commit pending self-removals promptly.
11
+ */
12
+ export declare function proposeSelfRemoval(group: GroupHandle): Promise<{
13
+ frame: Uint8Array;
14
+ epoch: bigint;
15
+ }>;
16
+ /**
17
+ * Commit other members' pending self-removals without absorbing other pending proposals.
18
+ * Returns null when only the committer's own self-removal (or none) is pending.
19
+ * Once a member processes a pending self-removal, application encrypt throws until
20
+ * a commit lands. Callers should commit pending self-removals promptly.
21
+ */
22
+ export declare function commitSelfRemovals(group: GroupHandle): Promise<CommitResult | null>;
23
+ export type RevokeBuildResult = {
24
+ status: 'built';
25
+ result: DeviceWriteResult;
26
+ } | {
27
+ status: 'already-revoked';
28
+ } | {
29
+ status: 'self-affected';
30
+ subject: string;
31
+ } | {
32
+ status: 'not-provable';
33
+ reason: RevokeProofReason;
34
+ };
35
+ export declare function renewLeaf(group: GroupHandle, binding: ControllerBinding): Promise<DeviceWriteResult>;
36
+ export type RemoveLapsedLeavesResult = {
37
+ removed: Array<string>;
38
+ /** Absent when no leaf had lapsed. */
39
+ result?: DeviceWriteResult;
40
+ };
41
+ export declare function removeLapsedLeaves(group: GroupHandle): Promise<RemoveLapsedLeavesResult>;
42
+ export type RevokeWithProofParams = {
43
+ subject: string;
44
+ log: Array<SignedEvent>;
45
+ } | {
46
+ reset: true;
47
+ log: Array<SignedEvent>;
48
+ };
49
+ export declare function revokeWithProof(group: GroupHandle, params: RevokeWithProofParams): Promise<RevokeBuildResult>;