@kumiai/mls 0.10.0 → 0.10.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 (49) hide show
  1. package/lib/anchor.d.ts +10 -4
  2. package/lib/anchor.js +26 -2
  3. package/lib/authentication.d.ts +11 -14
  4. package/lib/authentication.js +127 -86
  5. package/lib/capability.d.ts +37 -0
  6. package/lib/capability.js +141 -0
  7. package/lib/device-proof.d.ts +1 -0
  8. package/lib/device-proof.js +8 -12
  9. package/lib/envelope-fold.d.ts +16 -1
  10. package/lib/envelope-fold.js +49 -9
  11. package/lib/errors.d.ts +18 -0
  12. package/lib/errors.js +33 -0
  13. package/lib/group-commit.d.ts +22 -35
  14. package/lib/group-commit.js +122 -103
  15. package/lib/group-context.d.ts +6 -2
  16. package/lib/group-context.js +11 -4
  17. package/lib/group-create.js +56 -11
  18. package/lib/group-credential.d.ts +3 -1
  19. package/lib/group-credential.js +17 -3
  20. package/lib/group-device.js +34 -21
  21. package/lib/group-handle.d.ts +21 -8
  22. package/lib/group-handle.js +207 -56
  23. package/lib/group-lifecycle.d.ts +32 -0
  24. package/lib/group-lifecycle.js +300 -0
  25. package/lib/group-membership.js +7 -3
  26. package/lib/group-welcome.d.ts +11 -2
  27. package/lib/group-welcome.js +113 -21
  28. package/lib/group.d.ts +2 -1
  29. package/lib/group.js +1 -0
  30. package/lib/history.d.ts +6 -0
  31. package/lib/history.js +26 -0
  32. package/lib/index.d.ts +10 -4
  33. package/lib/index.js +8 -2
  34. package/lib/lifecycle-proof.d.ts +24 -0
  35. package/lib/lifecycle-proof.js +193 -0
  36. package/lib/lifecycle.d.ts +44 -0
  37. package/lib/lifecycle.js +385 -0
  38. package/lib/policy.d.ts +20 -0
  39. package/lib/policy.js +7 -4
  40. package/lib/recovery-verdict.d.ts +43 -0
  41. package/lib/recovery-verdict.js +135 -0
  42. package/lib/recovery.d.ts +70 -0
  43. package/lib/recovery.js +110 -36
  44. package/lib/registry.d.ts +34 -7
  45. package/lib/registry.js +113 -15
  46. package/lib/roster.d.ts +1 -1
  47. package/lib/roster.js +2 -2
  48. package/lib/types.d.ts +13 -8
  49. package/package.json +4 -4
@@ -2,18 +2,21 @@ import { normalizeDID } from '@kokuin/token';
2
2
  import { EventEmitter } from '@sozai/event';
3
3
  import { contentTypes, createApplicationMessage, decode, 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 { 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, 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,12 +71,12 @@ 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') {
72
80
  capture.rejected = {
73
81
  proposals: incoming.proposals,
74
82
  senderLeafIndex: incoming.senderLeafIndex == null ? undefined : Number(incoming.senderLeafIndex)
@@ -187,6 +195,8 @@ export function mutexFor(handle) {
187
195
  * the same wherever it appears in the log, so this store is keyed. */ #entryBodies;
188
196
  #roster;
189
197
  #registry;
198
+ #admission;
199
+ #pendingControlEvents;
190
200
  constructor(params){
191
201
  this.#state = params.state;
192
202
  this.#credential = params.credential;
@@ -215,12 +225,36 @@ export function mutexFor(handle) {
215
225
  const folded = foldLedgerControl(this.#ledger, anchor, this.groupID);
216
226
  this.#roster = folded.roster;
217
227
  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.
228
+ // Authentication reads only this handle's registry and lifetime limits.
221
229
  const denyHolder = deviceDenyHolderFor(this.#context);
222
- if (denyHolder != null) denyHolder.provider = ()=>this.currentDenySet();
230
+ if (denyHolder != null) {
231
+ denyHolder.provider = ()=>this.currentDenySet();
232
+ denyHolder.leafLifetime = anchor.controller == null ? undefined : anchor.leafLifetime ?? 86_400;
233
+ denyHolder.trustedGrantLifetime = anchor.controller == null ? undefined : anchor.trustedGrantLifetime ?? 2_592_000;
234
+ }
223
235
  EMITTERS.set(this, params.events ?? new EventEmitter());
236
+ this.#pendingControlEvents = params.speculative ? [] : undefined;
237
+ this.#admission = this.#computeAdmission();
238
+ }
239
+ #computeAdmission() {
240
+ const leaf = leafAt(this.#state.ratchetTree, this.#state.privatePath.leafIndex);
241
+ const epoch = Number(this.epoch);
242
+ return Object.freeze(leaf != null && isLapsed(this, leaf) ? {
243
+ epoch,
244
+ admissible: false,
245
+ reason: 'lapsed'
246
+ } : {
247
+ epoch,
248
+ admissible: true
249
+ });
250
+ }
251
+ sendAdmission() {
252
+ return this.#admission;
253
+ }
254
+ confirmAdopted() {
255
+ const pending = this.#pendingControlEvents;
256
+ this.#pendingControlEvents = undefined;
257
+ if (pending != null) this.emitControlEvents(pending);
224
258
  }
225
259
  get groupID() {
226
260
  return this.#credential.groupID;
@@ -301,19 +335,31 @@ export function mutexFor(handle) {
301
335
  }
302
336
  /**
303
337
  * @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
338
+ * Called after acceptance or adoption — NEVER from
305
339
  * the constructor or a fresh-join applyLedgerEntries, so a joiner is not replayed the whole
306
340
  * 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.
341
+ * `fire`: a throwing listener is swallowed and cannot break the fold. Reads the post-fold registry.
309
342
  */ emitControlEvents(enacted) {
343
+ if (this.#pendingControlEvents != null) {
344
+ this.#pendingControlEvents.push(...enacted);
345
+ return;
346
+ }
310
347
  const emitter = emitterOf(this);
311
348
  const revoked = [];
312
349
  for (const { entry } of enacted){
313
350
  if (entry.type !== DEVICE_ENTRY_TYPE || !isDeviceValue(entry.value)) continue;
314
351
  const value = entry.value;
315
352
  const subject = normalizeDID(entry.subject);
316
- if (value.op === 'revoke') {
353
+ if (this.#anchor.controller != null && (value.op === 'revoke' || value.op === 'reset')) {
354
+ for (const effect of value.revoked ?? []){
355
+ const device = normalizeDID(effect.did);
356
+ const record = revocationOf(this, device);
357
+ if (record != null) revoked.push({
358
+ device,
359
+ ...record
360
+ });
361
+ }
362
+ } else if (value.op === 'revoke') {
317
363
  const controller = controllerOf(this.#registry, subject);
318
364
  if (controller != null) revoked.push({
319
365
  device: subject,
@@ -377,6 +423,10 @@ export function mutexFor(handle) {
377
423
  const folded = foldLedgerControl(this.#ledger, this.#anchor, this.groupID);
378
424
  this.#roster = folded.roster;
379
425
  this.#registry = folded.registry;
426
+ this.#admission = this.#computeAdmission();
427
+ if (this.#pendingControlEvents != null) {
428
+ this.emitControlEvents(appended.filter(({ entry })=>entry.type === DEVICE_ENTRY_TYPE));
429
+ }
380
430
  return appended;
381
431
  });
382
432
  }
@@ -471,7 +521,8 @@ export function mutexFor(handle) {
471
521
  ledger: this.#ledger,
472
522
  entryBodies: this.#entryBodies,
473
523
  roster: this.#roster,
474
- registry: this.#registry
524
+ registry: this.#registry,
525
+ admission: this.#admission
475
526
  };
476
527
  const folded = foldLedgerControl(log, this.#anchor, this.groupID);
477
528
  this.#ledger = log;
@@ -484,6 +535,7 @@ export function mutexFor(handle) {
484
535
  ]));
485
536
  this.#roster = folded.roster;
486
537
  this.#registry = folded.registry;
538
+ this.#admission = this.#computeAdmission();
487
539
  try {
488
540
  await opts?.persist?.(this);
489
541
  } catch (error) {
@@ -492,6 +544,7 @@ export function mutexFor(handle) {
492
544
  this.#entryBodies = previous.entryBodies;
493
545
  this.#roster = previous.roster;
494
546
  this.#registry = previous.registry;
547
+ this.#admission = previous.admission;
495
548
  throw error;
496
549
  }
497
550
  // SURFACED HERE TOO, not only on the commit path. A heal is how a peer that missed commits
@@ -625,6 +678,8 @@ export function mutexFor(handle) {
625
678
  * `expectedAAD`) needs no key. Defaults to empty.
626
679
  */ async encrypt(plaintext, opts) {
627
680
  return mutexFor(this).run(async ()=>{
681
+ const own = leafAt(this.#state.ratchetTree, this.#state.privatePath.leafIndex);
682
+ if (own != null && isLapsed(this, own)) throw new LeafLapsedError('lapsed');
628
683
  const { newState, message, consumed } = await createApplicationMessage({
629
684
  context: this.#context,
630
685
  state: this.#state,
@@ -675,7 +730,15 @@ export function mutexFor(handle) {
675
730
  }
676
731
  // Read the sender BEFORE opening: the sender-data secret is epoch-level and this
677
732
  // 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);
733
+ const historical = this.#state.historicalReceiverData.get(pm.epoch);
734
+ const epochTree = historical?.ratchetTree ?? this.#state.ratchetTree;
735
+ const leafIndex = await readSenderLeafIndex(this.#context, historical?.senderDataSecret ?? this.#state.keySchedule.senderDataSecret, pm);
736
+ assertSenderNotLapsed({
737
+ group: this,
738
+ tree: epochTree,
739
+ leafIndex,
740
+ extensions: (historical?.groupContext ?? this.#state.groupContext).extensions
741
+ });
679
742
  const result = await mlsProcessMessage({
680
743
  context: this.#context,
681
744
  state: this.#state,
@@ -686,7 +749,8 @@ export function mutexFor(handle) {
686
749
  if (result.kind !== 'applicationMessage') {
687
750
  throw new Error('decrypt: frame was not an application message');
688
751
  }
689
- const senderDID = leafIndex == null ? undefined : this.#didOfLeaf(leafIndex);
752
+ const senderLeaf = leafIndex == null ? undefined : leafAt(epochTree, leafIndex);
753
+ const senderDID = senderLeaf == null ? undefined : didFromCredential(senderLeaf.credential);
690
754
  return {
691
755
  payload: result.message,
692
756
  aad: result.aad,
@@ -710,7 +774,15 @@ export function mutexFor(handle) {
710
774
  if (opts.expectedAAD != null && !bytesEqual(pm.authenticatedData, opts.expectedAAD)) {
711
775
  throw new Error('decryptStaged: frame authenticated data does not match expected AAD');
712
776
  }
713
- const leafIndex = await readSenderLeafIndex(this.#context, this.#state.keySchedule.senderDataSecret, pm);
777
+ const historical = this.#state.historicalReceiverData.get(pm.epoch);
778
+ const epochTree = historical?.ratchetTree ?? this.#state.ratchetTree;
779
+ const leafIndex = await readSenderLeafIndex(this.#context, historical?.senderDataSecret ?? this.#state.keySchedule.senderDataSecret, pm);
780
+ assertSenderNotLapsed({
781
+ group: this,
782
+ tree: epochTree,
783
+ leafIndex,
784
+ extensions: (historical?.groupContext ?? this.#state.groupContext).extensions
785
+ });
714
786
  const result = await mlsProcessMessage({
715
787
  context: this.#context,
716
788
  state: this.#state,
@@ -719,7 +791,8 @@ export function mutexFor(handle) {
719
791
  if (result.kind !== 'applicationMessage') {
720
792
  throw new Error('decryptStaged: frame was not an application message');
721
793
  }
722
- const senderDID = leafIndex == null ? undefined : this.#didOfLeaf(leafIndex);
794
+ const senderLeaf = leafIndex == null ? undefined : leafAt(epochTree, leafIndex);
795
+ const senderDID = senderLeaf == null ? undefined : didFromCredential(senderLeaf.credential);
723
796
  if (senderDID == null) throw new Error('decryptStaged: unnamed sender');
724
797
  const opened = {
725
798
  payload: result.message,
@@ -732,20 +805,7 @@ export function mutexFor(handle) {
732
805
  return opened;
733
806
  });
734
807
  }
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) {
808
+ /** Resolve ledger inputs before MLS, then run mandatory gates before caller role policy. */ async #prepareCommitPipeline(decoded, opts) {
749
809
  const callerPolicy = opts?.commitPolicy ?? this.#commitPolicy;
750
810
  const capture = {};
751
811
  const commit = readPrivateCommit(decoded);
@@ -826,9 +886,19 @@ export function mutexFor(handle) {
826
886
  ]);
827
887
  return input;
828
888
  });
829
- const foldResult = foldEnvelope(this.#roster, this.#registry, ordered, this.groupID);
889
+ const foldResult = foldEnvelope({
890
+ baseRoster: this.#roster,
891
+ baseRegistry: this.#registry,
892
+ entries: ordered,
893
+ groupID: this.groupID,
894
+ context: this.#anchor.controller == null ? undefined : {
895
+ controllerID: this.#anchor.controller,
896
+ memberController: (did)=>this.bindingOfDID(did)?.controller
897
+ }
898
+ });
830
899
  if (!foldResult.ok) {
831
900
  precomputedReject = true;
901
+ capture.proofError = foldResult.error;
832
902
  } else {
833
903
  candidateRoster = foldResult.roster;
834
904
  candidateRegistry = foldResult.registry;
@@ -840,6 +910,9 @@ export function mutexFor(handle) {
840
910
  };
841
911
  for (const { verified } of acceptedEntries){
842
912
  if (verified.entry.type !== DEVICE_ENTRY_TYPE) continue;
913
+ if (this.#anchor.controller != null && verified.entry.value.op !== 'beacon') {
914
+ continue;
915
+ }
843
916
  const ok = await verifyDeviceEntry(verified, proofCtx);
844
917
  if (!ok) {
845
918
  precomputedReject = true;
@@ -863,12 +936,38 @@ export function mutexFor(handle) {
863
936
  externalCommitDID
864
937
  }
865
938
  });
939
+ let gate;
940
+ try {
941
+ const frame = decoded;
942
+ 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;
943
+ gate = await prepareLifecycleGate({
944
+ group: this,
945
+ entries: acceptedEntries.map(({ verified })=>verified),
946
+ candidateRegistry,
947
+ context,
948
+ externalLeaf
949
+ });
950
+ } catch (error) {
951
+ precomputedReject = true;
952
+ capture.reason = rejectionReason(error);
953
+ if (error instanceof RevokeProofError) capture.proofError = error;
954
+ }
866
955
  const combined = (incoming)=>{
867
956
  // A decode/fold failure is a hard reject even under a caller policy: the
868
957
  // ledger the commit depends on is unresolvable or malformed.
869
- if (precomputedReject) return 'reject';
958
+ if (precomputedReject) {
959
+ capture.reason ??= capture.proofError == null ? 'invalid' : rejectionReason(capture.proofError);
960
+ return 'reject';
961
+ }
962
+ try {
963
+ gate?.check(incoming);
964
+ } catch (error) {
965
+ capture.reason = rejectionReason(error);
966
+ if (error instanceof RevokeProofError) capture.proofError = error;
967
+ return 'reject';
968
+ }
870
969
  if (callerPolicy != null) return callerPolicy(incoming);
871
- return defaultCommitPolicy(incoming, context);
970
+ return this.#anchor.controller == null ? defaultCommitPolicy(incoming, context) : 'accept';
872
971
  };
873
972
  const applyOnAccept = (notify = true)=>{
874
973
  // Appended, never deduped: the log records what this commit enacted, at the
@@ -886,6 +985,7 @@ export function mutexFor(handle) {
886
985
  }
887
986
  this.#roster = candidateRoster;
888
987
  this.#registry = candidateRegistry;
988
+ this.#admission = this.#computeAdmission();
889
989
  const emit = ()=>{
890
990
  this.#notifyAccepted(surfaced, acceptedEntries.filter(({ verified })=>verified.entry.type === DEVICE_ENTRY_TYPE).map(({ verified })=>verified));
891
991
  };
@@ -895,7 +995,10 @@ export function mutexFor(handle) {
895
995
  return {
896
996
  callback: wrapCommitPolicy(combined, capture),
897
997
  capture,
898
- applyOnAccept
998
+ applyOnAccept,
999
+ postApply: async (state)=>{
1000
+ await gate?.postApply(state);
1001
+ }
899
1002
  };
900
1003
  }
901
1004
  /**
@@ -971,7 +1074,8 @@ export function mutexFor(handle) {
971
1074
  leafKey: node.leaf.signaturePublicKey,
972
1075
  ...parsed.controller != null ? {
973
1076
  controller: parsed.controller.id,
974
- prefix: parsed.controller.prefix
1077
+ prefix: parsed.controller.prefix,
1078
+ capability: parsed.controller.capability
975
1079
  } : {}
976
1080
  };
977
1081
  }
@@ -1094,21 +1198,69 @@ export function mutexFor(handle) {
1094
1198
  decoded = parsed;
1095
1199
  }
1096
1200
  return mutexFor(this).run(async ()=>{
1097
- const { callback, capture, applyOnAccept } = await this.#prepareCommitPipeline(decoded, opts);
1201
+ const { callback, capture, applyOnAccept, postApply } = await this.#prepareCommitPipeline(decoded, opts);
1098
1202
  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;
1203
+ const previousAdmission = this.#admission;
1204
+ const application = readPrivateFrame(decoded, contentTypes.application);
1205
+ if (application != null) {
1206
+ const historical = this.#state.historicalReceiverData.get(application.epoch);
1207
+ const index = await readSenderLeafIndex(this.#context, historical?.senderDataSecret ?? this.#state.keySchedule.senderDataSecret, application);
1208
+ assertSenderNotLapsed({
1209
+ group: this,
1210
+ tree: historical?.ratchetTree ?? this.#state.ratchetTree,
1211
+ leafIndex: index,
1212
+ extensions: (historical?.groupContext ?? this.#state.groupContext).extensions
1213
+ });
1214
+ }
1215
+ let result;
1216
+ try {
1217
+ result = await mlsProcessMessage({
1218
+ context: {
1219
+ ...this.#context,
1220
+ authService: {
1221
+ validateCredential: async (credential, key)=>{
1222
+ try {
1223
+ await verifyLeafCredential(credential, key, {
1224
+ deviceDenySet: ()=>this.currentDenySet(),
1225
+ leafLifetime: ()=>this.#anchor.controller == null ? undefined : this.#anchor.leafLifetime ?? 86_400,
1226
+ trustedGrantLifetime: ()=>this.#anchor.controller == null ? undefined : this.#anchor.trustedGrantLifetime ?? 2_592_000
1227
+ });
1228
+ return true;
1229
+ } catch (error) {
1230
+ capture.reason = rejectionReason(error);
1231
+ return false;
1232
+ }
1233
+ }
1234
+ }
1235
+ },
1236
+ state: this.#state,
1237
+ message: decoded,
1238
+ ...callback != null && {
1239
+ callback
1240
+ }
1241
+ });
1242
+ } catch (error) {
1243
+ if (application != null) throw error;
1244
+ const rejection = new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex, capture.reason ?? 'invalid');
1245
+ rejection.cause = error;
1246
+ if (error instanceof Error) rejection.message += `: ${error.message}`;
1247
+ throw rejection;
1248
+ }
1108
1249
  if (result.kind === 'newState' && result.actionTaken === 'reject') {
1109
- zeroAll(result.consumed);
1110
- throw new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex);
1250
+ const rejection = new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex, capture.reason ?? 'policy');
1251
+ if (capture.proofError != null) rejection.cause = capture.proofError;
1252
+ throw rejection;
1253
+ }
1254
+ if (result.kind === 'newState') {
1255
+ try {
1256
+ await postApply(result.newState);
1257
+ } catch (error) {
1258
+ const rejection = new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex, rejectionReason(error));
1259
+ rejection.cause = error;
1260
+ throw rejection;
1261
+ }
1111
1262
  }
1263
+ this.#state = result.newState;
1112
1264
  if (result.kind === 'applicationMessage') {
1113
1265
  zeroAll(result.consumed);
1114
1266
  return result.message;
@@ -1133,6 +1285,7 @@ export function mutexFor(handle) {
1133
1285
  this.#entryBodies = previousEntryBodies;
1134
1286
  this.#roster = previousRoster;
1135
1287
  this.#registry = previousRegistry;
1288
+ this.#admission = previousAdmission;
1136
1289
  throw error;
1137
1290
  }
1138
1291
  zeroAll(result.consumed);
@@ -1145,10 +1298,7 @@ export function mutexFor(handle) {
1145
1298
  });
1146
1299
  }
1147
1300
  }
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) {
1301
+ /** Build policy inputs shared by author and receiver gates. Entry ids drive the expected head. */ export function buildCommitPolicyContext(handle, args) {
1152
1302
  const leafToDID = new Map();
1153
1303
  for (const member of handle.listMembers())leafToDID.set(member.leafIndex, member.id);
1154
1304
  const headExt = readLedgerHeadExtension(handle);
@@ -1181,11 +1331,12 @@ export function mutexFor(handle) {
1181
1331
  return new GroupHandle({
1182
1332
  state,
1183
1333
  credential: group.credential,
1184
- context: group.context,
1334
+ context: createMlsContext(group.context.cipherSuite, group.anchor),
1185
1335
  ledger: group.ledger,
1186
1336
  commitPolicy: group.commitPolicy,
1187
1337
  resolveLedgerEntries: group.resolveLedgerEntries,
1188
1338
  onLedgerEntries: group.onLedgerEntries,
1189
- events: emitterOf(group)
1339
+ events: emitterOf(group),
1340
+ speculative: true
1190
1341
  });
1191
1342
  }
@@ -0,0 +1,32 @@
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 RevokeBuildResult = {
7
+ status: 'built';
8
+ result: DeviceWriteResult;
9
+ } | {
10
+ status: 'already-revoked';
11
+ } | {
12
+ status: 'self-affected';
13
+ subject: string;
14
+ } | {
15
+ status: 'not-provable';
16
+ reason: RevokeProofReason;
17
+ };
18
+ export declare function renewLeaf(group: GroupHandle, binding: ControllerBinding): Promise<DeviceWriteResult>;
19
+ export type RemoveLapsedLeavesResult = {
20
+ removed: Array<string>;
21
+ /** Absent when no leaf had lapsed. */
22
+ result?: DeviceWriteResult;
23
+ };
24
+ export declare function removeLapsedLeaves(group: GroupHandle): Promise<RemoveLapsedLeavesResult>;
25
+ export type RevokeWithProofParams = {
26
+ subject: string;
27
+ log: Array<SignedEvent>;
28
+ } | {
29
+ reset: true;
30
+ log: Array<SignedEvent>;
31
+ };
32
+ export declare function revokeWithProof(group: GroupHandle, params: RevokeWithProofParams): Promise<RevokeBuildResult>;