@kumiai/mls 0.10.9 → 0.12.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 (48) hide show
  1. package/README.md +29 -1
  2. package/lib/authentication.d.ts +8 -4
  3. package/lib/authentication.js +210 -54
  4. package/lib/capability.d.ts +4 -0
  5. package/lib/capability.js +22 -10
  6. package/lib/controller-ingest.d.ts +19 -0
  7. package/lib/controller-ingest.js +117 -0
  8. package/lib/controller-log.d.ts +10 -0
  9. package/lib/controller-log.js +71 -0
  10. package/lib/credential.d.ts +8 -5
  11. package/lib/credential.js +32 -3
  12. package/lib/device-proof.d.ts +5 -0
  13. package/lib/embedded-resolver.d.ts +8 -15
  14. package/lib/embedded-resolver.js +53 -16
  15. package/lib/errors.d.ts +8 -2
  16. package/lib/errors.js +11 -0
  17. package/lib/group-commit.d.ts +11 -2
  18. package/lib/group-commit.js +154 -46
  19. package/lib/group-context.d.ts +4 -2
  20. package/lib/group-context.js +30 -6
  21. package/lib/group-create.js +44 -16
  22. package/lib/group-credential.js +22 -1
  23. package/lib/group-device.js +5 -15
  24. package/lib/group-handle.d.ts +12 -1
  25. package/lib/group-handle.js +102 -16
  26. package/lib/group-lifecycle.d.ts +31 -5
  27. package/lib/group-lifecycle.js +253 -154
  28. package/lib/group-membership.js +1 -1
  29. package/lib/group-welcome.d.ts +4 -0
  30. package/lib/group-welcome.js +14 -2
  31. package/lib/history.d.ts +6 -0
  32. package/lib/history.js +20 -1
  33. package/lib/index.d.ts +12 -7
  34. package/lib/index.js +11 -6
  35. package/lib/lifecycle-proof.d.ts +15 -6
  36. package/lib/lifecycle-proof.js +196 -132
  37. package/lib/lifecycle.d.ts +9 -6
  38. package/lib/lifecycle.js +196 -86
  39. package/lib/member-root.d.ts +88 -0
  40. package/lib/member-root.js +469 -0
  41. package/lib/recovery-verdict.d.ts +1 -1
  42. package/lib/recovery-verdict.js +32 -15
  43. package/lib/registry.d.ts +17 -6
  44. package/lib/registry.js +205 -21
  45. package/lib/stale-leaf.d.ts +2 -0
  46. package/lib/stale-leaf.js +9 -4
  47. package/lib/types.d.ts +3 -0
  48. package/package.json +4 -4
@@ -1,15 +1,17 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
- import { createCommit, defaultCredentialTypes, defaultProposalTypes, encode, isDefaultCredential, mlsMessageEncoder } from 'ts-mls';
2
+ import { createCommit, defaultCredentialTypes, defaultProposalTypes, encode, isDefaultCredential, isDefaultProposal, mlsMessageEncoder, nodeTypes } from 'ts-mls';
3
3
  import { LEDGER_HEAD_EXTENSION_TYPE } from './anchor.js';
4
4
  import { parseMLSCredentialIdentity } from './credential.js';
5
5
  import { verifyDeviceEntry } from './device-proof.js';
6
6
  import { encodeControlEnvelope } from './envelope.js';
7
7
  import { foldEnvelope } from './envelope-fold.js';
8
+ import { withJudging } from './group-context.js';
8
9
  import { assertBindingAuthorTime } from './group-credential.js';
9
10
  import { buildCommitPolicyContext, CommitRejectedError, deriveGroup, mutexFor } from './group-handle.js';
11
+ import { controllerLogDelta, preservationClock } from './group-lifecycle.js';
10
12
  import { buildLedgerHeadExtension, extendHead, readLedgerHead } from './head.js';
11
13
  import { ledgerEntryDigest, signLedgerEntry, verifyLedgerEntry } from './ledger.js';
12
- import { prepareLifecycleGate, rejectionReason, validateEntry } from './lifecycle.js';
14
+ import { isUnchangedLeaf, prepareLifecycleGate, rejectionReason, validateEntry } from './lifecycle.js';
13
15
  import { authority, controllerOf, DEVICE_ENTRY_TYPE } from './registry.js';
14
16
  import { ROLE_ENTRY_TYPE } from './roster.js';
15
17
  import { staleLeafIndex } from './stale-leaf.js';
@@ -34,6 +36,8 @@ import { staleLeafIndex } from './stale-leaf.js';
34
36
  return this.#actualDID;
35
37
  }
36
38
  }
39
+ // Completed builds refresh the handle, but retries must never enact a previous build's clock.
40
+ const INVITE_ENTRIES = new WeakMap();
37
41
  /** Create an invite without adding its recipient; commitInvite enacts the admission. */ export async function createInvite(params) {
38
42
  const { group, identity, recipientDID } = params;
39
43
  let appended;
@@ -42,11 +46,25 @@ import { staleLeafIndex } from './stale-leaf.js';
42
46
  if (group.findMemberLeafIndex(identity.id) == null) {
43
47
  throw new Error('createInvite: the inviter must hold a leaf');
44
48
  }
45
- appended = params.entries ?? [];
49
+ appended = [
50
+ ...params.entries ?? []
51
+ ];
46
52
  for (const token of appended){
47
53
  const verified = await verifyLedgerEntry(token);
48
54
  if (verified == null || verified.entry.groupID !== group.groupID || verified.entry.type.startsWith('kumiai.') || normalizeDID(verified.issuer) !== normalizeDID(identity.id)) throw new Error('createInvite: entries must be consumer entries signed by the inviter');
49
55
  }
56
+ if (params.controllerLog != null) {
57
+ const delta = controllerLogDelta(group, params.controllerLog);
58
+ if (delta != null) appended.unshift(await signLedgerEntry(identity, {
59
+ type: DEVICE_ENTRY_TYPE,
60
+ groupID: group.groupID,
61
+ subject: group.anchor.controller,
62
+ value: {
63
+ op: 'log',
64
+ proof: delta
65
+ }
66
+ }));
67
+ }
50
68
  } else {
51
69
  if (params.permission == null) throw new Error('createInvite: standard invites require permission');
52
70
  if (group.roster.roles.get(authority(group.registry, identity.id)) !== 'admin') {
@@ -61,16 +79,20 @@ import { staleLeafIndex } from './stale-leaf.js';
61
79
  })
62
80
  ];
63
81
  }
82
+ const invite = {
83
+ groupID: group.groupID,
84
+ inviterID: identity.id,
85
+ recipientDID,
86
+ ledgerEntries: [
87
+ ...group.ledgerTokens,
88
+ ...appended
89
+ ]
90
+ };
91
+ INVITE_ENTRIES.set(invite, [
92
+ ...invite.ledgerEntries
93
+ ]);
64
94
  return {
65
- invite: {
66
- groupID: group.groupID,
67
- inviterID: identity.id,
68
- recipientDID,
69
- ledgerEntries: [
70
- ...group.ledgerTokens,
71
- ...appended
72
- ]
73
- }
95
+ invite
74
96
  };
75
97
  }
76
98
  /**
@@ -87,6 +109,30 @@ import { staleLeafIndex } from './stale-leaf.js';
87
109
  const next = buildLedgerHeadExtension(extendHead(current.head, entryIDs));
88
110
  return group.state.groupContext.extensions.map((ext)=>ext.extensionType === LEDGER_HEAD_EXTENSION_TYPE ? next : ext);
89
111
  }
112
+ export function proposedTree(state, proposals) {
113
+ const tree = state.ratchetTree.slice();
114
+ for (const { proposal, senderLeafIndex } of proposals){
115
+ if (!isDefaultProposal(proposal)) continue;
116
+ switch(proposal.proposalType){
117
+ case defaultProposalTypes.add:
118
+ tree.push({
119
+ nodeType: nodeTypes.leaf,
120
+ leaf: proposal.add.keyPackage.leafNode
121
+ });
122
+ break;
123
+ case defaultProposalTypes.update:
124
+ if (senderLeafIndex != null) tree[senderLeafIndex * 2] = {
125
+ nodeType: nodeTypes.leaf,
126
+ leaf: proposal.update.leafNode
127
+ };
128
+ break;
129
+ case defaultProposalTypes.remove:
130
+ tree[proposal.remove.removed * 2] = undefined;
131
+ break;
132
+ }
133
+ }
134
+ return tree;
135
+ }
90
136
  /**
91
137
  * The one place a commit carrying control-ledger entries is built: `commitInvite`,
92
138
  * `removeMember`, and `commitLedgerEntries` all route through it, so envelope and
@@ -106,7 +152,10 @@ import { staleLeafIndex } from './stale-leaf.js';
106
152
  * proposal advancing the head by exactly those ids, in envelope order. An empty list
107
153
  * moves no head and carries no envelope.
108
154
  */ export async function commitWithEntries(params) {
109
- const { group, extraProposals, enacted } = params;
155
+ const { group, extraProposals } = params;
156
+ const enacted = [
157
+ ...params.enacted
158
+ ];
110
159
  if (group.anchor.controller != null && group.findMemberLeafIndex(group.credential.id) == null) {
111
160
  throw new Error('the committer must hold a leaf');
112
161
  }
@@ -136,20 +185,41 @@ import { staleLeafIndex } from './stale-leaf.js';
136
185
  entryID: ledgerEntryDigest(token)
137
186
  });
138
187
  }
139
- const fold = foldEnvelope({
140
- baseRoster: group.roster,
141
- baseRegistry: group.registry,
142
- entries: inputs,
143
- groupID: group.groupID,
144
- context: group.anchor.controller == null ? undefined : {
145
- controllerID: group.anchor.controller,
146
- memberController: (did)=>group.bindingOfDID(did)?.controller
147
- }
148
- });
188
+ const foldEntries = ()=>foldEnvelope({
189
+ baseRoster: group.roster,
190
+ baseRegistry: group.registry,
191
+ entries: inputs,
192
+ groupID: group.groupID,
193
+ context: group.anchor.controller == null ? undefined : {
194
+ controllerID: group.anchor.controller,
195
+ memberController: (did)=>group.bindingOfDID(did)?.controller
196
+ }
197
+ });
198
+ let fold = foldEntries();
149
199
  if (!fold.ok) {
150
200
  if (fold.error != null) throw fold.error;
151
201
  throw new Error(`cannot enact ledger entry ${fold.entryID}: ${fold.reason}`);
152
202
  }
203
+ const sourceState = params.commitState ?? group.state;
204
+ const tree = proposedTree(sourceState, [
205
+ ...Object.values(params.pendingProposals ?? {}),
206
+ ...extraProposals.map((proposal)=>({
207
+ proposal,
208
+ senderLeafIndex: sourceState.privatePath.leafIndex
209
+ }))
210
+ ]);
211
+ const clocks = await preservationClock(group, tree, fold.registry);
212
+ for (const clock of clocks){
213
+ const verified = await verifyLedgerEntry(clock);
214
+ if (verified == null) throw new Error('Invalid preservation clock');
215
+ enacted.push(clock);
216
+ inputs.push({
217
+ verified,
218
+ entryID: ledgerEntryDigest(clock)
219
+ });
220
+ fold = foldEntries();
221
+ if (!fold.ok) throw fold.error ?? new Error(fold.reason);
222
+ }
153
223
  // Same reason as the fold guard above: verify device entries against THIS group's tree and
154
224
  // registry so the committer never authors a commit every receiver's own gate will reject.
155
225
  const proofCtx = {
@@ -223,25 +293,53 @@ import { staleLeafIndex } from './stale-leaf.js';
223
293
  if (isDefaultCredential(leaf.credential) && leaf.credential.credentialType === defaultCredentialTypes.basic) {
224
294
  assertBindingAuthorTime(parseMLSCredentialIdentity(leaf.credential.identity).controller);
225
295
  }
226
- await validateEntry(group, leaf);
296
+ await validateEntry(group, leaf, undefined, {
297
+ registry: fold.registry,
298
+ stage: 'full',
299
+ mode: 'admit'
300
+ });
227
301
  }
228
302
  }
229
- const result = await createCommit({
230
- context: group.context,
231
- state: commitState,
232
- extraProposals: proposals,
233
- ...ratchetTreeExtension && {
234
- ratchetTreeExtension: true
235
- },
236
- ...entryIDs.length > 0 && {
237
- authenticatedData: encodeControlEnvelope({
238
- v: 1,
239
- entries: entryIDs
240
- })
241
- }
242
- });
303
+ const candidateRegistry = fold.registry;
304
+ const result = await withJudging(group.context, {
305
+ registry: group.anchor.controller == null ? undefined : candidateRegistry,
306
+ stage: 'full',
307
+ mode: 'admit'
308
+ }, (context)=>createCommit({
309
+ context: {
310
+ ...context,
311
+ authService: {
312
+ validateCredential: async (credential, key)=>{
313
+ const update = incoming.proposals.find(({ proposal })=>isDefaultProposal(proposal) && proposal.proposalType === defaultProposalTypes.update && proposal.update.leafNode.credential === credential);
314
+ const index = update?.senderLeafIndex;
315
+ return withJudging(group.context, {
316
+ registry: group.anchor.controller == null ? undefined : candidateRegistry,
317
+ stage: 'full',
318
+ mode: index != null && isUnchangedLeaf(group.state.ratchetTree, index, {
319
+ credential,
320
+ signaturePublicKey: key
321
+ }) ? 'retain' : 'admit'
322
+ }, (judgedContext)=>judgedContext.authService.validateCredential(credential, key));
323
+ }
324
+ }
325
+ },
326
+ state: commitState,
327
+ extraProposals: proposals,
328
+ ...ratchetTreeExtension && {
329
+ ratchetTreeExtension: true
330
+ },
331
+ ...entryIDs.length > 0 && {
332
+ authenticatedData: encodeControlEnvelope({
333
+ v: 1,
334
+ entries: entryIDs
335
+ })
336
+ }
337
+ }));
243
338
  await gate.postApply(result.newState);
244
- return result;
339
+ return {
340
+ ...result,
341
+ enacted
342
+ };
245
343
  }
246
344
  /**
247
345
  * The entries an invite adds beyond the committer's own log: everything past the
@@ -254,11 +352,15 @@ import { staleLeafIndex } from './stale-leaf.js';
254
352
  * history would mis-slice and move the head by ids that do not follow the group's own,
255
353
  * corrupting the chain for every receiver.
256
354
  */ function entriesAddedByInvite(group, invite) {
355
+ const entries = INVITE_ENTRIES.get(invite) ?? [
356
+ ...invite.ledgerEntries
357
+ ];
358
+ INVITE_ENTRIES.set(invite, entries);
257
359
  const held = group.ledgerTokens;
258
- if (invite.ledgerEntries.length < held.length || held.some((token, index)=>invite.ledgerEntries[index] !== token)) {
360
+ if (entries.length < held.length || held.some((token, index)=>entries[index] !== token)) {
259
361
  throw new Error("commitInvite: the invite's ledger does not extend this group's own");
260
362
  }
261
- return invite.ledgerEntries.slice(held.length);
363
+ return entries.slice(held.length);
262
364
  }
263
365
  /**
264
366
  * The admin write path for the control ledger: a commit carrying no membership
@@ -289,7 +391,7 @@ import { staleLeafIndex } from './stale-leaf.js';
289
391
  enacted: tokens
290
392
  });
291
393
  const newGroup = deriveGroup(group, result.newState);
292
- await newGroup.applyLedgerEntries(tokens);
394
+ await newGroup.applyLedgerEntries(result.enacted);
293
395
  return {
294
396
  commitMessage: encode(mlsMessageEncoder, result.commit),
295
397
  newGroup,
@@ -310,6 +412,8 @@ import { staleLeafIndex } from './stale-leaf.js';
310
412
  * The invite carries the group's whole history (a joiner has nothing to fold it onto),
311
413
  * but only the entries beyond that history ride the commit — see
312
414
  * {@link entriesAddedByInvite} and {@link commitWithEntries}.
415
+ * On success, updates the input invite with the complete ledger for delivery with the Welcome.
416
+ * Failed attempts leave it unchanged. Retries always build from its original ledger entries.
313
417
  *
314
418
  * Reads `group` and returns a NEW derived handle (`newGroup`); it never advances
315
419
  * `group`. The caller MUST adopt `newGroup` — never reuse `group` — before the next
@@ -390,11 +494,15 @@ import { staleLeafIndex } from './stale-leaf.js';
390
494
  if (result.welcome == null) {
391
495
  throw new Error('commitInvite: expected a Welcome message for the add proposal');
392
496
  }
393
- // The entries this commit enacts are now part of the group's ledger.
394
- await newGroup.applyLedgerEntries(enacted);
497
+ // Preservation may append a clock after the invite was prepared.
498
+ await newGroup.applyLedgerEntries(result.enacted);
499
+ const commitMessage = encode(mlsMessageEncoder, result.commit);
500
+ const welcomeMessage = encode(mlsMessageEncoder, result.welcome);
501
+ invite.ledgerEntries = newGroup.ledgerTokens;
395
502
  return {
396
- commitMessage: encode(mlsMessageEncoder, result.commit),
397
- welcomeMessage: encode(mlsMessageEncoder, result.welcome),
503
+ invite,
504
+ commitMessage,
505
+ welcomeMessage,
398
506
  newGroup,
399
507
  epoch: newGroup.epoch
400
508
  };
@@ -1,16 +1,18 @@
1
1
  import { type Capabilities, type GroupContextExtension, type MlsContext } from 'ts-mls';
2
2
  import type { GroupAnchor } from './anchor.js';
3
- import type { DeviceRegistry } from './registry.js';
3
+ import { type JudgingContext } from './authentication.js';
4
4
  import type { GroupOptions } from './types.js';
5
5
  /** Late-bound provider of a context's device deny set, pointed at the live handle after construction. */
6
6
  export type DeviceDenyHolder = {
7
7
  provider: () => ReadonlySet<string>;
8
- registry?: () => DeviceRegistry | undefined;
8
+ judging?: () => JudgingContext;
9
9
  leafLifetime?: number;
10
10
  trustedGrantLifetime?: number;
11
11
  };
12
12
  /** The deny holder for an internally built context, or undefined for others. */
13
13
  export declare function deviceDenyHolderFor(context: MlsContext): DeviceDenyHolder | undefined;
14
+ /** Run with an isolated authentication service without changing the source context. */
15
+ export declare function withJudging<T>(context: MlsContext, judging: JudgingContext, fn: (context: MlsContext) => Promise<T>): Promise<T>;
14
16
  export declare function resolveMlsContext(options?: GroupOptions, anchor?: GroupAnchor): Promise<MlsContext>;
15
17
  export declare function createMlsContext(cipherSuite: MlsContext['cipherSuite'], anchor?: GroupAnchor): MlsContext;
16
18
  /**
@@ -1,12 +1,41 @@
1
1
  import { defaultCapabilities, getCiphersuiteImpl } from 'ts-mls';
2
2
  import { createDIDAuthenticationService } from './authentication.js';
3
3
  import { nobleCryptoProvider } from './crypto.js';
4
+ import { denySetOf } from './registry.js';
4
5
  const DEFAULT_CIPHERSUITE = 'MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519';
5
6
  const EMPTY_DENY = new Set();
6
7
  const DENY_HOLDERS = new WeakMap();
7
8
  /** The deny holder for an internally built context, or undefined for others. */ export function deviceDenyHolderFor(context) {
8
9
  return DENY_HOLDERS.get(context);
9
10
  }
11
+ /** Run with an isolated authentication service without changing the source context. */ export async function withJudging(context, judging, fn) {
12
+ const holder = deviceDenyHolderFor(context);
13
+ if (holder == null) throw new Error('Missing judging holder');
14
+ const registry = judging.registry;
15
+ const scopedHolder = {
16
+ ...holder,
17
+ provider: registry == null ? holder.provider : ()=>denySetOf(registry),
18
+ judging: ()=>judging
19
+ };
20
+ const scopedContext = {
21
+ ...context,
22
+ authService: authenticationFor(scopedHolder)
23
+ };
24
+ DENY_HOLDERS.set(scopedContext, scopedHolder);
25
+ return fn(scopedContext);
26
+ }
27
+ function authenticationFor(holder) {
28
+ return createDIDAuthenticationService({
29
+ deviceDenySet: ()=>holder.provider(),
30
+ judging: ()=>holder.judging?.() ?? {
31
+ stage: 'full',
32
+ mode: 'admit'
33
+ },
34
+ mayKeepDeniedIssuer: ()=>holder.judging?.().mode === 'retain',
35
+ leafLifetime: ()=>holder.leafLifetime,
36
+ trustedGrantLifetime: ()=>holder.trustedGrantLifetime
37
+ });
38
+ }
10
39
  export async function resolveMlsContext(options, anchor) {
11
40
  const name = options?.ciphersuiteName ?? DEFAULT_CIPHERSUITE;
12
41
  const cipherSuite = await getCiphersuiteImpl(name, options?.cryptoProvider ?? nobleCryptoProvider);
@@ -20,12 +49,7 @@ export function createMlsContext(cipherSuite, anchor) {
20
49
  leafLifetime: anchor?.controller == null ? undefined : anchor.leafLifetime ?? 86_400,
21
50
  trustedGrantLifetime: anchor?.controller == null ? undefined : anchor.trustedGrantLifetime ?? 2_592_000
22
51
  };
23
- const authService = createDIDAuthenticationService({
24
- deviceDenySet: ()=>holder.provider(),
25
- deviceRegistry: ()=>holder.registry?.(),
26
- leafLifetime: ()=>holder.leafLifetime,
27
- trustedGrantLifetime: ()=>holder.trustedGrantLifetime
28
- });
52
+ const authService = authenticationFor(holder);
29
53
  const context = {
30
54
  cipherSuite,
31
55
  authService
@@ -1,12 +1,15 @@
1
+ import { pruneLog } from '@kokuin/controller';
1
2
  import { normalizeDID } from '@kokuin/token';
2
3
  import { generateKeyPackageWithKey, createGroup as mlsCreateGroup } from 'ts-mls';
3
4
  import { buildCurrentGroupAnchorExtension, buildGroupAnchorExtension, decodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, LEDGER_HEAD_EXTENSION_TYPE } from './anchor.js';
4
5
  import { verifyLeafCredential } from './authentication.js';
5
6
  import { LeafBindingError } from './errors.js';
6
- import { buildLeafCapabilities, resolveMlsContext } from './group-context.js';
7
+ import { buildLeafCapabilities, resolveMlsContext, withJudging } from './group-context.js';
7
8
  import { assertBindingAuthorTime, makeMLSCredential } from './group-credential.js';
8
9
  import { GroupHandle } from './group-handle.js';
9
- import { buildLedgerHeadExtension, genesisHead } from './head.js';
10
+ import { buildLedgerHeadExtension, extendHead, genesisHead } from './head.js';
11
+ import { ledgerEntryDigest, signLedgerEntry } from './ledger.js';
12
+ import { DEVICE_ENTRY_TYPE, registryForLog } from './registry.js';
10
13
  /** Create a new MLS group. The identity becomes the sole member and admin. */ export async function createGroup(identity, groupID, options) {
11
14
  assertBindingAuthorTime(options?.controller);
12
15
  // A binding enriches a supplied anchor before genesis; standard anchor bytes stay untouched.
@@ -62,35 +65,59 @@ import { buildLedgerHeadExtension, genesisHead } from './head.js';
62
65
  } else if (options?.controller != null) {
63
66
  throw new LeafBindingError('controller-mismatch');
64
67
  }
68
+ if (anchor.controller != null && options?.controllerLog == null) throw new LeafBindingError('member-unavailable');
69
+ const registry = anchor.controller == null || options?.controllerLog == null ? undefined : registryForLog(anchor.controller, options.controllerLog);
70
+ const tokens = [];
71
+ if (anchor.controller != null && options?.controllerLog != null) {
72
+ tokens.push(await signLedgerEntry(identity, {
73
+ type: DEVICE_ENTRY_TYPE,
74
+ groupID,
75
+ subject: anchor.controller,
76
+ value: {
77
+ op: 'seed',
78
+ proof: pruneLog(anchor.controller, options.controllerLog)
79
+ }
80
+ }));
81
+ }
65
82
  const context = await resolveMlsContext(options, anchor);
66
83
  const mlsCredential = makeMLSCredential(identity, options?.controller);
67
84
  if (options?.controller != null) {
68
85
  await verifyLeafCredential(mlsCredential, identity.publicKey, {
86
+ judging: ()=>({
87
+ registry,
88
+ stage: 'full',
89
+ mode: 'admit'
90
+ }),
69
91
  leafLifetime: ()=>anchor.leafLifetime ?? 86_400,
70
92
  trustedGrantLifetime: ()=>anchor.trustedGrantLifetime ?? 2_592_000
71
93
  });
72
94
  }
73
- if (!extensions.some((ext)=>ext.extensionType === LEDGER_HEAD_EXTENSION_TYPE)) {
74
- extensions.push(buildLedgerHeadExtension(genesisHead(groupID)));
75
- }
76
- const statePromise = generateKeyPackageWithKey({
77
- credential: mlsCredential,
78
- signatureKeyPair: {
79
- signKey: identity.privateKey,
80
- publicKey: identity.publicKey
81
- },
82
- cipherSuite: context.cipherSuite,
83
- capabilities: buildLeafCapabilities(extensions, options?.capabilities)
84
- }).then((keyPackage)=>{
95
+ const head = buildLedgerHeadExtension(extendHead(genesisHead(groupID), tokens.map(ledgerEntryDigest)));
96
+ const headIndex = extensions.findIndex((ext)=>ext.extensionType === LEDGER_HEAD_EXTENSION_TYPE);
97
+ if (tokens.length > 0 && headIndex >= 0) extensions[headIndex] = head;
98
+ else if (headIndex < 0) extensions.push(head);
99
+ const state = await withJudging(context, {
100
+ registry,
101
+ stage: 'full',
102
+ mode: 'admit'
103
+ }, async (judgedContext)=>{
104
+ const keyPackage = await generateKeyPackageWithKey({
105
+ credential: mlsCredential,
106
+ signatureKeyPair: {
107
+ signKey: identity.privateKey,
108
+ publicKey: identity.publicKey
109
+ },
110
+ cipherSuite: judgedContext.cipherSuite,
111
+ capabilities: buildLeafCapabilities(extensions, options?.capabilities)
112
+ });
85
113
  return mlsCreateGroup({
86
- context,
114
+ context: judgedContext,
87
115
  groupId: new TextEncoder().encode(groupID),
88
116
  keyPackage: keyPackage.publicPackage,
89
117
  privateKeyPackage: keyPackage.privatePackage,
90
118
  extensions
91
119
  });
92
120
  });
93
- const state = await statePromise;
94
121
  const credential = {
95
122
  id: identity.id,
96
123
  groupID
@@ -103,6 +130,7 @@ import { buildLedgerHeadExtension, genesisHead } from './head.js';
103
130
  resolveLedgerEntries: options?.resolveLedgerEntries,
104
131
  onLedgerEntries: options?.onLedgerEntries
105
132
  });
133
+ await group.applyLedgerEntries(tokens);
106
134
  return {
107
135
  group,
108
136
  credential
@@ -3,7 +3,10 @@ import { defaultCredentialTypes, generateKeyPackageWithKey, greaseExtensions, ma
3
3
  import { controlCapabilities } from './anchor.js';
4
4
  import { verifyLeafCredential } from './authentication.js';
5
5
  import { readCapability } from './capability.js';
6
+ import { LeafBindingError } from './errors.js';
6
7
  import { resolveMlsContext } from './group-context.js';
8
+ import { memberRootsOf } from './member-root.js';
9
+ import { registryForLog } from './registry.js';
7
10
  export function makeMLSCredential(identity, controller) {
8
11
  const id = identity.id;
9
12
  const isPeer = isPeer4(id);
@@ -25,6 +28,13 @@ export function makeMLSCredential(identity, controller) {
25
28
  }
26
29
  export function assertBindingAuthorTime(controller) {
27
30
  if (controller == null) return;
31
+ if (controller.member != null) {
32
+ if (controller.iat == null || !Number.isFinite(controller.iat) || controller.iat > now()) {
33
+ throw new Error('Membership binding is not valid at authoring time');
34
+ }
35
+ return;
36
+ }
37
+ if (controller.capability == null) throw new LeafBindingError('controller-mismatch');
28
38
  const { iat, exp } = readCapability(controller.capability).payload;
29
39
  const timestamp = now();
30
40
  if (exp <= timestamp || iat > timestamp) {
@@ -42,7 +52,18 @@ export function assertBindingAuthorTime(controller) {
42
52
  */ async function buildBundle(identity, options, overrides = {}) {
43
53
  assertBindingAuthorTime(options?.controller);
44
54
  const credential = makeMLSCredential(identity, options?.controller);
45
- if (options?.controller != null) await verifyLeafCredential(credential, identity.publicKey);
55
+ if (options?.controller != null) {
56
+ const memberRooted = memberRootsOf(options.controller, identity.id).some(({ root })=>root.kind === 'member');
57
+ if (memberRooted && options.controllerLog == null) throw new LeafBindingError('member-unavailable');
58
+ const registry = memberRooted && options.controllerLog != null ? registryForLog(options.controller.id, options.controllerLog) : undefined;
59
+ await verifyLeafCredential(credential, identity.publicKey, {
60
+ judging: ()=>({
61
+ registry,
62
+ stage: 'full',
63
+ mode: 'admit'
64
+ })
65
+ });
66
+ }
46
67
  const { cipherSuite } = await resolveMlsContext(options);
47
68
  const result = await generateKeyPackageWithKey({
48
69
  credential,
@@ -33,9 +33,7 @@ import { DEVICE_ENTRY_TYPE } from './registry.js';
33
33
  requireAdmin: false
34
34
  });
35
35
  const newGroup = deriveGroup(group, result.newState);
36
- await newGroup.applyLedgerEntries([
37
- token
38
- ]);
36
+ await newGroup.applyLedgerEntries(result.enacted);
39
37
  return {
40
38
  commitMessage: encode(mlsMessageEncoder, result.commit),
41
39
  newGroup,
@@ -67,9 +65,7 @@ import { DEVICE_ENTRY_TYPE } from './registry.js';
67
65
  requireAdmin: false
68
66
  });
69
67
  const newGroup = deriveGroup(group, result.newState);
70
- await newGroup.applyLedgerEntries([
71
- token
72
- ]);
68
+ await newGroup.applyLedgerEntries(result.enacted);
73
69
  return {
74
70
  commitMessage: encode(mlsMessageEncoder, result.commit),
75
71
  newGroup,
@@ -124,9 +120,7 @@ import { DEVICE_ENTRY_TYPE } from './registry.js';
124
120
  throw new Error('addDevice: expected a Welcome message for the add proposal');
125
121
  }
126
122
  const newGroup = deriveGroup(group, result.newState);
127
- await newGroup.applyLedgerEntries([
128
- token
129
- ]);
123
+ await newGroup.applyLedgerEntries(result.enacted);
130
124
  return {
131
125
  commitMessage: encode(mlsMessageEncoder, result.commit),
132
126
  welcomeMessage: encode(mlsMessageEncoder, result.welcome),
@@ -171,9 +165,7 @@ import { DEVICE_ENTRY_TYPE } from './registry.js';
171
165
  requireAdmin: false
172
166
  });
173
167
  const newGroup = deriveGroup(group, result.newState);
174
- await newGroup.applyLedgerEntries([
175
- token
176
- ]);
168
+ await newGroup.applyLedgerEntries(result.enacted);
177
169
  return {
178
170
  commitMessage: encode(mlsMessageEncoder, result.commit),
179
171
  newGroup,
@@ -207,9 +199,7 @@ import { DEVICE_ENTRY_TYPE } from './registry.js';
207
199
  requireAdmin: false
208
200
  });
209
201
  const newGroup = deriveGroup(group, result.newState);
210
- await newGroup.applyLedgerEntries([
211
- token
212
- ]);
202
+ await newGroup.applyLedgerEntries(result.enacted);
213
203
  return {
214
204
  commitMessage: encode(mlsMessageEncoder, result.commit),
215
205
  newGroup,
@@ -6,18 +6,28 @@ import { type GroupMember, type MemberCredential } from './credential.js';
6
6
  import { type LeafBinding } from './device-proof.js';
7
7
  import { type VerifiedLedgerEntry } from './ledger.js';
8
8
  import { type CommitRejectionReason } from './lifecycle.js';
9
+ import type { ProofRef } from './member-root.js';
9
10
  import { type Mutex } from './mutex.js';
10
11
  import { type CommitPolicyContext } from './policy.js';
11
12
  import { type DeviceOp, type DeviceRegistry } from './registry.js';
12
13
  import type { RosterState } from './roster.js';
14
+ export declare function registryAt(group: GroupHandle, head: Uint8Array): DeviceRegistry;
13
15
  export declare function mutexFor(handle: GroupHandle): Mutex;
14
16
  /** Events a GroupHandle emits. Advisory notifications derived from the folded ledger; never
15
17
  * a protocol input. Delivered via `fire` (a throwing listener never breaks a fold). */
16
18
  export type GroupHandleEvents = {
19
+ memberRemoved: Array<{
20
+ controller: string;
21
+ member: {
22
+ did: string;
23
+ add: string;
24
+ };
25
+ removedLeaves: Array<string>;
26
+ }>;
17
27
  deviceRevoked: Array<{
18
28
  device: string;
19
29
  controller: string;
20
- logPosition?: number;
30
+ proofRef?: ProofRef;
21
31
  reason?: 'reset';
22
32
  cascadedFrom?: string;
23
33
  }>;
@@ -112,6 +122,7 @@ export declare class GroupHandle {
112
122
  get roster(): RosterState;
113
123
  /** The device registry folded from the anchor and every applied ledger entry. */
114
124
  get registry(): DeviceRegistry;
125
+ settleAdvisory(): 'ok' | 'prompt' | 'blocked';
115
126
  /**
116
127
  * The device deny set the auth service consumes: the DIDs revoked in the CURRENTLY folded
117
128
  * registry (pre-commit). Matched, never enumerated by consumers. A revoke takes deny-effect from