@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
@@ -0,0 +1,300 @@
1
+ import { didFromInception, foldLog } from '@kokuin/controller';
2
+ import { createSigningIdentityForDID, normalizeDID } from '@kokuin/token';
3
+ import { defaultProposalTypes, encode, mlsMessageEncoder, nodeTypes } from 'ts-mls';
4
+ import { readCapability } from './capability.js';
5
+ import { parseMLSCredentialIdentity } from './credential.js';
6
+ import { LeafBindingError, RevokeProofError } from './errors.js';
7
+ import { commitWithEntries } from './group-commit.js';
8
+ import { assertBindingAuthorTime } from './group-credential.js';
9
+ import { deriveGroup, mutexFor } from './group-handle.js';
10
+ import { HISTORY_HORIZON, historySize } from './history.js';
11
+ import { signLedgerEntry } from './ledger.js';
12
+ import { isLapsed, leafAt, treeTime, validateEntry } from './lifecycle.js';
13
+ import { authenticateLifecycleProof, verifyLifecycleProof } from './lifecycle-proof.js';
14
+ import { DEVICE_ENTRY_TYPE } from './registry.js';
15
+ function ownIdentity(group) {
16
+ const leaf = leafAt(group.state.ratchetTree, group.state.privatePath.leafIndex);
17
+ if (leaf == null || !('identity' in leaf.credential)) throw new LeafBindingError('identity-change');
18
+ const parsed = parseMLSCredentialIdentity(leaf.credential.identity);
19
+ return createSigningIdentityForDID(parsed.longForm ?? parsed.id, group.state.signaturePrivateKey);
20
+ }
21
+ async function clockEntries(group, tree) {
22
+ const controller = group.anchor.controller;
23
+ if (controller == null) return [];
24
+ const before = treeTime(group, controller);
25
+ let after = group.registry.controllers.get(normalizeDID(controller))?.timeFloor ?? 0;
26
+ for (const node of tree){
27
+ if (node?.nodeType !== nodeTypes.leaf || !('identity' in node.leaf.credential)) continue;
28
+ const binding = parseMLSCredentialIdentity(node.leaf.credential.identity).controller;
29
+ if (binding == null || normalizeDID(binding.id) !== normalizeDID(controller)) continue;
30
+ const payload = readCapability(binding.capability).payload;
31
+ const parent = Array.isArray(payload.cap) ? payload.cap[0] : payload.cap;
32
+ after = Math.max(after, parent == null ? payload.iat : readCapability(parent).payload.iat);
33
+ }
34
+ if (after >= before) return [];
35
+ return [
36
+ await signLedgerEntry(ownIdentity(group), {
37
+ type: DEVICE_ENTRY_TYPE,
38
+ groupID: group.groupID,
39
+ subject: controller,
40
+ value: {
41
+ op: 'clock',
42
+ time: before
43
+ }
44
+ })
45
+ ];
46
+ }
47
+ async function buildResult(params) {
48
+ const { group, proposals, tokens, commitState } = params;
49
+ const result = await commitWithEntries({
50
+ group,
51
+ extraProposals: proposals,
52
+ enacted: tokens,
53
+ requireAdmin: false,
54
+ commitState
55
+ });
56
+ // MLS captured the replacement tree as historical data when building a renewal.
57
+ const historical = result.newState.historicalReceiverData.get(group.epoch);
58
+ if (historical != null && commitState != null) historical.ratchetTree = group.state.ratchetTree;
59
+ const newGroup = deriveGroup(group, result.newState);
60
+ await newGroup.applyLedgerEntries(tokens);
61
+ return {
62
+ commitMessage: encode(mlsMessageEncoder, result.commit),
63
+ newGroup,
64
+ epoch: newGroup.epoch
65
+ };
66
+ }
67
+ export async function renewLeaf(group, binding) {
68
+ return mutexFor(group).run(async ()=>{
69
+ assertBindingAuthorTime(binding);
70
+ const index = group.state.privatePath.leafIndex * 2;
71
+ const tree = group.state.ratchetTree.slice();
72
+ const original = tree[index];
73
+ if (original?.nodeType !== nodeTypes.leaf || !('identity' in original.leaf.credential)) throw new LeafBindingError('identity-change');
74
+ const own = structuredClone(original);
75
+ if (!('identity' in own.leaf.credential)) throw new LeafBindingError('identity-change');
76
+ const parsed = parseMLSCredentialIdentity(own.leaf.credential.identity);
77
+ own.leaf.credential.identity = new TextEncoder().encode(JSON.stringify({
78
+ v: 1,
79
+ ...parsed,
80
+ controller: binding
81
+ }));
82
+ tree[index] = own;
83
+ await validateEntry(group, own.leaf, original.leaf);
84
+ if (group.anchor.controller != null) {
85
+ const entries = group.ledger.map(({ verified })=>verified);
86
+ const before = historySize(group.state.ratchetTree, entries);
87
+ const after = historySize(tree, entries);
88
+ if (after > HISTORY_HORIZON && after > before) throw new LeafBindingError('history-horizon');
89
+ }
90
+ const tokens = await clockEntries(group, tree);
91
+ return buildResult({
92
+ group,
93
+ proposals: [],
94
+ tokens,
95
+ commitState: {
96
+ ...group.state,
97
+ ratchetTree: tree
98
+ }
99
+ });
100
+ });
101
+ }
102
+ export async function removeLapsedLeaves(group) {
103
+ return mutexFor(group).run(async ()=>{
104
+ const removed = [];
105
+ const proposals = [];
106
+ const tree = group.state.ratchetTree.slice();
107
+ for (const member of group.listMembers()){
108
+ const leaf = leafAt(tree, member.leafIndex);
109
+ if (leaf == null || !isLapsed(group, leaf)) continue;
110
+ removed.push(member.id);
111
+ tree[member.leafIndex * 2] = undefined;
112
+ proposals.push({
113
+ proposalType: defaultProposalTypes.remove,
114
+ remove: {
115
+ removed: member.leafIndex
116
+ }
117
+ });
118
+ }
119
+ if (removed.length === 0) return {
120
+ removed
121
+ };
122
+ const tokens = await clockEntries(group, tree);
123
+ return {
124
+ removed,
125
+ result: await buildResult({
126
+ group,
127
+ proposals,
128
+ tokens
129
+ })
130
+ };
131
+ });
132
+ }
133
+ /** The slice of `log` a receiver needs on top of the controller events it already recorded. */ function proofFor(params) {
134
+ const { group, log, subject, reset } = params;
135
+ const controller = group.anchor.controller;
136
+ if (controller == null) throw new RevokeProofError('wrong-controller');
137
+ if (log.length === 0) throw new RevokeProofError('no-rev');
138
+ const first = log[0];
139
+ if (first?.event.t === 'icp') {
140
+ let did;
141
+ try {
142
+ did = didFromInception(first.event);
143
+ } catch (cause) {
144
+ const rejection = new RevokeProofError('not-authority-signed');
145
+ rejection.cause = cause;
146
+ throw rejection;
147
+ }
148
+ if (normalizeDID(did) !== normalizeDID(controller)) throw new RevokeProofError('wrong-controller');
149
+ }
150
+ if (log.some(({ event })=>event.t !== 'icp' && event.i !== controller)) throw new RevokeProofError('wrong-controller');
151
+ const folded = foldLog(controller, log);
152
+ if (!folded.ok) {
153
+ const detached = /sequence|digest|prior|inception must/.test(folded.reason);
154
+ throw new RevokeProofError(detached ? 'detached' : 'not-authority-signed');
155
+ }
156
+ // Drop events that leave the folded state unchanged.
157
+ const advancing = log.filter((_, index)=>index === 0 || folded.states[index]?.digest !== folded.states[index - 1]?.digest);
158
+ const canonical = foldLog(controller, advancing);
159
+ if (!canonical.ok) throw new RevokeProofError('not-authority-signed');
160
+ let resetIndex = -1;
161
+ for(let index = 1; index < advancing.length; index++){
162
+ if (advancing[index]?.event.g !== advancing[index - 1]?.event.g) resetIndex = index;
163
+ }
164
+ const projection = group.registry.controllers.get(normalizeDID(controller));
165
+ const recorded = projection?.recordedLog ?? [];
166
+ const floor = projection?.genFloor ?? 0;
167
+ if (reset) {
168
+ if (resetIndex < 0) throw new RevokeProofError('no-rev');
169
+ return [
170
+ advancing[0],
171
+ ...advancing.slice(resetIndex)
172
+ ];
173
+ }
174
+ const recordedFold = foldLog(controller, recorded);
175
+ const recordedHead = recordedFold.ok ? recordedFold.states.at(-1) : undefined;
176
+ const generation = canonical.states.at(-1)?.gen ?? 0;
177
+ if (recorded.length > 0 && generation > (recordedHead?.gen ?? floor)) throw new RevokeProofError('needs-reset');
178
+ const start = recorded.length === 0 ? Math.max(1, resetIndex) : 1;
179
+ let end = advancing.findIndex(({ event }, index)=>index >= start && event.t === 'rev' && 'x' in event && typeof event.x === 'string' && normalizeDID(event.x) === subject && (canonical.states[index]?.gen ?? 0) >= floor);
180
+ if (end < 0) {
181
+ if (generation < floor) throw new RevokeProofError('generation-floor');
182
+ throw new RevokeProofError('no-rev');
183
+ }
184
+ if (recorded.length === 0) {
185
+ return [
186
+ advancing[0],
187
+ ...advancing.slice(start, end + 1)
188
+ ];
189
+ }
190
+ const headIndex = canonical.states.findIndex(({ digest })=>digest === recordedHead?.digest);
191
+ if (headIndex < 0) throw new RevokeProofError('detached');
192
+ end = Math.max(headIndex, end);
193
+ return advancing.slice(headIndex + 1, end + 1);
194
+ }
195
+ /** Revoked in the registry, with no leaf of its own and no leaf it issued left in the tree. */ function isFullyRevoked(group, subject) {
196
+ if (group.registry.devices.get(subject)?.status !== 'revoked') return false;
197
+ if (group.findMemberLeafIndex(subject) != null) return false;
198
+ return !group.listMembers().some((member)=>{
199
+ const capability = group.bindingOfDID(member.id)?.capability;
200
+ return capability != null && normalizeDID(readCapability(capability).payload.iss) === subject;
201
+ });
202
+ }
203
+ export async function revokeWithProof(group, params) {
204
+ return mutexFor(group).run(async ()=>{
205
+ try {
206
+ const controller = group.anchor.controller;
207
+ if (controller == null) throw new RevokeProofError('wrong-controller');
208
+ const reset = 'reset' in params;
209
+ const subject = normalizeDID(reset ? controller : params.subject);
210
+ if (!reset && isFullyRevoked(group, subject)) return {
211
+ status: 'already-revoked'
212
+ };
213
+ const value = {
214
+ op: reset ? 'reset' : 'revoke',
215
+ proof: proofFor({
216
+ group,
217
+ log: params.log,
218
+ subject,
219
+ reset
220
+ }),
221
+ revoked: []
222
+ };
223
+ const verified = {
224
+ issuer: group.credential.id,
225
+ entry: {
226
+ type: DEVICE_ENTRY_TYPE,
227
+ groupID: group.groupID,
228
+ subject,
229
+ value
230
+ }
231
+ };
232
+ const authenticated = authenticateLifecycleProof(controller, verified, group.registry);
233
+ const revoked = reset ? [] : [
234
+ {
235
+ did: subject
236
+ }
237
+ ];
238
+ const leaves = group.listMembers().map((member)=>{
239
+ const binding = group.bindingOfDID(member.id);
240
+ const payload = binding?.capability == null ? undefined : readCapability(binding.capability).payload;
241
+ const folded = binding?.prefix == null ? undefined : foldLog(controller, binding.prefix);
242
+ return {
243
+ ...member,
244
+ issuer: payload?.cap == null ? undefined : normalizeDID(payload.iss),
245
+ generation: folded?.ok ? folded.states.at(-1)?.gen : undefined
246
+ };
247
+ });
248
+ if (reset) for (const leaf of leaves){
249
+ if (leaf.generation != null && leaf.generation < authenticated.genFloor) revoked.push({
250
+ did: normalizeDID(leaf.id)
251
+ });
252
+ }
253
+ const direct = new Set(revoked.map(({ did })=>did));
254
+ for (const leaf of leaves){
255
+ if (leaf.issuer != null && direct.has(leaf.issuer) && !direct.has(normalizeDID(leaf.id))) revoked.push({
256
+ did: normalizeDID(leaf.id),
257
+ cascadedFrom: leaf.issuer
258
+ });
259
+ }
260
+ value.revoked = revoked;
261
+ if (revoked.some(({ did })=>did === normalizeDID(group.credential.id))) return {
262
+ status: 'self-affected',
263
+ subject: group.credential.id
264
+ };
265
+ const effects = await verifyLifecycleProof(group, verified);
266
+ const tree = group.state.ratchetTree.slice();
267
+ const proposals = effects.removeLeafIndices.map((removed)=>{
268
+ tree[removed * 2] = undefined;
269
+ return {
270
+ proposalType: defaultProposalTypes.remove,
271
+ remove: {
272
+ removed
273
+ }
274
+ };
275
+ });
276
+ const tokens = [
277
+ await signLedgerEntry(ownIdentity(group), verified.entry),
278
+ ...await clockEntries(group, tree)
279
+ ];
280
+ return {
281
+ status: 'built',
282
+ result: await buildResult({
283
+ group,
284
+ proposals,
285
+ tokens
286
+ })
287
+ };
288
+ } catch (error) {
289
+ if (error instanceof RevokeProofError) return {
290
+ status: 'not-provable',
291
+ reason: error.reason
292
+ };
293
+ if (error instanceof LeafBindingError && error.reason === 'history-horizon') return {
294
+ status: 'not-provable',
295
+ reason: 'too-large'
296
+ };
297
+ throw error;
298
+ }
299
+ });
300
+ }
@@ -22,9 +22,13 @@ import { deriveGroup, mutexFor } from './group-handle.js';
22
22
  }
23
23
  };
24
24
  const enacted = ledgerEntries ?? [];
25
- const result = await commitWithEntries(group, [
26
- removeProposal
27
- ], enacted);
25
+ const result = await commitWithEntries({
26
+ group,
27
+ extraProposals: [
28
+ removeProposal
29
+ ],
30
+ enacted
31
+ });
28
32
  const newGroup = deriveGroup(group, result.newState);
29
33
  await newGroup.applyLedgerEntries(enacted);
30
34
  return {
@@ -1,7 +1,8 @@
1
1
  import { type OwnIdentity } from '@kokuin/token';
2
- import { type Welcome } from 'ts-mls';
3
- import type { MemberCredential } from './credential.js';
2
+ import { type ClientState, type Welcome } from 'ts-mls';
3
+ import { type ControllerBinding, type MemberCredential } from './credential.js';
4
4
  import { GroupHandle } from './group-handle.js';
5
+ import type { DeviceRegistry } from './registry.js';
5
6
  import type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
6
7
  export type ProcessWelcomeResult = {
7
8
  group: GroupHandle;
@@ -52,13 +53,21 @@ export type JoinGroupExternalParams = {
52
53
  credential: MemberCredential;
53
54
  /** Stale-recovery only: atomically removes prior leaf for same identity. */
54
55
  resync: true;
56
+ /** Authenticated recovery reply ledger, checked against the source GroupContext. */
57
+ ledgerEntries?: Array<string>;
58
+ controller?: ControllerBinding;
55
59
  options?: GroupOptions;
56
60
  authenticatedData?: Uint8Array;
61
+ /** @internal Judge the attestation before any replacement-binding checks. */
62
+ beforeBinding?: (pending: GroupHandle, source: GroupHandle) => Promise<void>;
57
63
  };
58
64
  export type JoinGroupExternalResult = {
59
65
  /** Framed MLSMessage(PublicMessage) bytes. Broadcast to existing members. */
60
66
  commitMessage: Uint8Array;
61
67
  /** New GroupHandle at post-commit epoch. */
62
68
  group: GroupHandle;
69
+ /** @internal Inputs from the source admission gate, without operational source secrets. */
70
+ sourceTree: ClientState['ratchetTree'];
71
+ sourceRegistry: DeviceRegistry;
63
72
  };
64
73
  export declare function joinGroupExternal(params: JoinGroupExternalParams): Promise<JoinGroupExternalResult>;
@@ -1,28 +1,22 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
- import { decode, encode, generateKeyPackageWithKey, joinGroup as mlsJoinGroup, joinGroupExternal as mlsJoinGroupExternal, mlsMessageDecoder, mlsMessageEncoder, protocolVersions, wireformats } from 'ts-mls';
2
+ import { contentTypes, decode, defaultCredentialTypes, defaultProposalTypes, encode, generateKeyPackageWithKey, isDefaultCredential, isDefaultProposal, joinGroup as mlsJoinGroup, joinGroupExternal as mlsJoinGroupExternal, mlsMessageDecoder, mlsMessageEncoder, nodeTypes, proposalOrRefTypes, protocolVersions, wireformats } from 'ts-mls';
3
+ import { decodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE } from './anchor.js';
4
+ import { verifyLeafCredential } from './authentication.js';
3
5
  import { sanitizeRatchetTree } from './codec.js';
6
+ import { parseMLSCredentialIdentity } from './credential.js';
7
+ import { LeafBindingError } from './errors.js';
4
8
  import { buildLeafCapabilities, resolveMlsContext } from './group-context.js';
5
- import { makeMLSCredential } from './group-credential.js';
6
- import { GroupHandle } from './group-handle.js';
9
+ import { assertBindingAuthorTime, makeMLSCredential } from './group-credential.js';
10
+ import { buildCommitPolicyContext, GroupHandle } from './group-handle.js';
7
11
  import { assertHeadMatches, computeHead, readLedgerHead } from './head.js';
8
12
  import { ledgerEntryDigest, verifyLedgerEntry } from './ledger.js';
13
+ import { prepareLifecycleGate, validateWelcomeTree } from './lifecycle.js';
9
14
  import { ROLE_ENTRY_TYPE } from './roster.js';
10
15
  export async function processWelcome(params) {
11
16
  const { identity, invite, welcome, keyPackageBundle, ratchetTree, options } = params;
12
17
  const context = await resolveMlsContext(options);
13
- // A Welcome is only this member's when the invite carries a role entry naming
14
- // them: an invite minted for someone else is not an invitation to join.
15
- const selfDID = normalizeDID(identity.id);
16
- let namesSelf = false;
17
- for (const token of invite.ledgerEntries){
18
- const verified = await verifyLedgerEntry(token);
19
- if (verified != null && verified.entry.type === ROLE_ENTRY_TYPE && verified.entry.groupID === invite.groupID && normalizeDID(verified.entry.subject) === selfDID) {
20
- namesSelf = true;
21
- break;
22
- }
23
- }
24
- if (!namesSelf) {
25
- throw new Error('processWelcome: the invite carries no role entry naming this identity');
18
+ if (normalizeDID(invite.recipientDID) !== normalizeDID(identity.id)) {
19
+ throw new Error('processWelcome: the invite recipient is not this identity');
26
20
  }
27
21
  let resolvedWelcome = welcome;
28
22
  if (welcome instanceof Uint8Array) {
@@ -42,6 +36,10 @@ export async function processWelcome(params) {
42
36
  ratchetTree: sanitizedTree
43
37
  }
44
38
  });
39
+ const joinedLeaf = state.ratchetTree[state.privatePath.leafIndex * 2];
40
+ if (joinedLeaf?.nodeType !== nodeTypes.leaf || !isDefaultCredential(joinedLeaf.leaf.credential) || joinedLeaf.leaf.credential.credentialType !== defaultCredentialTypes.basic || normalizeDID(parseMLSCredentialIdentity(joinedLeaf.leaf.credential.identity).id) !== normalizeDID(invite.recipientDID)) {
41
+ throw new Error('processWelcome: the joined leaf does not name the invite recipient');
42
+ }
45
43
  const credential = {
46
44
  id: identity.id,
47
45
  groupID: invite.groupID
@@ -66,7 +64,16 @@ export async function processWelcome(params) {
66
64
  // Fold the invite's entries: the roster is seeded from the anchor and the fold grants
67
65
  // authority only to an admin-so-far, so a member-signed entry cannot promote anyone
68
66
  // even though applyLedgerEntries itself is the permissive primitive.
67
+ if (group.anchor.controller == null) {
68
+ let namesSelf = false;
69
+ for (const token of invite.ledgerEntries){
70
+ const verified = await verifyLedgerEntry(token);
71
+ if (verified?.entry.type === ROLE_ENTRY_TYPE && verified.entry.groupID === invite.groupID && normalizeDID(verified.entry.subject) === normalizeDID(identity.id)) namesSelf = true;
72
+ }
73
+ if (!namesSelf) throw new Error('processWelcome: the invite carries no role entry naming this identity');
74
+ }
69
75
  await group.applyLedgerEntries(invite.ledgerEntries);
76
+ await validateWelcomeTree(group);
70
77
  return {
71
78
  group,
72
79
  credential
@@ -101,7 +108,7 @@ export async function processWelcome(params) {
101
108
  return result;
102
109
  }
103
110
  export async function joinGroupExternal(params) {
104
- const { identity, groupInfo: groupInfoBytes, credential, resync, options, authenticatedData } = params;
111
+ const { identity, groupInfo: groupInfoBytes, credential, resync, options, authenticatedData, controller, ledgerEntries } = params;
105
112
  // Resync replaces the caller's own prior leaf, so the rejoining identity must match
106
113
  // the presented credential. A friendly precheck, not the security boundary: on a
107
114
  // mismatch ts-mls rejects the external commit downstream anyway. Eviction
@@ -110,7 +117,6 @@ export async function joinGroupExternal(params) {
110
117
  if (normalizeDID(identity.id) !== normalizeDID(credential.id)) {
111
118
  throw new Error(`joinGroupExternal: identity.id (${identity.id}) must match credential.id (${credential.id}) for resync`);
112
119
  }
113
- const context = await resolveMlsContext(options);
114
120
  const message = decode(mlsMessageDecoder, groupInfoBytes);
115
121
  if (message == null) {
116
122
  throw new Error('Invalid groupInfo: failed to decode MLSMessage');
@@ -127,11 +133,36 @@ export async function joinGroupExternal(params) {
127
133
  if (offeredGroupID !== credential.groupID) {
128
134
  throw new Error(`joinGroupExternal: groupInfo names group ${offeredGroupID}, not credential.groupID (${credential.groupID})`);
129
135
  }
136
+ const anchorExtension = groupInfo.groupContext.extensions.find((extension)=>extension.extensionType === GROUP_ANCHOR_EXTENSION_TYPE);
137
+ const anchor = anchorExtension?.extensionData instanceof Uint8Array ? decodeGroupAnchor(anchorExtension.extensionData) : null;
138
+ if (anchor == null) throw new Error('joinGroupExternal: the group has no valid anchor');
139
+ const context = await resolveMlsContext(options, anchor);
140
+ const originalCredentials = [];
141
+ const joinContext = {
142
+ ...context,
143
+ authService: {
144
+ async validateCredential (leafCredential, signaturePublicKey) {
145
+ if (!isDefaultCredential(leafCredential) || leafCredential.credentialType !== defaultCredentialTypes.basic) return false;
146
+ const parsed = parseMLSCredentialIdentity(leafCredential.identity);
147
+ if (anchor.controller != null && parsed.controller == null) throw new LeafBindingError('floating-refused');
148
+ if (anchor.controller != null && parsed.controller != null && normalizeDID(parsed.controller.id) !== normalizeDID(anchor.controller)) throw new LeafBindingError('controller-mismatch');
149
+ await verifyLeafCredential(leafCredential, signaturePublicKey, {
150
+ leafLifetime: ()=>anchor.controller == null ? undefined : anchor.leafLifetime ?? 86_400,
151
+ trustedGrantLifetime: ()=>anchor.controller == null ? undefined : anchor.trustedGrantLifetime ?? 2_592_000
152
+ });
153
+ originalCredentials.push({
154
+ credential: leafCredential,
155
+ signaturePublicKey
156
+ });
157
+ return true;
158
+ }
159
+ }
160
+ };
130
161
  // The rejoining leaf must advertise every GroupContext extension the group uses, or
131
162
  // ts-mls rejects the external join. Derive them from the GroupInfo being resynced
132
163
  // against, honoring an explicit capabilities override.
133
164
  const keyPackage = await generateKeyPackageWithKey({
134
- credential: makeMLSCredential(identity),
165
+ credential: makeMLSCredential(identity, controller),
135
166
  signatureKeyPair: {
136
167
  signKey: identity.privateKey,
137
168
  publicKey: identity.publicKey
@@ -140,7 +171,7 @@ export async function joinGroupExternal(params) {
140
171
  capabilities: buildLeafCapabilities(groupInfo.groupContext.extensions, options?.capabilities)
141
172
  });
142
173
  const { publicMessage, newState } = await mlsJoinGroupExternal({
143
- context,
174
+ context: joinContext,
144
175
  groupInfo,
145
176
  keyPackage: keyPackage.publicPackage,
146
177
  privateKeys: keyPackage.privatePackage,
@@ -163,8 +194,69 @@ export async function joinGroupExternal(params) {
163
194
  resolveLedgerEntries: options?.resolveLedgerEntries,
164
195
  onLedgerEntries: options?.onLedgerEntries
165
196
  });
197
+ const ownIndex = newState.privatePath.leafIndex;
198
+ const own = newState.ratchetTree[ownIndex * 2];
199
+ const previous = originalCredentials.find(({ credential: candidate })=>isDefaultCredential(candidate) && candidate.credentialType === defaultCredentialTypes.basic && normalizeDID(parseMLSCredentialIdentity(candidate.identity).id) === normalizeDID(identity.id));
200
+ if (own?.nodeType !== nodeTypes.leaf || previous == null) throw new LeafBindingError('identity-change');
201
+ // Only the replaced leaf's credential and key affect the lifecycle predicates.
202
+ if (publicMessage.content.contentType !== contentTypes.commit) throw new Error('Expected external commit');
203
+ const proposals = publicMessage.content.commit.proposals.map((proposal)=>{
204
+ if (proposal.proposalOrRefType !== proposalOrRefTypes.proposal) throw new Error('Expected inline proposal');
205
+ return {
206
+ proposal: proposal.proposal,
207
+ senderLeafIndex: ownIndex
208
+ };
209
+ });
210
+ const removed = proposals.find(({ proposal })=>isDefaultProposal(proposal) && proposal.proposalType === defaultProposalTypes.remove)?.proposal;
211
+ if (removed == null || !isDefaultProposal(removed) || removed.proposalType !== defaultProposalTypes.remove) throw new Error('Missing replacement target');
212
+ const beforeTree = newState.ratchetTree.slice();
213
+ beforeTree[ownIndex * 2] = undefined;
214
+ beforeTree[removed.remove.removed * 2] = {
215
+ ...own,
216
+ leaf: {
217
+ ...own.leaf,
218
+ ...previous
219
+ }
220
+ };
221
+ const before = new GroupHandle({
222
+ state: {
223
+ ...newState,
224
+ ratchetTree: beforeTree,
225
+ groupContext: groupInfo.groupContext
226
+ },
227
+ credential,
228
+ context: await resolveMlsContext(options, anchor)
229
+ });
230
+ if (ledgerEntries != null) {
231
+ await before.bootstrapLedger(ledgerEntries);
232
+ await group.bootstrapLedger(ledgerEntries);
233
+ }
234
+ await params.beforeBinding?.(group, before);
235
+ if (anchor.controller != null && controller == null) throw new LeafBindingError('floating-refused');
236
+ assertBindingAuthorTime(controller);
237
+ const gate = await prepareLifecycleGate({
238
+ group: before,
239
+ entries: [],
240
+ candidateRegistry: before.registry,
241
+ context: buildCommitPolicyContext(before, {
242
+ baseRoster: before.roster,
243
+ candidateRoster: before.roster,
244
+ entryIDs: [],
245
+ enactedDeviceEntries: []
246
+ }),
247
+ externalLeaf: own.leaf
248
+ });
249
+ gate.check({
250
+ kind: 'commit',
251
+ senderLeafIndex: undefined,
252
+ proposals
253
+ });
254
+ await gate.postApply(newState);
255
+ await validateWelcomeTree(group);
166
256
  return {
167
257
  commitMessage,
168
- group
258
+ group,
259
+ sourceTree: beforeTree,
260
+ sourceRegistry: before.registry
169
261
  };
170
262
  }
package/lib/group.d.ts CHANGED
@@ -2,7 +2,8 @@ export { type CommitInviteResult, type CommitLedgerEntriesResult, type CreateInv
2
2
  export { type CreateGroupResult, createGroup, type RestoreGroupParams, restoreGroup, } from './group-create.js';
3
3
  export { createKeyPackageBundle, createLastResortKeyPackageBundle, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, } from './group-credential.js';
4
4
  export { addDevice, announceControllerBeacon, type DeviceWriteResult, labelDevice, registerDevice, revokeDevice, } from './group-device.js';
5
- export { CommitRejectedError, GroupHandle, type GroupHandleEvents, type GroupHandleParams, type HeldLedgerEntry, type LedgerLogEntry, } from './group-handle.js';
5
+ export { CommitRejectedError, GroupHandle, type GroupHandleEvents, type GroupHandleParams, type HeldLedgerEntry, type LedgerLogEntry, type SendAdmission, } from './group-handle.js';
6
6
  export { type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, type GroupInfoBinding, type InspectGroupInfoResult, inspectGroupInfo, readCommitEntryIDs, readGroupInfoBinding, readMessageAAD, readMessageEpoch, } from './group-info.js';
7
+ export { type RevokeBuildResult, removeLapsedLeaves, renewLeaf, revokeWithProof, } from './group-lifecycle.js';
7
8
  export { type RemoveMemberResult, removeMember } from './group-membership.js';
8
9
  export { type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, type ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, } from './group-welcome.js';
package/lib/group.js CHANGED
@@ -4,5 +4,6 @@ export { createKeyPackageBundle, createLastResortKeyPackageBundle, LAST_RESORT_E
4
4
  export { addDevice, announceControllerBeacon, labelDevice, registerDevice, revokeDevice } from './group-device.js';
5
5
  export { CommitRejectedError, GroupHandle } from './group-handle.js';
6
6
  export { exportGroupInfo, inspectGroupInfo, readCommitEntryIDs, readGroupInfoBinding, readMessageAAD, readMessageEpoch } from './group-info.js';
7
+ export { removeLapsedLeaves, renewLeaf, revokeWithProof } from './group-lifecycle.js';
7
8
  export { removeMember } from './group-membership.js';
8
9
  export { joinGroupExternal, processWelcome, processWelcomeOnce } from './group-welcome.js';
@@ -0,0 +1,6 @@
1
+ import { type ClientState } from 'ts-mls';
2
+ import type { VerifiedLedgerEntry } from './ledger.js';
3
+ export declare const HISTORY_HORIZON = 393216;
4
+ export declare function controllerLogSize(events: ReadonlyArray<unknown>): number;
5
+ /** Count validated controller history. Callers apply the horizon only to lifecycle groups. */
6
+ export declare function historySize(tree: ClientState['ratchetTree'], entries: ReadonlyArray<VerifiedLedgerEntry>): number;
package/lib/history.js ADDED
@@ -0,0 +1,26 @@
1
+ import { defaultCredentialTypes, isDefaultCredential, nodeTypes } from 'ts-mls';
2
+ import { parseMLSCredentialIdentity } from './credential.js';
3
+ import { DEVICE_ENTRY_TYPE } from './registry.js';
4
+ export const HISTORY_HORIZON = 393_216;
5
+ const utf8 = new TextEncoder();
6
+ export function controllerLogSize(events) {
7
+ return events.reduce((total, event)=>total + utf8.encode(JSON.stringify(event)).length, 0);
8
+ }
9
+ /** Count validated controller history. Callers apply the horizon only to lifecycle groups. */ export function historySize(tree, entries) {
10
+ let size = 0;
11
+ for (const node of tree){
12
+ if (node == null || node.nodeType !== nodeTypes.leaf) continue;
13
+ const credential = node.leaf.credential;
14
+ if (!isDefaultCredential(credential) || credential.credentialType !== defaultCredentialTypes.basic) continue;
15
+ const binding = parseMLSCredentialIdentity(credential.identity).controller;
16
+ if (binding != null) size += controllerLogSize(binding.prefix);
17
+ }
18
+ for (const { entry } of entries){
19
+ if (entry.type !== DEVICE_ENTRY_TYPE || entry.value == null || typeof entry.value !== 'object') {
20
+ continue;
21
+ }
22
+ const proof = entry.value.proof;
23
+ if (Array.isArray(proof)) size += controllerLogSize(proof);
24
+ }
25
+ return size;
26
+ }
package/lib/index.d.ts CHANGED
@@ -3,20 +3,26 @@ export type { Capabilities, GroupContextExtension, IncomingMessageCallback, KeyP
3
3
  export { defaultCapabilities, defaultProposalTypes, makeCustomExtension } from 'ts-mls';
4
4
  export { buildCurrentGroupAnchorExtension, buildGroupAnchorExtension, controlCapabilities, decodeGroupAnchor, encodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, type GroupAnchor, LEDGER_HEAD_EXTENSION_TYPE, readGroupAnchor, readGroupAnchorExtension, } from './anchor.js';
5
5
  export { createDIDAuthenticationService, MLS_DEVICES_ACT, MLS_DEVICES_RES, MLS_LEAF_ACT, MLS_LEAF_RES, verifyManagementCapability, } from './authentication.js';
6
+ export { type MintLeafCapabilityParams, type MintTrustedGrantParams, mintLeafCapability, mintTrustedGrant, } from './capability.js';
6
7
  export { type ClientState, decodeClientState, encodeClientState, sanitizeRatchetTree, } from './codec.js';
7
8
  export { type ControllerBinding, type GroupMember, type MemberCredential, type MLSCredentialIdentity, parseMLSCredentialIdentity, } from './credential.js';
8
9
  export { createNobleCryptoProvider, type NobleCryptoProviderOptions, nobleCryptoProvider, } from './crypto.js';
9
10
  export type { LeafBinding } from './device-proof.js';
10
11
  export { CONTROL_ENVELOPE_VERSION, type ControlEnvelope, type DecodeResult, decodeControlEnvelope, encodeControlEnvelope, } from './envelope.js';
11
- export { type EnvelopeFoldResult, foldEnvelope } from './envelope-fold.js';
12
+ export { type EnvelopeFoldResult, type FoldEnvelopeContext, type FoldEnvelopeParams, foldEnvelope, } from './envelope-fold.js';
13
+ export { LeafBindingError, type LeafBindingReason, LeafLapsedError, type LeafLapsedReason, RevokeProofError, type RevokeProofReason, } from './errors.js';
12
14
  export { type FoldDrop, type FoldInput, foldLedger, type LedgerReducer, } from './fold.js';
13
- export { addDevice, announceControllerBeacon, type CommitInviteResult, type CommitLedgerEntriesResult, CommitRejectedError, type CreateGroupResult, type CreateInviteParams, type CreateInviteResult, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, type DeviceWriteResult, type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, GroupHandle, type GroupHandleEvents, type GroupHandleParams, type HeldLedgerEntry, type InspectGroupInfoResult, InviteRecipientMismatchError, type InviteRecipientMismatchErrorParams, inspectGroupInfo, type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, type LedgerLogEntry, labelDevice, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, type ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, type RemoveMemberResult, type RestoreGroupParams, readCommitEntryIDs, readMessageAAD, readMessageEpoch, registerDevice, removeMember, restoreGroup, revokeDevice, } from './group.js';
15
+ export { addDevice, announceControllerBeacon, type CommitInviteResult, type CommitLedgerEntriesResult, CommitRejectedError, type CreateGroupResult, type CreateInviteParams, type CreateInviteResult, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, type DeviceWriteResult, type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, GroupHandle, type GroupHandleEvents, type GroupHandleParams, type HeldLedgerEntry, type InspectGroupInfoResult, InviteRecipientMismatchError, type InviteRecipientMismatchErrorParams, inspectGroupInfo, type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, type LedgerLogEntry, labelDevice, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, type ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, type RemoveMemberResult, type RestoreGroupParams, readCommitEntryIDs, readMessageAAD, readMessageEpoch, registerDevice, removeMember, restoreGroup, revokeDevice, type SendAdmission, } from './group.js';
16
+ export { type RemoveLapsedLeavesResult, type RevokeBuildResult, type RevokeWithProofParams, removeLapsedLeaves, renewLeaf, revokeWithProof, } from './group-lifecycle.js';
14
17
  export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, type LedgerHead, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension, } from './head.js';
18
+ export { HISTORY_HORIZON, historySize } from './history.js';
15
19
  export { decodeKeyPackage, decodePrivateKeyPackage, encodeKeyPackage, encodePrivateKeyPackage, keyPackageRef, } from './key-package-codec.js';
16
20
  export { type LedgerEntry, ledgerEntryDigest, signLedgerEntry, type VerifiedLedgerEntry, verifyLedgerEntry, } from './ledger.js';
21
+ export { type AssertRecoveryBindingParams, assertRecoveryBinding } from './lifecycle.js';
17
22
  export { type CommitPolicyContext, defaultCommitPolicy, MissingLedgerEntriesError, } from './policy.js';
18
- export { type CreateRecoveryRequestParams, type CreateRecoveryRequestResult, createRecoveryRequest, type OpenSealedGroupInfoParams, type OpenSealedLedgerParams, openSealedGroupInfo, openSealedLedger, RECOVERY_REQUEST_TYPE, type RecoveryRequest, RecoveryRequestError, type RecoveryRequestRejection, SEALED_GROUP_INFO_VERSION, SEALED_LEDGER_VERSION, SealedGroupInfoError, type SealedGroupInfoRejection, SealedLedgerError, type SealedLedgerRejection, type SealedReplyRejection, type SealGroupInfoParams, type SealLedgerParams, sealGroupInfo, sealLedger, type VerifiedRecoveryRequest, } from './recovery.js';
19
- export { authority, beaconOf, type ControllerBeacon, controllerOf, DEVICE_ENTRY_TYPE, type DeviceOp, type DeviceRecord, type DeviceRegistry, type DeviceValue, denySetOf, foldControl, registrySeed, } from './registry.js';
23
+ export { type CreateRecoveryRequestParams, type CreateRecoveryRequestResult, createRecoveryRequest, type OpenSealedGroupInfoParams, type OpenSealedLedgerParams, openRecoveryGroupInfo, openSealedGroupInfo, openSealedLedger, RECOVERY_REQUEST_TYPE, type RecoveryGroupInfo, type RecoveryRequest, RecoveryRequestError, type RecoveryRequestRejection, SEALED_GROUP_INFO_VERSION, SEALED_LEDGER_VERSION, SealedGroupInfoError, type SealedGroupInfoRejection, SealedLedgerError, type SealedLedgerRejection, type SealedReplyRejection, type SealGroupInfoParams, type SealLedgerParams, sealGroupInfo, sealLedger, type VerifiedRecoveryRequest, verifyRecoveryRequest, } from './recovery.js';
24
+ export { confirmationKey, confirmationTag, type OpenedRecoveryVerdict, openRecoveryVerdict, type RecoveryRefusalReason, type RecoverySignerEligibleParams, type RecoveryVerdict, recoverySignerEligible, type SealRecoveryVerdictParams, sealRecoveryVerdict, } from './recovery-verdict.js';
25
+ export { authority, beaconOf, type ControllerBeacon, type ControllerProjection, controllerOf, DEVICE_ENTRY_TYPE, type DeviceOp, type DeviceRecord, type DeviceRegistry, type DeviceValue, denySetOf, foldControl, type Revocation, type RevokedEffect, registrySeed, revocationOf, } from './registry.js';
20
26
  export { adminCount, foldRoster, type GroupPermission, ROLE_ENTRY_TYPE, type RoleValue, type RosterState, roleReducer, } from './roster.js';
21
27
  export type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
22
28
  export { welcomeKeyPackageRefs } from './welcome-refs.js';