@kumiai/mls 0.10.1 → 0.10.3

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.
@@ -1,6 +1,6 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
2
  import { EventEmitter } from '@sozai/event';
3
- import { contentTypes, createApplicationMessage, decode, encode, mlsExporter, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, wireformats } from 'ts-mls';
3
+ import { contentTypes, createApplicationMessage, createProposal, decode, defaultCredentialTypes, defaultProposalTypes, encode, isDefaultCredential, mlsExporter, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, wireformats } from 'ts-mls';
4
4
  import { readGroupAnchor } from './anchor.js';
5
5
  import { verifyLeafCredential } from './authentication.js';
6
6
  import { encodeClientState } from './codec.js';
@@ -8,15 +8,15 @@ import { didFromCredential, parseMLSCredentialIdentity } from './credential.js';
8
8
  import { verifyDeviceEntry } from './device-proof.js';
9
9
  import { decodeControlEnvelope } from './envelope.js';
10
10
  import { foldEnvelope, GROUP_TYPE_PREFIX } from './envelope-fold.js';
11
- import { LeafLapsedError, RevokeProofError } from './errors.js';
11
+ import { LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
12
12
  import { createMlsContext, deviceDenyHolderFor } from './group-context.js';
13
13
  import { readMessageEpoch } from './group-info.js';
14
14
  import { assertHeadMatches, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, headsMatch, readLedgerHead, readLedgerHeadExtension } from './head.js';
15
15
  import { ledgerEntryDigest, verifyLedgerEntry } from './ledger.js';
16
- import { assertSenderNotLapsed, isLapsed, leafAt, prepareLifecycleGate, rejectionReason } from './lifecycle.js';
16
+ import { assertSenderNotLapsed, isLapsed, isUnchangedLeaf, leafAt, prepareLifecycleGate, rejectionReason } from './lifecycle.js';
17
17
  import { createMutex } from './mutex.js';
18
18
  import { defaultCommitPolicy, MissingLedgerEntriesError } from './policy.js';
19
- import { beaconOf, controllerOf, DEVICE_ENTRY_TYPE, denySetOf, foldControl, isDeviceValue, revocationOf } from './registry.js';
19
+ import { beaconOf, controllerOf, DEVICE_ENTRY_TYPE, denySetOf, foldControl, isDeviceValue, mayReadmitResetDevice, revocationOf } from './registry.js';
20
20
  import { readSenderLeafIndex } from './sender-data.js';
21
21
  /** One serializer per live handle, so its state-mutating operations run one at a
22
22
  * time in issue order. Keyed weakly: the entry is collected with the handle, and
@@ -77,10 +77,12 @@ export function mutexFor(handle) {
77
77
  return (incoming)=>{
78
78
  const action = callback(incoming);
79
79
  if (incoming.kind === 'commit') {
80
+ const senderLeafIndex = incoming.senderLeafIndex == null ? undefined : Number(incoming.senderLeafIndex);
80
81
  capture.rejected = {
81
82
  proposals: incoming.proposals,
82
- senderLeafIndex: incoming.senderLeafIndex == null ? undefined : Number(incoming.senderLeafIndex)
83
+ senderLeafIndex
83
84
  };
85
+ capture.committerLeafIndex = senderLeafIndex;
84
86
  }
85
87
  return action;
86
88
  };
@@ -169,6 +171,33 @@ export function mutexFor(handle) {
169
171
  };
170
172
  }
171
173
  }
174
+ /** Project tree re-admissions from the full ledger fold, never a previous projection.
175
+ * A lapsed re-admitted leaf and a leaf inserted after expiry are indistinguishable here;
176
+ * a genuine expired post-reset package can activate a leaf for a Welcome joiner or an
177
+ * external rejoiner adopting a fork existing members reject. Ordinary commit admission
178
+ * still enforces expiry.
179
+ */ function registryWithTreeBindings(registry, tree) {
180
+ const devices = new Map(registry.devices);
181
+ for (const node of tree){
182
+ if (node?.nodeType !== nodeTypes.leaf || !isDefaultCredential(node.leaf.credential) || node.leaf.credential.credentialType !== defaultCredentialTypes.basic) continue;
183
+ const parsed = parseMLSCredentialIdentity(node.leaf.credential.identity);
184
+ if (!mayReadmitResetDevice(registry, parsed)) continue;
185
+ const did = normalizeDID(parsed.id);
186
+ const record = devices.get(did);
187
+ if (record == null) continue;
188
+ devices.set(did, {
189
+ controller: record.controller,
190
+ status: 'active',
191
+ ...record.label == null ? {} : {
192
+ label: record.label
193
+ }
194
+ });
195
+ }
196
+ return {
197
+ ...registry,
198
+ devices
199
+ };
200
+ }
172
201
  /**
173
202
  * Project a held ledger into BOTH the roster and the device registry in one ordered pass
174
203
  * (see {@link foldControl}), so a role entry's authority resolves against the registry-so-far.
@@ -224,11 +253,12 @@ export function mutexFor(handle) {
224
253
  ]));
225
254
  const folded = foldLedgerControl(this.#ledger, anchor, this.groupID);
226
255
  this.#roster = folded.roster;
227
- this.#registry = folded.registry;
256
+ this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree);
228
257
  // Authentication reads only this handle's registry and lifetime limits.
229
258
  const denyHolder = deviceDenyHolderFor(this.#context);
230
259
  if (denyHolder != null) {
231
260
  denyHolder.provider = ()=>this.currentDenySet();
261
+ denyHolder.registry = ()=>anchor.controller == null ? undefined : this.registry;
232
262
  denyHolder.leafLifetime = anchor.controller == null ? undefined : anchor.leafLifetime ?? 86_400;
233
263
  denyHolder.trustedGrantLifetime = anchor.controller == null ? undefined : anchor.trustedGrantLifetime ?? 2_592_000;
234
264
  }
@@ -422,7 +452,7 @@ export function mutexFor(handle) {
422
452
  }
423
453
  const folded = foldLedgerControl(this.#ledger, this.#anchor, this.groupID);
424
454
  this.#roster = folded.roster;
425
- this.#registry = folded.registry;
455
+ this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree);
426
456
  this.#admission = this.#computeAdmission();
427
457
  if (this.#pendingControlEvents != null) {
428
458
  this.emitControlEvents(appended.filter(({ entry })=>entry.type === DEVICE_ENTRY_TYPE));
@@ -534,7 +564,7 @@ export function mutexFor(handle) {
534
564
  }
535
565
  ]));
536
566
  this.#roster = folded.roster;
537
- this.#registry = folded.registry;
567
+ this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree);
538
568
  this.#admission = this.#computeAdmission();
539
569
  try {
540
570
  await opts?.persist?.(this);
@@ -667,6 +697,50 @@ export function mutexFor(handle) {
667
697
  return await mlsExporter(this.#state.keySchedule.exporterSecret, label, context, length, this.#context.cipherSuite);
668
698
  }
669
699
  /**
700
+ * Author and retain an authenticated self-removal proposal under the handle mutex.
701
+ * Once a member processes a pending self-removal, application encrypt throws until
702
+ * a commit lands. Callers should commit pending self-removals promptly.
703
+ */ async proposeSelfRemoval() {
704
+ return mutexFor(this).run(async ()=>{
705
+ const senderLeafIndex = this.#state.privatePath.leafIndex;
706
+ const proposal = {
707
+ proposalType: defaultProposalTypes.remove,
708
+ remove: {
709
+ removed: senderLeafIndex
710
+ }
711
+ };
712
+ const gate = await prepareLifecycleGate({
713
+ group: this,
714
+ entries: [],
715
+ candidateRegistry: this.#registry,
716
+ context: buildCommitPolicyContext(this, {
717
+ baseRoster: this.#roster,
718
+ candidateRoster: this.#roster,
719
+ entryIDs: [],
720
+ enactedDeviceEntries: []
721
+ })
722
+ });
723
+ gate.check({
724
+ kind: 'proposal',
725
+ proposal: {
726
+ proposal,
727
+ senderLeafIndex
728
+ }
729
+ });
730
+ const result = await createProposal({
731
+ context: this.#context,
732
+ state: this.#state,
733
+ proposal
734
+ });
735
+ this.#state = result.newState;
736
+ zeroAll(result.consumed);
737
+ return {
738
+ frame: encode(mlsMessageEncoder, result.message),
739
+ epoch: this.epoch
740
+ };
741
+ });
742
+ }
743
+ /**
670
744
  * Encrypt an application message for the group at this handle's current epoch,
671
745
  * returning framed wire bytes. A handle a commit has already superseded (see
672
746
  * {@link commitInvite}, {@link removeMember}, {@link commitLedgerEntries}) must not
@@ -951,6 +1025,7 @@ export function mutexFor(handle) {
951
1025
  precomputedReject = true;
952
1026
  capture.reason = rejectionReason(error);
953
1027
  if (error instanceof RevokeProofError) capture.proofError = error;
1028
+ if (error instanceof LeafBindingError) capture.bindingError = error;
954
1029
  }
955
1030
  const combined = (incoming)=>{
956
1031
  // A decode/fold failure is a hard reject even under a caller policy: the
@@ -964,6 +1039,7 @@ export function mutexFor(handle) {
964
1039
  } catch (error) {
965
1040
  capture.reason = rejectionReason(error);
966
1041
  if (error instanceof RevokeProofError) capture.proofError = error;
1042
+ if (error instanceof LeafBindingError) capture.bindingError = error;
967
1043
  return 'reject';
968
1044
  }
969
1045
  if (callerPolicy != null) return callerPolicy(incoming);
@@ -984,7 +1060,8 @@ export function mutexFor(handle) {
984
1060
  });
985
1061
  }
986
1062
  this.#roster = candidateRoster;
987
- this.#registry = candidateRegistry;
1063
+ const folded = foldLedgerControl(this.#ledger, this.#anchor, this.groupID);
1064
+ this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree);
988
1065
  this.#admission = this.#computeAdmission();
989
1066
  const emit = ()=>{
990
1067
  this.#notifyAccepted(surfaced, acceptedEntries.filter(({ verified })=>verified.entry.type === DEVICE_ENTRY_TYPE).map(({ verified })=>verified));
@@ -1075,7 +1152,10 @@ export function mutexFor(handle) {
1075
1152
  ...parsed.controller != null ? {
1076
1153
  controller: parsed.controller.id,
1077
1154
  prefix: parsed.controller.prefix,
1078
- capability: parsed.controller.capability
1155
+ capability: parsed.controller.capability,
1156
+ ...parsed.controller.holderGrant == null ? {} : {
1157
+ holderGrant: parsed.controller.holderGrant
1158
+ }
1079
1159
  } : {}
1080
1160
  };
1081
1161
  }
@@ -1184,6 +1264,7 @@ export function mutexFor(handle) {
1184
1264
  * Process a received MLS message (Commit, Proposal, or application). Accepts
1185
1265
  * wire-form bytes (preferred, e.g. from commitInvite/removeMember) or a pre-decoded
1186
1266
  * ts-mls framed message (legacy). The runtime `instanceof` selects the decode path.
1267
+ * A proposal from a past epoch is ignored (returns null, nothing persisted).
1187
1268
  * `persist` covers accepted commits and proposals, not application messages or their
1188
1269
  * receive ratchet. It runs under this handle's mutex and must not call back into it.
1189
1270
  * It must write atomically: rejection means nothing was stored. Host callbacks run
@@ -1198,6 +1279,11 @@ export function mutexFor(handle) {
1198
1279
  decoded = parsed;
1199
1280
  }
1200
1281
  return mutexFor(this).run(async ()=>{
1282
+ const privateProposal = readPrivateFrame(decoded, contentTypes.proposal);
1283
+ const frame = decoded;
1284
+ const proposalEpoch = privateProposal?.epoch ?? (frame.wireformat === wireformats.mls_public_message && frame.publicMessage.content.contentType === contentTypes.proposal ? frame.publicMessage.content.epoch : undefined);
1285
+ // Past proposals cannot be enacted at this epoch and need no ratchet or ledger work.
1286
+ if (proposalEpoch != null && proposalEpoch < this.epoch) return null;
1201
1287
  const { callback, capture, applyOnAccept, postApply } = await this.#prepareCommitPipeline(decoded, opts);
1202
1288
  const previousState = this.#state;
1203
1289
  const previousAdmission = this.#admission;
@@ -1222,12 +1308,21 @@ export function mutexFor(handle) {
1222
1308
  try {
1223
1309
  await verifyLeafCredential(credential, key, {
1224
1310
  deviceDenySet: ()=>this.currentDenySet(),
1311
+ deviceRegistry: ()=>this.#anchor.controller == null ? undefined : this.registry,
1312
+ // MLS re-validates the committer's path leaf after its proposals are judged:
1313
+ // an evidenced child keeps a denied issuer only with the credential it
1314
+ // already holds at that leaf.
1315
+ mayKeepDeniedIssuer: (leafCredential, leafKey)=>this.#anchor.controller != null && capture.committerLeafIndex != null && isUnchangedLeaf(this.#state.ratchetTree, capture.committerLeafIndex, {
1316
+ credential: leafCredential,
1317
+ signaturePublicKey: leafKey
1318
+ }),
1225
1319
  leafLifetime: ()=>this.#anchor.controller == null ? undefined : this.#anchor.leafLifetime ?? 86_400,
1226
1320
  trustedGrantLifetime: ()=>this.#anchor.controller == null ? undefined : this.#anchor.trustedGrantLifetime ?? 2_592_000
1227
1321
  });
1228
1322
  return true;
1229
1323
  } catch (error) {
1230
1324
  capture.reason = rejectionReason(error);
1325
+ if (error instanceof LeafBindingError) capture.bindingError = error;
1231
1326
  return false;
1232
1327
  }
1233
1328
  }
@@ -1242,13 +1337,14 @@ export function mutexFor(handle) {
1242
1337
  } catch (error) {
1243
1338
  if (application != null) throw error;
1244
1339
  const rejection = new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex, capture.reason ?? 'invalid');
1245
- rejection.cause = error;
1340
+ rejection.cause = capture.bindingError ?? error;
1246
1341
  if (error instanceof Error) rejection.message += `: ${error.message}`;
1247
1342
  throw rejection;
1248
1343
  }
1249
1344
  if (result.kind === 'newState' && result.actionTaken === 'reject') {
1250
1345
  const rejection = new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex, capture.reason ?? 'policy');
1251
- if (capture.proofError != null) rejection.cause = capture.proofError;
1346
+ const cause = capture.proofError ?? capture.bindingError;
1347
+ if (cause != null) rejection.cause = cause;
1252
1348
  throw rejection;
1253
1349
  }
1254
1350
  if (result.kind === 'newState') {
@@ -3,6 +3,23 @@ import { type ControllerBinding } from './credential.js';
3
3
  import { type RevokeProofReason } from './errors.js';
4
4
  import type { DeviceWriteResult } from './group-device.js';
5
5
  import { type GroupHandle } from './group-handle.js';
6
+ export type CommitResult = DeviceWriteResult;
7
+ /**
8
+ * Author a by-reference Remove for this handle's own leaf at its current epoch.
9
+ * Once a member processes a pending self-removal, application encrypt throws until
10
+ * a commit lands. Callers should commit pending self-removals promptly.
11
+ */
12
+ export declare function proposeSelfRemoval(group: GroupHandle): Promise<{
13
+ frame: Uint8Array;
14
+ epoch: bigint;
15
+ }>;
16
+ /**
17
+ * Commit other members' pending self-removals without absorbing other pending proposals.
18
+ * Returns null when only the committer's own self-removal (or none) is pending.
19
+ * Once a member processes a pending self-removal, application encrypt throws until
20
+ * a commit lands. Callers should commit pending self-removals promptly.
21
+ */
22
+ export declare function commitSelfRemovals(group: GroupHandle): Promise<CommitResult | null>;
6
23
  export type RevokeBuildResult = {
7
24
  status: 'built';
8
25
  result: DeviceWriteResult;
@@ -1,6 +1,6 @@
1
1
  import { didFromInception, foldLog } from '@kokuin/controller';
2
2
  import { createSigningIdentityForDID, normalizeDID } from '@kokuin/token';
3
- import { defaultProposalTypes, encode, mlsMessageEncoder, nodeTypes } from 'ts-mls';
3
+ import { defaultProposalTypes, encode, isDefaultProposal, mlsMessageEncoder, nodeTypes } from 'ts-mls';
4
4
  import { readCapability } from './capability.js';
5
5
  import { parseMLSCredentialIdentity } from './credential.js';
6
6
  import { LeafBindingError, RevokeProofError } from './errors.js';
@@ -10,8 +10,45 @@ import { deriveGroup, mutexFor } from './group-handle.js';
10
10
  import { HISTORY_HORIZON, historySize } from './history.js';
11
11
  import { signLedgerEntry } from './ledger.js';
12
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';
13
+ import { authenticateLifecycleProof, isExemptMember, verifyLifecycleProof } from './lifecycle-proof.js';
14
+ import { DEVICE_ENTRY_TYPE, isResetOnly } from './registry.js';
15
+ /**
16
+ * Author a by-reference Remove for this handle's own leaf at its current epoch.
17
+ * Once a member processes a pending self-removal, application encrypt throws until
18
+ * a commit lands. Callers should commit pending self-removals promptly.
19
+ */ export async function proposeSelfRemoval(group) {
20
+ return group.proposeSelfRemoval();
21
+ }
22
+ /**
23
+ * Commit other members' pending self-removals without absorbing other pending proposals.
24
+ * Returns null when only the committer's own self-removal (or none) is pending.
25
+ * Once a member processes a pending self-removal, application encrypt throws until
26
+ * a commit lands. Callers should commit pending self-removals promptly.
27
+ */ export async function commitSelfRemovals(group) {
28
+ return mutexFor(group).run(async ()=>{
29
+ const pendingProposals = Object.fromEntries(Object.entries(group.state.unappliedProposals).filter(([, { proposal, senderLeafIndex }])=>isDefaultProposal(proposal) && proposal.proposalType === defaultProposalTypes.remove && proposal.remove.removed === senderLeafIndex && senderLeafIndex !== group.state.privatePath.leafIndex));
30
+ if (Object.keys(pendingProposals).length === 0) return null;
31
+ const tree = group.state.ratchetTree.slice();
32
+ for (const { proposal } of Object.values(pendingProposals)){
33
+ if (isDefaultProposal(proposal) && proposal.proposalType === defaultProposalTypes.remove) tree[proposal.remove.removed * 2] = undefined;
34
+ }
35
+ const tokens = await clockEntries(group, tree);
36
+ const result = await commitWithEntries({
37
+ group,
38
+ extraProposals: [],
39
+ pendingProposals,
40
+ enacted: tokens,
41
+ requireAdmin: false
42
+ });
43
+ const newGroup = deriveGroup(group, result.newState);
44
+ await newGroup.applyLedgerEntries(tokens);
45
+ return {
46
+ commitMessage: encode(mlsMessageEncoder, result.commit),
47
+ newGroup,
48
+ epoch: newGroup.epoch
49
+ };
50
+ });
51
+ }
15
52
  function ownIdentity(group) {
16
53
  const leaf = leafAt(group.state.ratchetTree, group.state.privatePath.leafIndex);
17
54
  if (leaf == null || !('identity' in leaf.credential)) throw new LeafBindingError('identity-change');
@@ -192,12 +229,16 @@ export async function removeLapsedLeaves(group) {
192
229
  end = Math.max(headIndex, end);
193
230
  return advancing.slice(headIndex + 1, end + 1);
194
231
  }
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;
232
+ /**
233
+ * Revoked in the registry, with no leaf of its own and no leaf it issued left in the tree, apart
234
+ * from evidenced children, which its revocation never removes.
235
+ */ function isFullyRevoked(group, subject) {
236
+ const record = group.registry.devices.get(subject);
237
+ if (record?.status !== 'revoked' || isResetOnly(record)) return false;
197
238
  if (group.findMemberLeafIndex(subject) != null) return false;
198
239
  return !group.listMembers().some((member)=>{
199
240
  const capability = group.bindingOfDID(member.id)?.capability;
200
- return capability != null && normalizeDID(readCapability(capability).payload.iss) === subject;
241
+ return capability != null && normalizeDID(readCapability(capability).payload.iss) === subject && !isExemptMember(group, member.leafIndex);
201
242
  });
202
243
  }
203
244
  export async function revokeWithProof(group, params) {
@@ -242,7 +283,8 @@ export async function revokeWithProof(group, params) {
242
283
  return {
243
284
  ...member,
244
285
  issuer: payload?.cap == null ? undefined : normalizeDID(payload.iss),
245
- generation: folded?.ok ? folded.states.at(-1)?.gen : undefined
286
+ generation: folded?.ok ? folded.states.at(-1)?.gen : undefined,
287
+ exempt: isExemptMember(group, member.leafIndex)
246
288
  };
247
289
  });
248
290
  if (reset) for (const leaf of leaves){
@@ -252,7 +294,7 @@ export async function revokeWithProof(group, params) {
252
294
  }
253
295
  const direct = new Set(revoked.map(({ did })=>did));
254
296
  for (const leaf of leaves){
255
- if (leaf.issuer != null && direct.has(leaf.issuer) && !direct.has(normalizeDID(leaf.id))) revoked.push({
297
+ if (leaf.issuer != null && direct.has(leaf.issuer) && !direct.has(normalizeDID(leaf.id)) && !leaf.exempt) revoked.push({
256
298
  did: normalizeDID(leaf.id),
257
299
  cascadedFrom: leaf.issuer
258
300
  });
@@ -28,7 +28,15 @@ export async function processWelcome(params) {
28
28
  }
29
29
  const sanitizedTree = Array.isArray(ratchetTree) ? sanitizeRatchetTree(ratchetTree) : ratchetTree;
30
30
  const state = await mlsJoinGroup({
31
- context,
31
+ context: {
32
+ ...context,
33
+ authService: {
34
+ async validateCredential (credential, signaturePublicKey) {
35
+ await verifyLeafCredential(credential, signaturePublicKey);
36
+ return true;
37
+ }
38
+ }
39
+ },
32
40
  welcome: resolvedWelcome,
33
41
  keyPackage: keyPackageBundle.publicPackage,
34
42
  privateKeys: keyPackageBundle.privatePackage,
package/lib/index.d.ts CHANGED
@@ -5,7 +5,7 @@ export { buildCurrentGroupAnchorExtension, buildGroupAnchorExtension, controlCap
5
5
  export { createDIDAuthenticationService, MLS_DEVICES_ACT, MLS_DEVICES_RES, MLS_LEAF_ACT, MLS_LEAF_RES, verifyManagementCapability, } from './authentication.js';
6
6
  export { type MintLeafCapabilityParams, type MintTrustedGrantParams, mintLeafCapability, mintTrustedGrant, } from './capability.js';
7
7
  export { type ClientState, decodeClientState, encodeClientState, sanitizeRatchetTree, } from './codec.js';
8
- export { type ControllerBinding, type GroupMember, type MemberCredential, type MLSCredentialIdentity, parseMLSCredentialIdentity, } from './credential.js';
8
+ export { type ControllerBinding, didFromCredential, type GroupMember, type MemberCredential, type MLSCredentialIdentity, parseMLSCredentialIdentity, } from './credential.js';
9
9
  export { createNobleCryptoProvider, type NobleCryptoProviderOptions, nobleCryptoProvider, } from './crypto.js';
10
10
  export type { LeafBinding } from './device-proof.js';
11
11
  export { CONTROL_ENVELOPE_VERSION, type ControlEnvelope, type DecodeResult, decodeControlEnvelope, encodeControlEnvelope, } from './envelope.js';
@@ -13,7 +13,7 @@ export { type EnvelopeFoldResult, type FoldEnvelopeContext, type FoldEnvelopePar
13
13
  export { LeafBindingError, type LeafBindingReason, LeafLapsedError, type LeafLapsedReason, RevokeProofError, type RevokeProofReason, } from './errors.js';
14
14
  export { type FoldDrop, type FoldInput, foldLedger, type LedgerReducer, } from './fold.js';
15
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';
16
+ export { type CommitResult, commitSelfRemovals, proposeSelfRemoval, type RemoveLapsedLeavesResult, type RevokeBuildResult, type RevokeWithProofParams, removeLapsedLeaves, renewLeaf, revokeWithProof, } from './group-lifecycle.js';
17
17
  export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, type LedgerHead, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension, } from './head.js';
18
18
  export { HISTORY_HORIZON, historySize } from './history.js';
19
19
  export { decodeKeyPackage, decodePrivateKeyPackage, encodeKeyPackage, encodePrivateKeyPackage, keyPackageRef, } from './key-package-codec.js';
@@ -24,5 +24,6 @@ export { type CreateRecoveryRequestParams, type CreateRecoveryRequestResult, cre
24
24
  export { confirmationKey, confirmationTag, type OpenedRecoveryVerdict, openRecoveryVerdict, type RecoveryRefusalReason, type RecoverySignerEligibleParams, type RecoveryVerdict, recoverySignerEligible, type SealRecoveryVerdictParams, sealRecoveryVerdict, } from './recovery-verdict.js';
25
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';
26
26
  export { adminCount, foldRoster, type GroupPermission, ROLE_ENTRY_TYPE, type RoleValue, type RosterState, roleReducer, } from './roster.js';
27
+ export { mergeReceiveSecretTree } from './secret-tree.js';
27
28
  export type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
28
29
  export { welcomeKeyPackageRefs } from './welcome-refs.js';
package/lib/index.js CHANGED
@@ -3,14 +3,14 @@ export { buildCurrentGroupAnchorExtension, buildGroupAnchorExtension, controlCap
3
3
  export { createDIDAuthenticationService, MLS_DEVICES_ACT, MLS_DEVICES_RES, MLS_LEAF_ACT, MLS_LEAF_RES, verifyManagementCapability } from './authentication.js';
4
4
  export { mintLeafCapability, mintTrustedGrant } from './capability.js';
5
5
  export { decodeClientState, encodeClientState, sanitizeRatchetTree } from './codec.js';
6
- export { parseMLSCredentialIdentity } from './credential.js';
6
+ export { didFromCredential, parseMLSCredentialIdentity } from './credential.js';
7
7
  export { createNobleCryptoProvider, nobleCryptoProvider } from './crypto.js';
8
8
  export { CONTROL_ENVELOPE_VERSION, decodeControlEnvelope, encodeControlEnvelope } from './envelope.js';
9
9
  export { foldEnvelope } from './envelope-fold.js';
10
10
  export { LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
11
11
  export { foldLedger } from './fold.js';
12
12
  export { addDevice, announceControllerBeacon, CommitRejectedError, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, exportGroupInfo, GroupHandle, InviteRecipientMismatchError, inspectGroupInfo, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, labelDevice, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, processWelcome, processWelcomeOnce, readCommitEntryIDs, readMessageAAD, readMessageEpoch, registerDevice, removeMember, restoreGroup, revokeDevice } from './group.js';
13
- export { removeLapsedLeaves, renewLeaf, revokeWithProof } from './group-lifecycle.js';
13
+ export { commitSelfRemovals, proposeSelfRemoval, removeLapsedLeaves, renewLeaf, revokeWithProof } from './group-lifecycle.js';
14
14
  export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension } from './head.js';
15
15
  export { HISTORY_HORIZON, historySize } from './history.js';
16
16
  export { decodeKeyPackage, decodePrivateKeyPackage, encodeKeyPackage, encodePrivateKeyPackage, keyPackageRef } from './key-package-codec.js';
@@ -21,4 +21,5 @@ export { createRecoveryRequest, openRecoveryGroupInfo, openSealedGroupInfo, open
21
21
  export { confirmationKey, confirmationTag, openRecoveryVerdict, recoverySignerEligible, sealRecoveryVerdict } from './recovery-verdict.js';
22
22
  export { authority, beaconOf, controllerOf, DEVICE_ENTRY_TYPE, denySetOf, foldControl, registrySeed, revocationOf } from './registry.js';
23
23
  export { adminCount, foldRoster, ROLE_ENTRY_TYPE, roleReducer } from './roster.js';
24
+ export { mergeReceiveSecretTree } from './secret-tree.js';
24
25
  export { welcomeKeyPackageRefs } from './welcome-refs.js';
@@ -1,7 +1,8 @@
1
1
  import { type SignedEvent } from '@kokuin/controller';
2
+ import { type LeafNode } from 'ts-mls';
2
3
  import type { GroupHandle } from './group-handle.js';
3
4
  import type { VerifiedLedgerEntry } from './ledger.js';
4
- import type { DeviceRegistry, DeviceValue, RevokedEffect } from './registry.js';
5
+ import { type DeviceRegistry, type DeviceValue, type RevokedEffect } from './registry.js';
5
6
  export { controllerLogSize, HISTORY_HORIZON } from './history.js';
6
7
  /** Derived from a proof and the pre-commit tree; proposal comparison belongs to the commit gate. */
7
8
  export type LifecycleProofEffects = {
@@ -20,5 +21,13 @@ type AuthenticatedProof = {
20
21
  };
21
22
  /** Authenticate replayable log data without reading any membership state. */
22
23
  export declare function authenticateLifecycleProof(controllerID: string, verified: VerifiedLedgerEntry<DeviceValue>, registry: DeviceRegistry): AuthenticatedProof;
24
+ /**
25
+ * A leaf that stays when its issuer is denied: in a group whose anchor names a controller, a
26
+ * chained leaf of that controller carrying its holder's own valid grant from it, for a holder that
27
+ * is not denied. The cascade skips it and survivor checks keep it.
28
+ */
29
+ export declare function isEvidencedChild(group: GroupHandle, leaf: LeafNode, denied?: ReadonlySet<string>): boolean;
30
+ /** Whether the member at `leafIndex` is an evidenced child that a cascade leaves in place. */
31
+ export declare function isExemptMember(group: GroupHandle, leafIndex: number): boolean;
23
32
  /** Verify live effects while all leaves still describe the epoch before the commit. */
24
33
  export declare function verifyLifecycleProof(group: GroupHandle, verified: VerifiedLedgerEntry<DeviceValue>): Promise<LifecycleProofEffects>;
@@ -1,8 +1,12 @@
1
1
  import { didFromInception, foldLog } from '@kokuin/controller';
2
2
  import { normalizeDID } from '@kokuin/token';
3
+ import { defaultCredentialTypes, isDefaultCredential, nodeTypes } from 'ts-mls';
4
+ import { hasHolderEvidence } from './authentication.js';
3
5
  import { readCapability } from './capability.js';
6
+ import { parseMLSCredentialIdentity } from './credential.js';
4
7
  import { RevokeProofError } from './errors.js';
5
8
  import { controllerLogSize, HISTORY_HORIZON, historySize } from './history.js';
9
+ import { denySetOf, isResetOnly } from './registry.js';
6
10
  export { controllerLogSize, HISTORY_HORIZON } from './history.js';
7
11
  /** Authenticate replayable log data without reading any membership state. */ export function authenticateLifecycleProof(controllerID, verified, registry) {
8
12
  const controller = normalizeDID(controllerID);
@@ -99,6 +103,26 @@ export { controllerLogSize, HISTORY_HORIZON } from './history.js';
99
103
  }
100
104
  throw new RevokeProofError(belowFloor ? 'generation-floor' : 'no-rev');
101
105
  }
106
+ /**
107
+ * A leaf that stays when its issuer is denied: in a group whose anchor names a controller, a
108
+ * chained leaf of that controller carrying its holder's own valid grant from it, for a holder that
109
+ * is not denied. The cascade skips it and survivor checks keep it.
110
+ */ export function isEvidencedChild(group, leaf, denied = denySetOf(group.registry)) {
111
+ const controller = group.anchor.controller;
112
+ if (controller == null || !isDefaultCredential(leaf.credential) || leaf.credential.credentialType !== defaultCredentialTypes.basic) return false;
113
+ let parsed;
114
+ try {
115
+ parsed = parseMLSCredentialIdentity(leaf.credential.identity);
116
+ } catch {
117
+ return false;
118
+ }
119
+ if (parsed.controller == null || normalizeDID(parsed.controller.id) !== normalizeDID(controller)) return false;
120
+ return hasHolderEvidence(parsed, leaf.signaturePublicKey, denied, group.anchor.trustedGrantLifetime ?? 2_592_000);
121
+ }
122
+ /** Whether the member at `leafIndex` is an evidenced child that a cascade leaves in place. */ export function isExemptMember(group, leafIndex) {
123
+ const node = group.state.ratchetTree[leafIndex * 2];
124
+ return node?.nodeType === nodeTypes.leaf && isEvidencedChild(group, node.leaf);
125
+ }
102
126
  /** The entry must declare exactly the derived effects, in derivation order. */ function effectsMatch(declared, derived) {
103
127
  if (declared?.length !== derived.length) return false;
104
128
  return derived.every((effect, index)=>{
@@ -131,6 +155,7 @@ export { controllerLogSize, HISTORY_HORIZON } from './history.js';
131
155
  did: normalizeDID(member.id),
132
156
  leafIndex: member.leafIndex,
133
157
  issuer,
158
+ exempt: isExemptMember(group, member.leafIndex),
134
159
  generation: folded?.ok ? folded.states.at(-1)?.gen : undefined,
135
160
  attested: binding?.controller != null && normalizeDID(binding.controller) === controller ? attested : undefined,
136
161
  prefix: binding?.prefix ?? []
@@ -155,7 +180,8 @@ export { controllerLogSize, HISTORY_HORIZON } from './history.js';
155
180
  const authenticated = authenticateLifecycleProof(controller, verified, group.registry);
156
181
  const revoked = [];
157
182
  if (value.op === 'revoke') {
158
- if (group.registry.devices.get(subject)?.status === 'revoked') throw new RevokeProofError('effects-mismatch');
183
+ const record = group.registry.devices.get(subject);
184
+ if (record?.status === 'revoked' && !isResetOnly(record)) throw new RevokeProofError('effects-mismatch');
159
185
  revoked.push({
160
186
  did: subject
161
187
  });
@@ -170,7 +196,7 @@ export { controllerLogSize, HISTORY_HORIZON } from './history.js';
170
196
  }
171
197
  const direct = new Set(revoked.map(({ did })=>did));
172
198
  for (const leaf of leaves){
173
- if (leaf.issuer != null && direct.has(leaf.issuer) && !direct.has(leaf.did)) {
199
+ if (leaf.issuer != null && direct.has(leaf.issuer) && !direct.has(leaf.did) && !leaf.exempt) {
174
200
  revoked.push({
175
201
  did: leaf.did,
176
202
  cascadedFrom: leaf.issuer
@@ -11,6 +11,8 @@ export declare function leafAt(tree: ClientState['ratchetTree'], index: number):
11
11
  export declare function treeTime(group: GroupHandle, controllerID: string): number;
12
12
  export declare function isLapsed(group: GroupHandle, leaf: LeafNode): boolean;
13
13
  export declare function validateEntry(group: GroupHandle, leaf: LeafNode, previous?: LeafNode): Promise<void>;
14
+ /** The same credential and key a tree already holds at that leaf index. */
15
+ export declare function isUnchangedLeaf(tree: ClientState['ratchetTree'], index: number, leaf: Pick<LeafNode, 'credential' | 'signaturePublicKey'>): boolean;
14
16
  export declare function validateWelcomeTree(group: GroupHandle): Promise<void>;
15
17
  type IncomingMessage = Parameters<IncomingMessageCallback>[0];
16
18
  export type PrepareLifecycleGateParams = {