@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
@@ -5,36 +5,19 @@ 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 { buildCommitPolicyContext, deriveGroup, mutexFor } from './group-handle.js';
8
+ import { assertBindingAuthorTime } from './group-credential.js';
9
+ import { buildCommitPolicyContext, CommitRejectedError, deriveGroup, mutexFor } from './group-handle.js';
9
10
  import { buildLedgerHeadExtension, extendHead, readLedgerHead } from './head.js';
10
11
  import { ledgerEntryDigest, signLedgerEntry, verifyLedgerEntry } from './ledger.js';
11
- import { defaultCommitPolicy } from './policy.js';
12
+ import { prepareLifecycleGate, rejectionReason, validateEntry } from './lifecycle.js';
12
13
  import { authority, controllerOf, DEVICE_ENTRY_TYPE } from './registry.js';
13
14
  import { ROLE_ENTRY_TYPE } from './roster.js';
14
- /**
15
- * Thrown by {@link commitInvite} when the supplied key package's credential DID is not the
16
- * identity the invite's enacted role entry grants a role to.
17
- *
18
- * Distinct from an ordinary rejection on purpose: the expected trigger is a key-package store
19
- * that served the wrong owner's package, and adding the package anyway would put a different
20
- * identity in the group than the one the roster grants the role to. A host should alert on this.
21
- *
22
- * The same error also fires for any invite whose trailing `kumiai.role` entry names someone
23
- * other than the intended invitee — hand-built, tampered, or reordered — with an otherwise
24
- * honest key package. A host seeing this should not assume a store compromise on that basis
25
- * alone.
26
- *
27
- * The receive-side add rule in {@link defaultCommitPolicy} does NOT close this residual, though it
28
- * is easy to assume it would. That rule rejects an Add whose DID the candidate roster grants
29
- * nothing; in the reordered case the trailing grant's subject IS granted, so the Add passes and the
30
- * intended invitee is left holding a grant it never joined against. Closing it needs this binding to
31
- * seek the enacted entry matching the key package's DID rather than reading the last one.
32
- */ export class InviteRecipientMismatchError extends Error {
15
+ /** The supplied key package names a different identity from the invite's recipient. */ export class InviteRecipientMismatchError extends Error {
33
16
  #groupID;
34
17
  #expectedDID;
35
18
  #actualDID;
36
19
  constructor(params){
37
- super(`commitInvite: the key package presents ${params.actualDID}, but the invite grants a role to ${params.expectedDID}`);
20
+ super(`commitInvite: the key package presents ${params.actualDID}, but the invite names recipient ${params.expectedDID}`);
38
21
  this.name = 'InviteRecipientMismatchError';
39
22
  this.#groupID = params.groupID;
40
23
  this.#expectedDID = params.expectedDID;
@@ -43,49 +26,50 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
43
26
  get groupID() {
44
27
  return this.#groupID;
45
28
  }
46
- /** DID the invite's enacted role entry grants to. */ get expectedDID() {
29
+ /** DID the invite names. */ get expectedDID() {
47
30
  return this.#expectedDID;
48
31
  }
49
32
  /** DID the supplied key package presents. */ get actualDID() {
50
33
  return this.#actualDID;
51
34
  }
52
35
  }
53
- /**
54
- * Create an invite for a new member. Does NOT add them — call commitInvite with
55
- * their key package for that.
56
- *
57
- * Only an admin may invite: a role entry from a non-admin issuer is dropped by every
58
- * receiver's fold, so refusing here turns a silent downstream rejection into a local
59
- * error.
60
- */ export async function createInvite(params) {
61
- const { group, identity, recipientDID, permission } = params;
62
- if (group.roster.roles.get(authority(group.registry, identity.id)) !== 'admin') {
63
- throw new Error('createInvite: the inviter must be an admin in the group roster');
36
+ /** Create an invite without adding its recipient; commitInvite enacts the admission. */ export async function createInvite(params) {
37
+ const { group, identity, recipientDID } = params;
38
+ let appended;
39
+ if (group.anchor.controller != null) {
40
+ if (params.permission != null) throw new Error('createInvite: lifecycle invites have no permission');
41
+ if (group.findMemberLeafIndex(identity.id) == null) {
42
+ throw new Error('createInvite: the inviter must hold a leaf');
43
+ }
44
+ appended = params.entries ?? [];
45
+ for (const token of appended){
46
+ const verified = await verifyLedgerEntry(token);
47
+ 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');
48
+ }
49
+ } else {
50
+ if (params.permission == null) throw new Error('createInvite: standard invites require permission');
51
+ if (group.roster.roles.get(authority(group.registry, identity.id)) !== 'admin') {
52
+ throw new Error('createInvite: the inviter must be an admin in the group roster');
53
+ }
54
+ appended = [
55
+ await signLedgerEntry(identity, {
56
+ type: ROLE_ENTRY_TYPE,
57
+ groupID: group.groupID,
58
+ subject: recipientDID,
59
+ value: params.permission
60
+ })
61
+ ];
64
62
  }
65
- // The role entry naming the invitee. Its issuer is the inviter (authenticated by
66
- // the token signature) and its value is the permission granted.
67
- const roleToken = await signLedgerEntry(identity, {
68
- type: ROLE_ENTRY_TYPE,
69
- groupID: group.groupID,
70
- subject: recipientDID,
71
- value: permission
72
- });
73
- const invite = {
74
- groupID: group.groupID,
75
- inviterID: identity.id,
76
- // The whole log, new role entry last: a joiner handed only its own entry would
77
- // never learn of earlier role changes and would reject every commit by an admin
78
- // promoted since — a permanent fork nothing re-sends. The new entry must fold
79
- // after the history it depends on, hence last. Re-granting a role the log already
80
- // carries appends it again (a legal re-enactment). The joiner still folds from the
81
- // anchor, so padding this list cannot promote anyone.
82
- ledgerEntries: [
83
- ...group.ledgerTokens,
84
- roleToken
85
- ]
86
- };
87
63
  return {
88
- invite
64
+ invite: {
65
+ groupID: group.groupID,
66
+ inviterID: identity.id,
67
+ recipientDID,
68
+ ledgerEntries: [
69
+ ...group.ledgerTokens,
70
+ ...appended
71
+ ]
72
+ }
89
73
  };
90
74
  }
91
75
  /**
@@ -120,14 +104,18 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
120
104
  * When `enacted` is non-empty the commit also carries a group-context-extensions
121
105
  * proposal advancing the head by exactly those ids, in envelope order. An empty list
122
106
  * moves no head and carries no envelope.
123
- */ export async function commitWithEntries(group, extraProposals, enacted, options = {}) {
124
- const ratchetTreeExtension = options.ratchetTreeExtension ?? false;
125
- const requireAdmin = options.requireAdmin ?? true;
107
+ */ export async function commitWithEntries(params) {
108
+ const { group, extraProposals, enacted } = params;
109
+ if (group.anchor.controller != null && group.findMemberLeafIndex(group.credential.id) == null) {
110
+ throw new Error('the committer must hold a leaf');
111
+ }
112
+ const ratchetTreeExtension = params.ratchetTreeExtension ?? false;
113
+ const requireAdmin = params.requireAdmin ?? true;
126
114
  // Same reason createInvite guards the inviter: a non-admin's commit is rejected by
127
115
  // every receiver, so fail here rather than emitting a commit nobody will apply.
128
116
  // Authority-aware: a device of an admin profile commits as that profile. Device-only commits
129
117
  // (register/add/revoke/label) are authorized by proofs, not a role, so they pass requireAdmin:false.
130
- if (requireAdmin && group.roster.roles.get(authority(group.registry, group.credential.id)) !== 'admin') {
118
+ if (requireAdmin && group.anchor.controller == null && group.roster.roles.get(authority(group.registry, group.credential.id)) !== 'admin') {
131
119
  throw new Error('the committer must be an admin in the group roster');
132
120
  }
133
121
  // Fold the entries exactly as every receiver will; refuse to author a commit the
@@ -147,8 +135,18 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
147
135
  entryID: ledgerEntryDigest(token)
148
136
  });
149
137
  }
150
- const fold = foldEnvelope(group.roster, group.registry, inputs, group.groupID);
138
+ const fold = foldEnvelope({
139
+ baseRoster: group.roster,
140
+ baseRegistry: group.registry,
141
+ entries: inputs,
142
+ groupID: group.groupID,
143
+ context: group.anchor.controller == null ? undefined : {
144
+ controllerID: group.anchor.controller,
145
+ memberController: (did)=>group.bindingOfDID(did)?.controller
146
+ }
147
+ });
151
148
  if (!fold.ok) {
149
+ if (fold.error != null) throw fold.error;
152
150
  throw new Error(`cannot enact ledger entry ${fold.entryID}: ${fold.reason}`);
153
151
  }
154
152
  // Same reason as the fold guard above: verify device entries against THIS group's tree and
@@ -159,39 +157,28 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
159
157
  };
160
158
  for (const input of inputs){
161
159
  if (input.verified.entry.type !== DEVICE_ENTRY_TYPE) continue;
160
+ if (group.anchor.controller != null && input.verified.entry.value.op !== 'beacon') {
161
+ continue;
162
+ }
162
163
  const ok = await verifyDeviceEntry(input.verified, proofCtx);
163
164
  if (!ok) {
164
165
  throw new Error(`cannot enact device entry ${input.entryID}: proof verification failed`);
165
166
  }
166
167
  }
167
168
  const entryIDs = enacted.map(ledgerEntryDigest);
168
- // Filter the pending-proposal set the committer would otherwise absorb: ts-mls folds
169
- // every unappliedProposal into the commit, so a non-admin's pending proposal would
170
- // ride it and every peer would reject the whole thing — one member could stall the
171
- // group. Judge each against the same defaultCommitPolicy and context receivers build,
172
- // dropping any the group would reject.
173
169
  const enactedDeviceEntries = inputs.filter((i)=>i.verified.entry.type === DEVICE_ENTRY_TYPE).map((i)=>({
174
170
  subject: normalizeDID(i.verified.entry.subject),
175
171
  op: i.verified.entry.value.op
176
172
  }));
177
- const filterContext = buildCommitPolicyContext(group, {
173
+ const gateContext = buildCommitPolicyContext(group, {
178
174
  baseRoster: group.roster,
179
175
  candidateRoster: fold.roster,
180
176
  entryIDs,
181
177
  enactedDeviceEntries
182
178
  });
183
- const keptPending = {};
184
- for (const [ref, pws] of Object.entries(group.state.unappliedProposals)){
185
- if (defaultCommitPolicy({
186
- kind: 'proposal',
187
- proposal: pws
188
- }, filterContext) !== 'reject') {
189
- keptPending[ref] = pws;
190
- }
191
- }
192
179
  const commitState = {
193
- ...group.state,
194
- unappliedProposals: keptPending
180
+ ...params.commitState ?? group.state,
181
+ unappliedProposals: params.pendingProposals ?? {}
195
182
  };
196
183
  const proposals = [
197
184
  ...extraProposals
@@ -204,7 +191,41 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
204
191
  }
205
192
  });
206
193
  }
207
- return await createCommit({
194
+ const gate = await prepareLifecycleGate({
195
+ group,
196
+ entries: inputs.map(({ verified })=>verified),
197
+ candidateRegistry: fold.registry,
198
+ context: gateContext
199
+ });
200
+ const incoming = {
201
+ kind: 'commit',
202
+ senderLeafIndex: group.state.privatePath.leafIndex,
203
+ proposals: [
204
+ ...Object.values(commitState.unappliedProposals),
205
+ ...proposals.map((proposal)=>({
206
+ proposal,
207
+ senderLeafIndex: group.state.privatePath.leafIndex
208
+ }))
209
+ ]
210
+ };
211
+ try {
212
+ gate.check(incoming);
213
+ } catch (cause) {
214
+ if (params.pendingProposals == null) throw cause;
215
+ const error = new CommitRejectedError(incoming.proposals, incoming.senderLeafIndex, rejectionReason(cause));
216
+ error.cause = cause;
217
+ throw error;
218
+ }
219
+ for (const proposal of proposals){
220
+ if (proposal.proposalType === defaultProposalTypes.add) {
221
+ const leaf = proposal.add.keyPackage.leafNode;
222
+ if (isDefaultCredential(leaf.credential) && leaf.credential.credentialType === defaultCredentialTypes.basic) {
223
+ assertBindingAuthorTime(parseMLSCredentialIdentity(leaf.credential.identity).controller);
224
+ }
225
+ await validateEntry(group, leaf);
226
+ }
227
+ }
228
+ const result = await createCommit({
208
229
  context: group.context,
209
230
  state: commitState,
210
231
  extraProposals: proposals,
@@ -218,6 +239,8 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
218
239
  })
219
240
  }
220
241
  });
242
+ await gate.postApply(result.newState);
243
+ return result;
221
244
  }
222
245
  /**
223
246
  * The entries an invite adds beyond the committer's own log: everything past the
@@ -256,7 +279,11 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
256
279
  if (tokens.length === 0) {
257
280
  throw new Error('commitLedgerEntries: no ledger entries to commit');
258
281
  }
259
- const result = await commitWithEntries(group, [], tokens);
282
+ const result = await commitWithEntries({
283
+ group,
284
+ extraProposals: [],
285
+ enacted: tokens
286
+ });
260
287
  const newGroup = deriveGroup(group, result.newState);
261
288
  await newGroup.applyLedgerEntries(tokens);
262
289
  return {
@@ -272,7 +299,7 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
272
299
  *
273
300
  * The invite's ledger entries are enacted here: their content ids ride the commit's
274
301
  * control envelope and advance the head by exactly those ids, so every receiver folds
275
- * the invitee's role entry as it applies the Add. The envelope carries ids, not
302
+ * the appended entries as it applies the Add. The envelope carries ids, not
276
303
  * bodies — a receiver holding neither the entry nor a `resolveLedgerEntries` resolver
277
304
  * throws MissingLedgerEntriesError.
278
305
  *
@@ -291,40 +318,39 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
291
318
  throw new Error(`commitInvite: invite is for group ${invite.groupID}, not ${group.groupID}`);
292
319
  }
293
320
  const enacted = entriesAddedByInvite(group, invite);
294
- // Bind the leaf that joins to the role this same commit grants. Without it the joining
295
- // identity is decided by whoever supplied the key package bytes — a store that served the
296
- // wrong owner's package admits that owner while the roster names someone else, and neither
297
- // side can see the disagreement from its own state.
298
- //
299
- // The LAST role entry, because an invite may legitimately carry an unrelated promotion
300
- // riding the same commit, and createInvite puts the invitee's own grant last.
301
- //
302
- // The `groupID` check is belt-and-braces: `foldEnvelope` already hard-rejects any
303
- // cross-group entry in `enacted`, so no invite reaching this point can carry one.
304
- let grantedTo = null;
305
- for (const token of enacted){
306
- const verified = await verifyLedgerEntry(token);
307
- if (verified?.entry.type === ROLE_ENTRY_TYPE && verified.entry.groupID === group.groupID) {
308
- grantedTo = verified.entry.subject;
321
+ const expectedDID = normalizeDID(invite.recipientDID);
322
+ if (group.anchor.controller == null) {
323
+ let grantedTo = null;
324
+ for (const token of enacted){
325
+ const verified = await verifyLedgerEntry(token);
326
+ if (verified?.entry.type === ROLE_ENTRY_TYPE && verified.entry.groupID === group.groupID) {
327
+ grantedTo = verified.entry.subject;
328
+ }
329
+ }
330
+ if (grantedTo == null) {
331
+ throw new Error(`commitInvite: the invite enacts no ${ROLE_ENTRY_TYPE} entry for this group`);
332
+ }
333
+ if (normalizeDID(grantedTo) !== expectedDID) {
334
+ throw new InviteRecipientMismatchError({
335
+ groupID: group.groupID,
336
+ expectedDID,
337
+ actualDID: normalizeDID(grantedTo)
338
+ });
309
339
  }
310
340
  }
311
- if (grantedTo == null) {
312
- throw new Error(`commitInvite: the invite enacts no ${ROLE_ENTRY_TYPE} entry for this group, so there is no recipient to bind the key package to`);
313
- }
314
- const expectedDID = normalizeDID(grantedTo);
315
341
  // `credentialType !== basic` does not narrow on its own: CredentialCustom.credentialType is a
316
342
  // bare `number`, so the compiler cannot rule it out. ts-mls's own guard can.
317
343
  //
318
- // This inlines the same credential->DID chain `didFromCredential` (credential.ts) implements
319
- // for the receive-side policy, kept separate deliberately: this path needs to distinguish a
320
- // non-basic credential from a malformed-JSON failure for its error messages, and that helper
321
- // is deliberately unexported. The two must stay in agreement — if they diverge, the committer
322
- // authors a commit every receiver rejects, a liveness failure rather than a security one.
344
+ // The exported `didFromCredential` collapses absent identities to null. This inlined variant
345
+ // distinguishes non-basic credentials from malformed JSON for its error messages.
346
+ // DID normalisation must agree with the helper, or receivers reject the authored commit.
323
347
  const credential = keyPackage.leafNode.credential;
324
348
  if (!isDefaultCredential(credential) || credential.credentialType !== defaultCredentialTypes.basic) {
325
349
  throw new Error('commitInvite: the key package carries a non-basic credential, which names no DID to bind');
326
350
  }
327
- const actualDID = normalizeDID(parseMLSCredentialIdentity(credential.identity).id);
351
+ const recipientID = parseMLSCredentialIdentity(credential.identity).id;
352
+ if (recipientID === '') throw new Error('commitInvite: the recipient credential names no DID');
353
+ const actualDID = normalizeDID(recipientID);
328
354
  if (actualDID !== expectedDID) {
329
355
  throw new InviteRecipientMismatchError({
330
356
  groupID: group.groupID,
@@ -338,9 +364,12 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
338
364
  keyPackage
339
365
  }
340
366
  };
341
- const result = await commitWithEntries(group, [
342
- addProposal
343
- ], enacted, {
367
+ const result = await commitWithEntries({
368
+ group,
369
+ extraProposals: [
370
+ addProposal
371
+ ],
372
+ enacted,
344
373
  ratchetTreeExtension: true
345
374
  });
346
375
  const newGroup = deriveGroup(group, result.newState);
@@ -1,12 +1,16 @@
1
1
  import { type Capabilities, type GroupContextExtension, type MlsContext } from 'ts-mls';
2
+ import type { GroupAnchor } from './anchor.js';
2
3
  import type { GroupOptions } from './types.js';
3
4
  /** Late-bound provider of a context's device deny set, pointed at the live handle after construction. */
4
5
  export type DeviceDenyHolder = {
5
6
  provider: () => ReadonlySet<string>;
7
+ leafLifetime?: number;
8
+ trustedGrantLifetime?: number;
6
9
  };
7
- /** The deny holder for a context built by {@link resolveMlsContext}, or undefined for others. */
10
+ /** The deny holder for an internally built context, or undefined for others. */
8
11
  export declare function deviceDenyHolderFor(context: MlsContext): DeviceDenyHolder | undefined;
9
- export declare function resolveMlsContext(options?: GroupOptions): Promise<MlsContext>;
12
+ export declare function resolveMlsContext(options?: GroupOptions, anchor?: GroupAnchor): Promise<MlsContext>;
13
+ export declare function createMlsContext(cipherSuite: MlsContext['cipherSuite'], anchor?: GroupAnchor): MlsContext;
10
14
  /**
11
15
  * Build the leaf-node capabilities for a member joining or creating a group. RFC
12
16
  * 9420 requires a leaf to advertise every non-default GroupContext extension type
@@ -4,19 +4,26 @@ import { nobleCryptoProvider } from './crypto.js';
4
4
  const DEFAULT_CIPHERSUITE = 'MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519';
5
5
  const EMPTY_DENY = new Set();
6
6
  const DENY_HOLDERS = new WeakMap();
7
- /** The deny holder for a context built by {@link resolveMlsContext}, or undefined for others. */ export function deviceDenyHolderFor(context) {
7
+ /** The deny holder for an internally built context, or undefined for others. */ export function deviceDenyHolderFor(context) {
8
8
  return DENY_HOLDERS.get(context);
9
9
  }
10
- export async function resolveMlsContext(options) {
10
+ export async function resolveMlsContext(options, anchor) {
11
11
  const name = options?.ciphersuiteName ?? DEFAULT_CIPHERSUITE;
12
12
  const cipherSuite = await getCiphersuiteImpl(name, options?.cryptoProvider ?? nobleCryptoProvider);
13
+ return createMlsContext(cipherSuite, anchor);
14
+ }
15
+ export function createMlsContext(cipherSuite, anchor) {
13
16
  // The deny set cannot be known here — the handle that folds it does not exist yet. Bind a mutable
14
17
  // holder the auth service reads; the GroupHandle constructor points it at its own currentDenySet().
15
18
  const holder = {
16
- provider: ()=>EMPTY_DENY
19
+ provider: ()=>EMPTY_DENY,
20
+ leafLifetime: anchor?.controller == null ? undefined : anchor.leafLifetime ?? 86_400,
21
+ trustedGrantLifetime: anchor?.controller == null ? undefined : anchor.trustedGrantLifetime ?? 2_592_000
17
22
  };
18
23
  const authService = createDIDAuthenticationService({
19
- deviceDenySet: ()=>holder.provider()
24
+ deviceDenySet: ()=>holder.provider(),
25
+ leafLifetime: ()=>holder.leafLifetime,
26
+ trustedGrantLifetime: ()=>holder.trustedGrantLifetime
20
27
  });
21
28
  const context = {
22
29
  cipherSuite,
@@ -1,16 +1,16 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
2
  import { generateKeyPackageWithKey, createGroup as mlsCreateGroup } from 'ts-mls';
3
- import { buildCurrentGroupAnchorExtension, decodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, LEDGER_HEAD_EXTENSION_TYPE } from './anchor.js';
3
+ import { buildCurrentGroupAnchorExtension, buildGroupAnchorExtension, decodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, LEDGER_HEAD_EXTENSION_TYPE } from './anchor.js';
4
+ import { verifyLeafCredential } from './authentication.js';
5
+ import { LeafBindingError } from './errors.js';
4
6
  import { buildLeafCapabilities, resolveMlsContext } from './group-context.js';
5
- import { makeMLSCredential } from './group-credential.js';
7
+ import { assertBindingAuthorTime, makeMLSCredential } from './group-credential.js';
6
8
  import { GroupHandle } from './group-handle.js';
7
9
  import { buildLedgerHeadExtension, genesisHead } from './head.js';
8
10
  /** Create a new MLS group. The identity becomes the sole member and admin. */ export async function createGroup(identity, groupID, options) {
9
- const context = await resolveMlsContext(options);
10
- // Every group is anchored at creation: creator is the epoch-0 admin, ledger head
11
- // starts at genesis. A caller-supplied anchor is left untouched (the caller owns
12
- // its contents); its `creatorDID` coupling to the creating identity is validated
13
- // below. A decode failure here is left to the fail-closed decode in the constructor.
11
+ assertBindingAuthorTime(options?.controller);
12
+ // A binding enriches a supplied anchor before genesis; standard anchor bytes stay untouched.
13
+ // Existing lifecycle fields must agree with the authored policy before the tree is validated.
14
14
  const extensions = [
15
15
  ...options?.extensions ?? []
16
16
  ];
@@ -21,15 +21,60 @@ import { buildLedgerHeadExtension, genesisHead } from './head.js';
21
21
  if (suppliedAnchor != null && normalizeDID(suppliedAnchor.creatorDID) !== normalizeDID(identity.id)) {
22
22
  throw new Error(`createGroup: the anchor's creatorDID (${suppliedAnchor.creatorDID}) must be the creating identity (${identity.id})`);
23
23
  }
24
+ if (suppliedAnchor != null && suppliedAnchorData instanceof Uint8Array && options?.controller != null) {
25
+ const leafLifetime = options.leafLifetime ?? 86_400;
26
+ const trustedGrantLifetime = options.trustedGrantLifetime ?? 2_592_000;
27
+ if (suppliedAnchor.controller !== undefined && suppliedAnchor.controller !== options.controller.id) {
28
+ throw new LeafBindingError('controller-mismatch');
29
+ }
30
+ if (suppliedAnchor.leafLifetime !== undefined && suppliedAnchor.leafLifetime !== leafLifetime || suppliedAnchor.trustedGrantLifetime !== undefined && suppliedAnchor.trustedGrantLifetime !== trustedGrantLifetime) {
31
+ throw new Error('Lifecycle lifetime options must match the supplied anchor');
32
+ }
33
+ // Reading normally withholds future-version app payloads; authoring must preserve them.
34
+ const original = JSON.parse(new TextDecoder().decode(suppliedAnchorData));
35
+ extensions[extensions.indexOf(suppliedAnchorExtension)] = buildGroupAnchorExtension({
36
+ ...suppliedAnchor,
37
+ app: original.app,
38
+ controller: options.controller.id,
39
+ leafLifetime,
40
+ trustedGrantLifetime
41
+ });
42
+ }
43
+ }
44
+ if (suppliedAnchorExtension == null) {
45
+ extensions.push(options?.controller == null ? buildCurrentGroupAnchorExtension(identity.id) : buildGroupAnchorExtension({
46
+ creatorDID: identity.id,
47
+ version: 1,
48
+ controller: options.controller.id,
49
+ leafLifetime: options.leafLifetime ?? 86_400,
50
+ trustedGrantLifetime: options.trustedGrantLifetime ?? 2_592_000
51
+ }));
24
52
  }
25
- if (!extensions.some((ext)=>ext.extensionType === GROUP_ANCHOR_EXTENSION_TYPE)) {
26
- extensions.push(buildCurrentGroupAnchorExtension(identity.id));
53
+ const anchorExtension = extensions.find((ext)=>ext.extensionType === GROUP_ANCHOR_EXTENSION_TYPE);
54
+ const anchorData = anchorExtension?.extensionData;
55
+ const anchor = anchorData instanceof Uint8Array ? decodeGroupAnchor(anchorData) : null;
56
+ if (anchor == null) throw new Error('group anchor extension present but could not be decoded');
57
+ if (anchor.controller != null) {
58
+ if (options?.controller == null) throw new LeafBindingError('floating-refused');
59
+ if (normalizeDID(anchor.controller) !== normalizeDID(options.controller.id)) {
60
+ throw new LeafBindingError('controller-mismatch');
61
+ }
62
+ } else if (options?.controller != null) {
63
+ throw new LeafBindingError('controller-mismatch');
64
+ }
65
+ const context = await resolveMlsContext(options, anchor);
66
+ const mlsCredential = makeMLSCredential(identity, options?.controller);
67
+ if (options?.controller != null) {
68
+ await verifyLeafCredential(mlsCredential, identity.publicKey, {
69
+ leafLifetime: ()=>anchor.leafLifetime ?? 86_400,
70
+ trustedGrantLifetime: ()=>anchor.trustedGrantLifetime ?? 2_592_000
71
+ });
27
72
  }
28
73
  if (!extensions.some((ext)=>ext.extensionType === LEDGER_HEAD_EXTENSION_TYPE)) {
29
74
  extensions.push(buildLedgerHeadExtension(genesisHead(groupID)));
30
75
  }
31
76
  const statePromise = generateKeyPackageWithKey({
32
- credential: makeMLSCredential(identity),
77
+ credential: mlsCredential,
33
78
  signatureKeyPair: {
34
79
  signKey: identity.privateKey,
35
80
  publicKey: identity.publicKey
@@ -64,7 +109,7 @@ import { buildLedgerHeadExtension, genesisHead } from './head.js';
64
109
  };
65
110
  }
66
111
  export async function restoreGroup(params) {
67
- // Construction reseeds `{creator: 'admin'}` from the anchor in the restored state;
112
+ // Construction reseeds control authority from the anchor in the restored state;
68
113
  // an anchorless state throws (the same fail-closed guard).
69
114
  const group = new GroupHandle({
70
115
  state: params.state,
@@ -1,7 +1,9 @@
1
1
  import { type OwnIdentity } from '@kokuin/token';
2
2
  import { type Credential } from 'ts-mls';
3
+ import type { ControllerBinding } from './credential.js';
3
4
  import type { GroupOptions, KeyPackageBundle } from './types.js';
4
- export declare function makeMLSCredential(identity: OwnIdentity): Credential;
5
+ export declare function makeMLSCredential(identity: OwnIdentity, controller?: ControllerBinding): Credential;
6
+ export declare function assertBindingAuthorTime(controller?: ControllerBinding): void;
5
7
  /**
6
8
  * How long an ordinary, single-use key package stays valid, in days.
7
9
  *
@@ -1,8 +1,10 @@
1
- import { isPeer4 } from '@kokuin/token';
1
+ import { isPeer4, now } from '@kokuin/token';
2
2
  import { defaultCredentialTypes, generateKeyPackageWithKey, greaseExtensions, makeCustomExtension } from 'ts-mls';
3
3
  import { controlCapabilities } from './anchor.js';
4
+ import { verifyLeafCredential } from './authentication.js';
5
+ import { readCapability } from './capability.js';
4
6
  import { resolveMlsContext } from './group-context.js';
5
- export function makeMLSCredential(identity) {
7
+ export function makeMLSCredential(identity, controller) {
6
8
  const id = identity.id;
7
9
  const isPeer = isPeer4(id);
8
10
  if (isPeer && !('longForm' in identity && typeof identity.longForm === 'string')) {
@@ -12,6 +14,7 @@ export function makeMLSCredential(identity) {
12
14
  v: 1,
13
15
  id
14
16
  };
17
+ if (controller != null) payload.controller = controller;
15
18
  if (isPeer) {
16
19
  payload.longForm = identity.longForm;
17
20
  }
@@ -20,6 +23,14 @@ export function makeMLSCredential(identity) {
20
23
  identity: new TextEncoder().encode(JSON.stringify(payload))
21
24
  };
22
25
  }
26
+ export function assertBindingAuthorTime(controller) {
27
+ if (controller == null) return;
28
+ const { iat, exp } = readCapability(controller.capability).payload;
29
+ const timestamp = now();
30
+ if (exp <= timestamp || iat > timestamp) {
31
+ throw new Error('Leaf capability is not valid at authoring time');
32
+ }
33
+ }
23
34
  /**
24
35
  * Shared key-package construction. An invitee leaf must advertise the control extension types or
25
36
  * ts-mls refuses to add it to an anchored group. An explicit `options.capabilities` override still
@@ -29,9 +40,12 @@ export function makeMLSCredential(identity) {
29
40
  * so `generateKeyPackageWithKey`'s own `params.extensions ?? greaseExtensions(...)` default still
30
41
  * applies for the ordinary path.
31
42
  */ async function buildBundle(identity, options, overrides = {}) {
43
+ assertBindingAuthorTime(options?.controller);
44
+ const credential = makeMLSCredential(identity, options?.controller);
45
+ if (options?.controller != null) await verifyLeafCredential(credential, identity.publicKey);
32
46
  const { cipherSuite } = await resolveMlsContext(options);
33
47
  const result = await generateKeyPackageWithKey({
34
- credential: makeMLSCredential(identity),
48
+ credential,
35
49
  signatureKeyPair: {
36
50
  signKey: identity.privateKey,
37
51
  publicKey: identity.publicKey