@kumiai/mls 0.10.1 → 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.
@@ -1,5 +1,6 @@
1
1
  import { type SignedEvent } from '@kokuin/controller';
2
2
  import type { AuthenticationService, Credential } from 'ts-mls';
3
+ import { type MLSCredentialIdentity } from './credential.js';
3
4
  export { MLS_LEAF_ACT, MLS_LEAF_RES } from './capability.js';
4
5
  /** The action a management capability must grant to mutate a profile's device registry. */
5
6
  export declare const MLS_DEVICES_ACT = "manage";
@@ -9,7 +10,21 @@ export type DIDAuthenticationDependencies = {
9
10
  deviceDenySet?: () => ReadonlySet<string>;
10
11
  leafLifetime?: () => number | undefined;
11
12
  trustedGrantLifetime?: () => number | undefined;
13
+ /**
14
+ * Whether this leaf may keep an issuer the deny set names, on its holder evidence. The caller
15
+ * answers for the group (its anchor names a controller) and for the leaf (it is the credential
16
+ * already in the tree at that index, or it arrives in a Welcome tree). Absent: never.
17
+ */
18
+ mayKeepDeniedIssuer?: (credential: Credential, signaturePublicKey: Uint8Array) => boolean;
12
19
  };
20
+ /** Structural evidence gate also used before MLS invokes its boolean authentication adapter. */
21
+ export declare function checkHolderEvidence(parsed: MLSCredentialIdentity, signaturePublicKey: Uint8Array, trustedGrantLifetime?: number): string | undefined;
22
+ /**
23
+ * A chained leaf carrying its holder's own valid controller grant, for a holder the deny set does
24
+ * not name. Such a leaf names a device the controller bound itself, so denying the device that
25
+ * issued its capability does not take that binding away.
26
+ */
27
+ export declare function hasHolderEvidence(parsed: MLSCredentialIdentity, signaturePublicKey: Uint8Array, denied: ReadonlySet<string>, trustedGrantLifetime?: number): boolean;
13
28
  /** Internal throwing boundary for entry gates; ts-mls consumes the boolean adapter below. */
14
29
  export declare function verifyLeafCredential(credential: Credential, signaturePublicKey: Uint8Array, deps?: DIDAuthenticationDependencies): Promise<void>;
15
30
  /** Management grants are direct controller grants, verified at their issuance time. */
@@ -76,8 +76,9 @@ function isDenied(denied, did) {
76
76
  }
77
77
  const token = readCapability(params.capability);
78
78
  const payload = token.payload;
79
- const leafLifetime = Math.min(params.leafLifetime ?? MAX_LEAF_LIFETIME, MAX_LEAF_LIFETIME);
80
- assertCapabilityLifetime(payload, leafLifetime);
79
+ const ceiling = params.trustedGrant ? MAX_TRUSTED_GRANT_LIFETIME : MAX_LEAF_LIFETIME;
80
+ const lifetime = params.trustedGrant ? params.trustedGrantLifetime : params.leafLifetime;
81
+ assertCapabilityLifetime(payload, Math.min(lifetime ?? ceiling, ceiling));
81
82
  if (normalizeDID(payload.sub) !== normalizeDID(params.controllerID)) {
82
83
  throw new LeafBindingError('subject-mismatch');
83
84
  }
@@ -152,6 +153,47 @@ function isDenied(denied, did) {
152
153
  maxDepth: 1
153
154
  });
154
155
  }
156
+ function withoutIssuer(denied, capability) {
157
+ const issuer = normalizeDID(readCapability(capability).payload.iss);
158
+ return new Set([
159
+ ...denied
160
+ ].filter((did)=>normalizeDID(did) !== issuer));
161
+ }
162
+ /** Structural evidence gate also used before MLS invokes its boolean authentication adapter. */ export function checkHolderEvidence(parsed, signaturePublicKey, trustedGrantLifetime = MAX_TRUSTED_GRANT_LIFETIME) {
163
+ const binding = parsed.controller;
164
+ if (binding == null) return;
165
+ const leafPayload = readCapability(binding.capability).payload;
166
+ if (leafPayload.cap === undefined) return;
167
+ if (binding.holderGrant == null) throw new LeafBindingError('missing-holder-evidence');
168
+ try {
169
+ const grant = readCapability(binding.holderGrant).payload;
170
+ assertControllerGrant(grant, binding.id);
171
+ assertCapabilityLifetime(grant, Math.min(trustedGrantLifetime, MAX_TRUSTED_GRANT_LIFETIME));
172
+ if (grant.cap !== undefined || grant.iat > leafPayload.iat || grant.exp <= leafPayload.iat || grant.nbf != null && grant.nbf > leafPayload.iat || normalizeDID(grant.aud) !== normalizeDID(parsed.id) || !constantTimeEqual(capabilityKey(grant).publicKey, signaturePublicKey) || !hasPermission({
173
+ act: MLS_LEAF_ACT,
174
+ res: MLS_LEAF_RES
175
+ }, grant)) throw new LeafBindingError('holder-evidence-mismatch');
176
+ } catch (cause) {
177
+ const error = new LeafBindingError('holder-evidence-mismatch');
178
+ error.cause = cause;
179
+ throw error;
180
+ }
181
+ return binding.holderGrant;
182
+ }
183
+ /**
184
+ * A chained leaf carrying its holder's own valid controller grant, for a holder the deny set does
185
+ * not name. Such a leaf names a device the controller bound itself, so denying the device that
186
+ * issued its capability does not take that binding away.
187
+ */ export function hasHolderEvidence(parsed, signaturePublicKey, denied, trustedGrantLifetime) {
188
+ const binding = parsed.controller;
189
+ if (binding == null || isDenied(denied, parsed.id)) return false;
190
+ try {
191
+ if (readCapability(binding.capability).payload.cap === undefined) return false;
192
+ return checkHolderEvidence(parsed, signaturePublicKey, trustedGrantLifetime) != null;
193
+ } catch {
194
+ return false;
195
+ }
196
+ }
155
197
  /** Internal throwing boundary for entry gates; ts-mls consumes the boolean adapter below. */ export async function verifyLeafCredential(credential, signaturePublicKey, deps = {}) {
156
198
  if (credential.credentialType !== defaultCredentialTypes.basic) {
157
199
  throw new Error('Unsupported MLS credential type');
@@ -162,6 +204,8 @@ function isDenied(denied, did) {
162
204
  if (isDenied(denySet, parsed.id)) throw new LeafBindingError('denied-id');
163
205
  if (parsed.controller == null) return;
164
206
  try {
207
+ // The holder grant below is still verified against the full deny set.
208
+ const leafDenySet = deps.mayKeepDeniedIssuer?.(credential, signaturePublicKey) && hasHolderEvidence(parsed, signaturePublicKey, denySet, deps.trustedGrantLifetime?.()) ? withoutIssuer(denySet, parsed.controller.capability) : denySet;
165
209
  await verifyPinnedCapability({
166
210
  capability: parsed.controller.capability,
167
211
  prefix: parsed.controller.prefix,
@@ -172,10 +216,34 @@ function isDenied(denied, did) {
172
216
  res: MLS_LEAF_RES
173
217
  },
174
218
  leafKey: signaturePublicKey,
175
- denySet,
219
+ denySet: leafDenySet,
176
220
  leafLifetime: deps.leafLifetime?.(),
177
221
  trustedGrantLifetime: deps.trustedGrantLifetime?.()
178
222
  });
223
+ const holderGrant = checkHolderEvidence(parsed, signaturePublicKey, deps.trustedGrantLifetime?.());
224
+ if (holderGrant != null) {
225
+ try {
226
+ await verifyPinnedCapability({
227
+ capability: holderGrant,
228
+ prefix: parsed.controller.prefix,
229
+ controllerID: parsed.controller.id,
230
+ audience: parsed.id,
231
+ permission: {
232
+ act: MLS_LEAF_ACT,
233
+ res: MLS_LEAF_RES
234
+ },
235
+ leafKey: signaturePublicKey,
236
+ denySet,
237
+ trustedGrantLifetime: deps.trustedGrantLifetime?.(),
238
+ directOnly: true,
239
+ trustedGrant: true
240
+ });
241
+ } catch (cause) {
242
+ const error = new LeafBindingError('holder-evidence-mismatch');
243
+ error.cause = cause;
244
+ throw error;
245
+ }
246
+ }
179
247
  } catch (error) {
180
248
  if (error instanceof LeafBindingError) throw error;
181
249
  const rejection = new LeafBindingError('signature-invalid');
@@ -33,6 +33,8 @@ export type ControllerBinding = {
33
33
  id: string;
34
34
  prefix: Array<SignedEvent>;
35
35
  capability: string;
36
+ /** The leaf holder's direct controller grant, required for chained capabilities. */
37
+ holderGrant?: string;
36
38
  };
37
39
  export type MLSCredentialIdentity = {
38
40
  v?: 1;
@@ -63,21 +65,19 @@ export type GroupMember = {
63
65
  };
64
66
  export declare function parseMLSCredentialIdentity(identity: Uint8Array): MLSCredentialIdentity;
65
67
  /**
66
- * The normalized DID an MLS leaf credential names, or `undefined` when it names none.
68
+ * The normalized DID an MLS leaf credential names, or `null` when it names none.
67
69
  *
68
70
  * Total by contract. The receive-side commit policy calls this on a leaf inside an untrusted
69
71
  * commit, and `defaultCommitPolicy` is pure and total — a malformed credential must read as
70
72
  * "no DID", never throw past the policy boundary. Every rejection `parseMLSCredentialIdentity`
71
- * raises collapses to `undefined` here: non-JSON bytes, a non-object value, an unsupported `v`, a
73
+ * raises collapses to `null` here: non-JSON bytes, a non-object value, an unsupported `v`, a
72
74
  * non-string `id`, a non-string `longForm`.
73
75
  *
74
76
  * `credentialType !== basic` does not narrow on its own: `CredentialCustom.credentialType` is a
75
77
  * bare `number`, so the compiler cannot rule it out. ts-mls's own guard can.
76
78
  *
77
- * Syntax is not validated. An identity naming an arbitrary string returns that string, which no
79
+ * An empty `id` names no DID and returns `null`.
80
+ * Syntax is not validated. An identity naming an arbitrary non-empty string returns that string, which no
78
81
  * roster grants — a lookup miss, and deliberately distinct from a credential that names nothing.
79
- *
80
- * Not re-exported from the package index: `policy.ts` is the only consumer today, and widening the
81
- * surface is cheap to do later and impossible to undo.
82
82
  */
83
- export declare function didFromCredential(credential: Credential): string | undefined;
83
+ export declare function didFromCredential(credential: Credential): string | null;
package/lib/credential.js CHANGED
@@ -50,40 +50,45 @@ export function parseMLSCredentialIdentity(identity) {
50
50
  if (!Array.isArray(cc.prefix)) {
51
51
  throw new Error('Invalid MLS credential: controller.prefix must be an array');
52
52
  }
53
+ if ('holderGrant' in cc && typeof cc.holderGrant !== 'string') {
54
+ throw new Error('Invalid MLS credential: controller.holderGrant must be a string');
55
+ }
53
56
  // Structural only — the prefix events are validated cryptographically by the fold in
54
57
  // validateCredential, never here (parse stays pure/structural, like longForm).
55
58
  result.controller = {
56
59
  id: cc.id,
57
60
  prefix: cc.prefix,
58
- capability: cc.capability
61
+ capability: cc.capability,
62
+ ...typeof cc.holderGrant === 'string' ? {
63
+ holderGrant: cc.holderGrant
64
+ } : {}
59
65
  };
60
66
  }
61
67
  return result;
62
68
  }
63
69
  /**
64
- * The normalized DID an MLS leaf credential names, or `undefined` when it names none.
70
+ * The normalized DID an MLS leaf credential names, or `null` when it names none.
65
71
  *
66
72
  * Total by contract. The receive-side commit policy calls this on a leaf inside an untrusted
67
73
  * commit, and `defaultCommitPolicy` is pure and total — a malformed credential must read as
68
74
  * "no DID", never throw past the policy boundary. Every rejection `parseMLSCredentialIdentity`
69
- * raises collapses to `undefined` here: non-JSON bytes, a non-object value, an unsupported `v`, a
75
+ * raises collapses to `null` here: non-JSON bytes, a non-object value, an unsupported `v`, a
70
76
  * non-string `id`, a non-string `longForm`.
71
77
  *
72
78
  * `credentialType !== basic` does not narrow on its own: `CredentialCustom.credentialType` is a
73
79
  * bare `number`, so the compiler cannot rule it out. ts-mls's own guard can.
74
80
  *
75
- * Syntax is not validated. An identity naming an arbitrary string returns that string, which no
81
+ * An empty `id` names no DID and returns `null`.
82
+ * Syntax is not validated. An identity naming an arbitrary non-empty string returns that string, which no
76
83
  * roster grants — a lookup miss, and deliberately distinct from a credential that names nothing.
77
- *
78
- * Not re-exported from the package index: `policy.ts` is the only consumer today, and widening the
79
- * surface is cheap to do later and impossible to undo.
80
84
  */ export function didFromCredential(credential) {
81
85
  if (!isDefaultCredential(credential) || credential.credentialType !== defaultCredentialTypes.basic) {
82
- return undefined;
86
+ return null;
83
87
  }
84
88
  try {
85
- return normalizeDID(parseMLSCredentialIdentity(credential.identity).id);
89
+ const id = parseMLSCredentialIdentity(credential.identity).id;
90
+ return id === '' ? null : normalizeDID(id);
86
91
  } catch {
87
- return undefined;
92
+ return null;
88
93
  }
89
94
  }
@@ -8,6 +8,7 @@ export type LeafBinding = {
8
8
  /** The embedded controller log prefix (present iff bound), for resolving a capability signature. */
9
9
  prefix?: Array<SignedEvent>;
10
10
  capability?: string;
11
+ holderGrant?: string;
11
12
  /** The leaf's MLS signature public key. */
12
13
  leafKey: Uint8Array;
13
14
  };
package/lib/errors.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type LeafBindingReason = 'issuer-mismatch' | 'audience-mismatch' | 'permission-denied' | 'signature-invalid' | 'confirmation-invalid' | 'subject-mismatch' | 'chain-depth' | 'self-issued' | 'child-outlives-parent' | 'denied-issuer' | 'denied-id' | 'renewal-order' | 'lifetime-cap' | 'generation-floor' | 'identity-change' | 'controller-mismatch' | 'floating-refused' | 'history-horizon';
1
+ export type LeafBindingReason = 'missing-holder-evidence' | 'holder-evidence-mismatch' | 'issuer-mismatch' | 'audience-mismatch' | 'permission-denied' | 'signature-invalid' | 'confirmation-invalid' | 'subject-mismatch' | 'chain-depth' | 'self-issued' | 'child-outlives-parent' | 'denied-issuer' | 'denied-id' | 'renewal-order' | 'lifetime-cap' | 'generation-floor' | 'identity-change' | 'controller-mismatch' | 'floating-refused' | 'history-horizon';
2
2
  export declare class LeafBindingError extends Error {
3
3
  #private;
4
4
  constructor(reason: LeafBindingReason);
@@ -1,5 +1,5 @@
1
1
  import { type SigningIdentity } from '@kokuin/token';
2
- import { type ClientState, createCommit, type DefaultProposal, type KeyPackage } from 'ts-mls';
2
+ import { type ClientState, createCommit, type DefaultProposal, type KeyPackage, type UnappliedProposals } from 'ts-mls';
3
3
  import { type GroupHandle } from './group-handle.js';
4
4
  import { type GroupPermission } from './roster.js';
5
5
  import type { Invite } from './types.js';
@@ -37,6 +37,8 @@ export declare function createInvite(params: CreateInviteParams): Promise<Create
37
37
  export type CommitWithEntriesParams = {
38
38
  group: GroupHandle;
39
39
  extraProposals: Array<DefaultProposal>;
40
+ /** Pending proposals to commit by reference, retaining their authenticated senders. */
41
+ pendingProposals?: UnappliedProposals;
40
42
  enacted: Array<string>;
41
43
  ratchetTreeExtension?: boolean;
42
44
  /** Defaults to true; device and lifecycle entries carry their own authority. */
@@ -6,10 +6,10 @@ import { verifyDeviceEntry } from './device-proof.js';
6
6
  import { encodeControlEnvelope } from './envelope.js';
7
7
  import { foldEnvelope } from './envelope-fold.js';
8
8
  import { assertBindingAuthorTime } from './group-credential.js';
9
- import { buildCommitPolicyContext, deriveGroup, mutexFor } from './group-handle.js';
9
+ import { buildCommitPolicyContext, CommitRejectedError, deriveGroup, mutexFor } from './group-handle.js';
10
10
  import { buildLedgerHeadExtension, extendHead, readLedgerHead } from './head.js';
11
11
  import { ledgerEntryDigest, signLedgerEntry, verifyLedgerEntry } from './ledger.js';
12
- import { prepareLifecycleGate, validateEntry } from './lifecycle.js';
12
+ import { prepareLifecycleGate, rejectionReason, validateEntry } from './lifecycle.js';
13
13
  import { authority, controllerOf, DEVICE_ENTRY_TYPE } from './registry.js';
14
14
  import { ROLE_ENTRY_TYPE } from './roster.js';
15
15
  /** The supplied key package names a different identity from the invite's recipient. */ export class InviteRecipientMismatchError extends Error {
@@ -178,7 +178,7 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
178
178
  });
179
179
  const commitState = {
180
180
  ...params.commitState ?? group.state,
181
- unappliedProposals: {}
181
+ unappliedProposals: params.pendingProposals ?? {}
182
182
  };
183
183
  const proposals = [
184
184
  ...extraProposals
@@ -200,12 +200,22 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
200
200
  const incoming = {
201
201
  kind: 'commit',
202
202
  senderLeafIndex: group.state.privatePath.leafIndex,
203
- proposals: proposals.map((proposal)=>({
204
- proposal,
205
- senderLeafIndex: group.state.privatePath.leafIndex
206
- }))
203
+ proposals: [
204
+ ...Object.values(commitState.unappliedProposals),
205
+ ...proposals.map((proposal)=>({
206
+ proposal,
207
+ senderLeafIndex: group.state.privatePath.leafIndex
208
+ }))
209
+ ]
207
210
  };
208
- gate.check(incoming);
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
+ }
209
219
  for (const proposal of proposals){
210
220
  if (proposal.proposalType === defaultProposalTypes.add) {
211
221
  const leaf = proposal.add.keyPackage.leafNode;
@@ -331,16 +341,16 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
331
341
  // `credentialType !== basic` does not narrow on its own: CredentialCustom.credentialType is a
332
342
  // bare `number`, so the compiler cannot rule it out. ts-mls's own guard can.
333
343
  //
334
- // This inlines the same credential->DID chain `didFromCredential` (credential.ts) implements
335
- // for the receive-side policy, kept separate deliberately: this path needs to distinguish a
336
- // non-basic credential from a malformed-JSON failure for its error messages, and that helper
337
- // is deliberately unexported. The two must stay in agreement — if they diverge, the committer
338
- // 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.
339
347
  const credential = keyPackage.leafNode.credential;
340
348
  if (!isDefaultCredential(credential) || credential.credentialType !== defaultCredentialTypes.basic) {
341
349
  throw new Error('commitInvite: the key package carries a non-basic credential, which names no DID to bind');
342
350
  }
343
- 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);
344
354
  if (actualDID !== expectedDID) {
345
355
  throw new InviteRecipientMismatchError({
346
356
  groupID: group.groupID,
@@ -256,6 +256,15 @@ export declare class GroupHandle {
256
256
  * consequences of this method's plainness; wrapping it "for consistency" breaks both.
257
257
  */
258
258
  exportSecret(label: string, context: Uint8Array, length?: number): Promise<Uint8Array>;
259
+ /**
260
+ * Author and retain an authenticated self-removal proposal under the handle mutex.
261
+ * Once a member processes a pending self-removal, application encrypt throws until
262
+ * a commit lands. Callers should commit pending self-removals promptly.
263
+ */
264
+ proposeSelfRemoval(): Promise<{
265
+ frame: Uint8Array;
266
+ epoch: bigint;
267
+ }>;
259
268
  /**
260
269
  * Encrypt an application message for the group at this handle's current epoch,
261
270
  * returning framed wire bytes. A handle a commit has already superseded (see
@@ -371,6 +380,7 @@ export declare class GroupHandle {
371
380
  * Process a received MLS message (Commit, Proposal, or application). Accepts
372
381
  * wire-form bytes (preferred, e.g. from commitInvite/removeMember) or a pre-decoded
373
382
  * ts-mls framed message (legacy). The runtime `instanceof` selects the decode path.
383
+ * A proposal from a past epoch is ignored (returns null, nothing persisted).
374
384
  * `persist` covers accepted commits and proposals, not application messages or their
375
385
  * receive ratchet. It runs under this handle's mutex and must not call back into it.
376
386
  * It must write atomically: rejection means nothing was stored. Host callbacks run
@@ -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, defaultProposalTypes, encode, 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,12 +8,12 @@ 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
19
  import { beaconOf, controllerOf, DEVICE_ENTRY_TYPE, denySetOf, foldControl, isDeviceValue, revocationOf } from './registry.js';
@@ -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
  };
@@ -667,6 +669,50 @@ export function mutexFor(handle) {
667
669
  return await mlsExporter(this.#state.keySchedule.exporterSecret, label, context, length, this.#context.cipherSuite);
668
670
  }
669
671
  /**
672
+ * Author and retain an authenticated self-removal proposal under the handle mutex.
673
+ * Once a member processes a pending self-removal, application encrypt throws until
674
+ * a commit lands. Callers should commit pending self-removals promptly.
675
+ */ async proposeSelfRemoval() {
676
+ return mutexFor(this).run(async ()=>{
677
+ const senderLeafIndex = this.#state.privatePath.leafIndex;
678
+ const proposal = {
679
+ proposalType: defaultProposalTypes.remove,
680
+ remove: {
681
+ removed: senderLeafIndex
682
+ }
683
+ };
684
+ const gate = await prepareLifecycleGate({
685
+ group: this,
686
+ entries: [],
687
+ candidateRegistry: this.#registry,
688
+ context: buildCommitPolicyContext(this, {
689
+ baseRoster: this.#roster,
690
+ candidateRoster: this.#roster,
691
+ entryIDs: [],
692
+ enactedDeviceEntries: []
693
+ })
694
+ });
695
+ gate.check({
696
+ kind: 'proposal',
697
+ proposal: {
698
+ proposal,
699
+ senderLeafIndex
700
+ }
701
+ });
702
+ const result = await createProposal({
703
+ context: this.#context,
704
+ state: this.#state,
705
+ proposal
706
+ });
707
+ this.#state = result.newState;
708
+ zeroAll(result.consumed);
709
+ return {
710
+ frame: encode(mlsMessageEncoder, result.message),
711
+ epoch: this.epoch
712
+ };
713
+ });
714
+ }
715
+ /**
670
716
  * Encrypt an application message for the group at this handle's current epoch,
671
717
  * returning framed wire bytes. A handle a commit has already superseded (see
672
718
  * {@link commitInvite}, {@link removeMember}, {@link commitLedgerEntries}) must not
@@ -951,6 +997,7 @@ export function mutexFor(handle) {
951
997
  precomputedReject = true;
952
998
  capture.reason = rejectionReason(error);
953
999
  if (error instanceof RevokeProofError) capture.proofError = error;
1000
+ if (error instanceof LeafBindingError) capture.bindingError = error;
954
1001
  }
955
1002
  const combined = (incoming)=>{
956
1003
  // A decode/fold failure is a hard reject even under a caller policy: the
@@ -964,6 +1011,7 @@ export function mutexFor(handle) {
964
1011
  } catch (error) {
965
1012
  capture.reason = rejectionReason(error);
966
1013
  if (error instanceof RevokeProofError) capture.proofError = error;
1014
+ if (error instanceof LeafBindingError) capture.bindingError = error;
967
1015
  return 'reject';
968
1016
  }
969
1017
  if (callerPolicy != null) return callerPolicy(incoming);
@@ -1075,7 +1123,10 @@ export function mutexFor(handle) {
1075
1123
  ...parsed.controller != null ? {
1076
1124
  controller: parsed.controller.id,
1077
1125
  prefix: parsed.controller.prefix,
1078
- capability: parsed.controller.capability
1126
+ capability: parsed.controller.capability,
1127
+ ...parsed.controller.holderGrant == null ? {} : {
1128
+ holderGrant: parsed.controller.holderGrant
1129
+ }
1079
1130
  } : {}
1080
1131
  };
1081
1132
  }
@@ -1184,6 +1235,7 @@ export function mutexFor(handle) {
1184
1235
  * Process a received MLS message (Commit, Proposal, or application). Accepts
1185
1236
  * wire-form bytes (preferred, e.g. from commitInvite/removeMember) or a pre-decoded
1186
1237
  * ts-mls framed message (legacy). The runtime `instanceof` selects the decode path.
1238
+ * A proposal from a past epoch is ignored (returns null, nothing persisted).
1187
1239
  * `persist` covers accepted commits and proposals, not application messages or their
1188
1240
  * receive ratchet. It runs under this handle's mutex and must not call back into it.
1189
1241
  * It must write atomically: rejection means nothing was stored. Host callbacks run
@@ -1198,6 +1250,11 @@ export function mutexFor(handle) {
1198
1250
  decoded = parsed;
1199
1251
  }
1200
1252
  return mutexFor(this).run(async ()=>{
1253
+ const privateProposal = readPrivateFrame(decoded, contentTypes.proposal);
1254
+ const frame = decoded;
1255
+ const proposalEpoch = privateProposal?.epoch ?? (frame.wireformat === wireformats.mls_public_message && frame.publicMessage.content.contentType === contentTypes.proposal ? frame.publicMessage.content.epoch : undefined);
1256
+ // Past proposals cannot be enacted at this epoch and need no ratchet or ledger work.
1257
+ if (proposalEpoch != null && proposalEpoch < this.epoch) return null;
1201
1258
  const { callback, capture, applyOnAccept, postApply } = await this.#prepareCommitPipeline(decoded, opts);
1202
1259
  const previousState = this.#state;
1203
1260
  const previousAdmission = this.#admission;
@@ -1222,12 +1279,20 @@ export function mutexFor(handle) {
1222
1279
  try {
1223
1280
  await verifyLeafCredential(credential, key, {
1224
1281
  deviceDenySet: ()=>this.currentDenySet(),
1282
+ // MLS re-validates the committer's path leaf after its proposals are judged:
1283
+ // an evidenced child keeps a denied issuer only with the credential it
1284
+ // already holds at that leaf.
1285
+ mayKeepDeniedIssuer: (leafCredential, leafKey)=>this.#anchor.controller != null && capture.committerLeafIndex != null && isUnchangedLeaf(this.#state.ratchetTree, capture.committerLeafIndex, {
1286
+ credential: leafCredential,
1287
+ signaturePublicKey: leafKey
1288
+ }),
1225
1289
  leafLifetime: ()=>this.#anchor.controller == null ? undefined : this.#anchor.leafLifetime ?? 86_400,
1226
1290
  trustedGrantLifetime: ()=>this.#anchor.controller == null ? undefined : this.#anchor.trustedGrantLifetime ?? 2_592_000
1227
1291
  });
1228
1292
  return true;
1229
1293
  } catch (error) {
1230
1294
  capture.reason = rejectionReason(error);
1295
+ if (error instanceof LeafBindingError) capture.bindingError = error;
1231
1296
  return false;
1232
1297
  }
1233
1298
  }
@@ -1242,13 +1307,14 @@ export function mutexFor(handle) {
1242
1307
  } catch (error) {
1243
1308
  if (application != null) throw error;
1244
1309
  const rejection = new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex, capture.reason ?? 'invalid');
1245
- rejection.cause = error;
1310
+ rejection.cause = capture.bindingError ?? error;
1246
1311
  if (error instanceof Error) rejection.message += `: ${error.message}`;
1247
1312
  throw rejection;
1248
1313
  }
1249
1314
  if (result.kind === 'newState' && result.actionTaken === 'reject') {
1250
1315
  const rejection = new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex, capture.reason ?? 'policy');
1251
- if (capture.proofError != null) rejection.cause = capture.proofError;
1316
+ const cause = capture.proofError ?? capture.bindingError;
1317
+ if (cause != null) rejection.cause = cause;
1252
1318
  throw rejection;
1253
1319
  }
1254
1320
  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';
13
+ import { authenticateLifecycleProof, isExemptMember, verifyLifecycleProof } from './lifecycle-proof.js';
14
14
  import { DEVICE_ENTRY_TYPE } 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,15 @@ 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) {
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) {
196
236
  if (group.registry.devices.get(subject)?.status !== 'revoked') return false;
197
237
  if (group.findMemberLeafIndex(subject) != null) return false;
198
238
  return !group.listMembers().some((member)=>{
199
239
  const capability = group.bindingOfDID(member.id)?.capability;
200
- return capability != null && normalizeDID(readCapability(capability).payload.iss) === subject;
240
+ return capability != null && normalizeDID(readCapability(capability).payload.iss) === subject && !isExemptMember(group, member.leafIndex);
201
241
  });
202
242
  }
203
243
  export async function revokeWithProof(group, params) {
@@ -242,7 +282,8 @@ export async function revokeWithProof(group, params) {
242
282
  return {
243
283
  ...member,
244
284
  issuer: payload?.cap == null ? undefined : normalizeDID(payload.iss),
245
- generation: folded?.ok ? folded.states.at(-1)?.gen : undefined
285
+ generation: folded?.ok ? folded.states.at(-1)?.gen : undefined,
286
+ exempt: isExemptMember(group, member.leafIndex)
246
287
  };
247
288
  });
248
289
  if (reset) for (const leaf of leaves){
@@ -252,7 +293,7 @@ export async function revokeWithProof(group, params) {
252
293
  }
253
294
  const direct = new Set(revoked.map(({ did })=>did));
254
295
  for (const leaf of leaves){
255
- if (leaf.issuer != null && direct.has(leaf.issuer) && !direct.has(normalizeDID(leaf.id))) revoked.push({
296
+ if (leaf.issuer != null && direct.has(leaf.issuer) && !direct.has(normalizeDID(leaf.id)) && !leaf.exempt) revoked.push({
256
297
  did: normalizeDID(leaf.id),
257
298
  cascadedFrom: leaf.issuer
258
299
  });
@@ -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 } 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 ?? []
@@ -170,7 +195,7 @@ export { controllerLogSize, HISTORY_HORIZON } from './history.js';
170
195
  }
171
196
  const direct = new Set(revoked.map(({ did })=>did));
172
197
  for (const leaf of leaves){
173
- if (leaf.issuer != null && direct.has(leaf.issuer) && !direct.has(leaf.did)) {
198
+ if (leaf.issuer != null && direct.has(leaf.issuer) && !direct.has(leaf.did) && !leaf.exempt) {
174
199
  revoked.push({
175
200
  did: leaf.did,
176
201
  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 = {
package/lib/lifecycle.js CHANGED
@@ -2,14 +2,14 @@ import { foldLog } from '@kokuin/controller';
2
2
  import { normalizeDID } from '@kokuin/token';
3
3
  import { defaultCredentialTypes, defaultProposalTypes, isDefaultCredential, isDefaultProposal, nodeTypes } from 'ts-mls';
4
4
  import { LEDGER_HEAD_EXTENSION_TYPE } from './anchor.js';
5
- import { verifyLeafCredential } from './authentication.js';
5
+ import { checkHolderEvidence, verifyLeafCredential } from './authentication.js';
6
6
  import { assertCapabilityLifetime, MAX_LEAF_LIFETIME, MAX_TRUSTED_GRANT_LIFETIME, readCapability } from './capability.js';
7
7
  import { parseMLSCredentialIdentity } from './credential.js';
8
8
  import { LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
9
9
  import { assertBindingAuthorTime, makeMLSCredential } from './group-credential.js';
10
10
  import { decodeLedgerHead, extendHead, genesisHead, headsMatch } from './head.js';
11
11
  import { HISTORY_HORIZON, historySize } from './history.js';
12
- import { verifyLifecycleProof } from './lifecycle-proof.js';
12
+ import { isEvidencedChild, verifyLifecycleProof } from './lifecycle-proof.js';
13
13
  import { evaluateGroupContextExtensions } from './policy.js';
14
14
  import { DEVICE_ENTRY_TYPE, denySetOf } from './registry.js';
15
15
  export function rejectionReason(error) {
@@ -67,7 +67,18 @@ function bytesEqual(a, b) {
67
67
  function credentialEqual(a, b) {
68
68
  return isDefaultCredential(a.credential) && isDefaultCredential(b.credential) && a.credential.credentialType === defaultCredentialTypes.basic && b.credential.credentialType === defaultCredentialTypes.basic && bytesEqual(a.credential.identity, b.credential.identity);
69
69
  }
70
- function checkBinding(group, leaf, previous) {
70
+ /**
71
+ * Whether a direct capability from the anchor's controller replaces a leaf whose issuer the group
72
+ * recorded revoked. Such a replacement only trades a revoked issuer's credential for the
73
+ * controller's own, so it need not be newer.
74
+ */ function replacesRevokedIssuer(group, binding, old) {
75
+ const controller = group.anchor.controller;
76
+ if (controller == null || normalizeDID(binding.id) !== normalizeDID(controller)) return false;
77
+ if (readCapability(binding.capability).payload.cap !== undefined) return false;
78
+ const current = readCapability(old.capability).payload;
79
+ return current.cap !== undefined && group.registry.devices.get(normalizeDID(current.iss))?.status === 'revoked';
80
+ }
81
+ function checkBinding(group, leaf, previous, /** The leaf arrives in a Welcome tree rather than as an entry. */ welcome = false) {
71
82
  const parsed = identity(leaf);
72
83
  const binding = parsed.controller;
73
84
  const controller = group.anchor.controller;
@@ -80,14 +91,15 @@ function checkBinding(group, leaf, previous) {
80
91
  if (previous != null) {
81
92
  const old = identity(previous);
82
93
  if (parsed.id !== old.id || parsed.longForm !== old.longForm || !bytesEqual(leaf.signaturePublicKey, previous.signaturePublicKey) || old.controller != null && (binding == null || binding.id !== old.controller.id)) throw new LeafBindingError('identity-change');
83
- if (binding != null && old.controller != null && readCapability(binding.capability).payload.iat < readCapability(old.controller.capability).payload.iat) throw new LeafBindingError('renewal-order');
94
+ if (binding != null && old.controller != null && readCapability(binding.capability).payload.iat < readCapability(old.controller.capability).payload.iat && !replacesRevokedIssuer(group, binding, old.controller)) throw new LeafBindingError('renewal-order');
84
95
  }
85
96
  if (binding == null) return;
86
97
  const payload = readCapability(binding.capability).payload;
98
+ checkHolderEvidence(parsed, leaf.signaturePublicKey, controller == null ? MAX_TRUSTED_GRANT_LIFETIME : group.anchor.trustedGrantLifetime ?? 2_592_000);
87
99
  assertCapabilityLifetime(payload, controller == null ? MAX_LEAF_LIFETIME : group.anchor.leafLifetime ?? 86_400);
88
100
  const parent = Array.isArray(payload.cap) ? payload.cap[0] : payload.cap;
89
101
  if (parent != null) assertCapabilityLifetime(readCapability(parent).payload, controller == null ? MAX_TRUSTED_GRANT_LIFETIME : group.anchor.trustedGrantLifetime ?? 2_592_000);
90
- if (payload.cap != null && denied.has(normalizeDID(payload.iss))) throw new LeafBindingError('denied-issuer');
102
+ if (payload.cap != null && denied.has(normalizeDID(payload.iss)) && !(welcome && isEvidencedChild(group, leaf, denied))) throw new LeafBindingError('denied-issuer');
91
103
  const folded = foldLog(binding.id, binding.prefix);
92
104
  if (!folded.ok) throw new LeafBindingError('controller-mismatch');
93
105
  if (controller != null && (folded.states.at(-1)?.gen ?? 0) < (group.registry.controllers.get(normalizeDID(controller))?.genFloor ?? 0)) throw new LeafBindingError('generation-floor');
@@ -100,10 +112,11 @@ function checkEntry(group, leaf, previous) {
100
112
  checkBinding(group, leaf, previous);
101
113
  checkAdmissionExpiry(group, leaf);
102
114
  }
103
- async function validateBoundLeaf(group, leaf, previous) {
104
- checkBinding(group, leaf, previous);
115
+ async function validateBoundLeaf(group, leaf, previous, welcome = false) {
116
+ checkBinding(group, leaf, previous, welcome);
105
117
  await verifyLeafCredential(leaf.credential, leaf.signaturePublicKey, {
106
118
  deviceDenySet: ()=>denySetOf(group.registry),
119
+ mayKeepDeniedIssuer: ()=>welcome && group.anchor.controller != null,
107
120
  leafLifetime: ()=>group.anchor.controller == null ? undefined : group.anchor.leafLifetime ?? 86_400,
108
121
  trustedGrantLifetime: ()=>group.anchor.controller == null ? undefined : group.anchor.trustedGrantLifetime ?? 2_592_000
109
122
  });
@@ -112,10 +125,14 @@ export async function validateEntry(group, leaf, previous) {
112
125
  await validateBoundLeaf(group, leaf, previous);
113
126
  checkAdmissionExpiry(group, leaf);
114
127
  }
115
- function checkSurvivors(group, tree, registry) {
128
+ /** The same credential and key a tree already holds at that leaf index. */ export function isUnchangedLeaf(tree, index, leaf) {
129
+ const held = leafAt(tree, index);
130
+ return held != null && credentialEqual(held, leaf) && bytesEqual(held.signaturePublicKey, leaf.signaturePublicKey);
131
+ }
132
+ function checkSurvivors(group, tree, registry, origin) {
116
133
  const denied = denySetOf(registry);
117
134
  const controller = group.anchor.controller;
118
- for (const node of tree){
135
+ for (const [position, node] of tree.entries()){
119
136
  if (node?.nodeType !== nodeTypes.leaf) continue;
120
137
  const parsed = identity(node.leaf);
121
138
  if (denied.has(normalizeDID(parsed.id))) throw new LeafBindingError('denied-id');
@@ -125,7 +142,7 @@ function checkSurvivors(group, tree, registry) {
125
142
  }
126
143
  const binding = parsed.controller;
127
144
  const payload = readCapability(binding.capability).payload;
128
- if (payload.cap != null && denied.has(normalizeDID(payload.iss))) throw new LeafBindingError('denied-issuer');
145
+ if (payload.cap != null && denied.has(normalizeDID(payload.iss)) && !((origin.kind === 'welcome' || position % 2 === 0 && isUnchangedLeaf(origin.before, position / 2, node.leaf)) && isEvidencedChild(group, node.leaf, denied))) throw new LeafBindingError('denied-issuer');
129
146
  if (controller != null) {
130
147
  const folded = foldLog(binding.id, binding.prefix);
131
148
  if (normalizeDID(binding.id) !== normalizeDID(controller) || !folded.ok) throw new LeafBindingError('controller-mismatch');
@@ -136,10 +153,12 @@ function checkSurvivors(group, tree, registry) {
136
153
  export async function validateWelcomeTree(group) {
137
154
  for (const [index, node] of group.state.ratchetTree.entries()){
138
155
  if (node?.nodeType !== nodeTypes.leaf) continue;
139
- await validateBoundLeaf(group, node.leaf);
156
+ await validateBoundLeaf(group, node.leaf, undefined, true);
140
157
  if (index === group.state.privatePath.leafIndex * 2) checkAdmissionExpiry(group, node.leaf);
141
158
  }
142
- checkSurvivors(group, group.state.ratchetTree, group.registry);
159
+ checkSurvivors(group, group.state.ratchetTree, group.registry, {
160
+ kind: 'welcome'
161
+ });
143
162
  }
144
163
  /** The callback judges proposals; survivors check the path before any state is installed. */ export async function prepareLifecycleGate(params) {
145
164
  const { group, entries, candidateRegistry, context, externalLeaf } = params;
@@ -304,7 +323,10 @@ export async function validateWelcomeTree(group) {
304
323
  }
305
324
  if (incoming.kind === 'commit') checkTime(tree);
306
325
  checkSize(tree);
307
- checkSurvivors(group, tree, candidateRegistry);
326
+ checkSurvivors(group, tree, candidateRegistry, {
327
+ kind: 'commit',
328
+ before
329
+ });
308
330
  };
309
331
  const postApply = async (state)=>{
310
332
  if (incomingCommit == null || state.groupActiveState.kind === 'removedFromGroup') return;
@@ -326,7 +348,10 @@ export async function validateWelcomeTree(group) {
326
348
  }
327
349
  checkTime(state.ratchetTree);
328
350
  checkSize(state.ratchetTree);
329
- checkSurvivors(group, state.ratchetTree, candidateRegistry);
351
+ checkSurvivors(group, state.ratchetTree, candidateRegistry, {
352
+ kind: 'commit',
353
+ before
354
+ });
330
355
  };
331
356
  return {
332
357
  check,
package/lib/policy.js CHANGED
@@ -111,7 +111,7 @@ function bytesEqual(a, b) {
111
111
  // A credential that names no DID (non-`basic`, or malformed) is rejected rather than
112
112
  // trusted. `didFromCredential` is total, so nothing here can throw past this boundary.
113
113
  const addedDID = didFromCredential(proposal.add.keyPackage.leafNode.credential);
114
- if (addedDID === undefined) {
114
+ if (addedDID === null) {
115
115
  return 'reject';
116
116
  }
117
117
  // Bind the leaf that joins to the roster this commit produces, mirroring the binding
@@ -0,0 +1,3 @@
1
+ import type { SecretTree } from 'ts-mls';
2
+ /** Merge same-epoch trees without mutating inputs. The result takes `leafWidth` from `target`. */
3
+ export declare function mergeReceiveSecretTree(target: SecretTree, source: SecretTree): SecretTree;
@@ -0,0 +1,60 @@
1
+ /** Combine two same-epoch ratchets, retaining a skipped key only if neither side spent it. */ function mergeGenerationSecrets(a, b) {
2
+ const [ahead, behind] = a.generation >= b.generation ? [
3
+ a,
4
+ b
5
+ ] : [
6
+ b,
7
+ a
8
+ ];
9
+ const unusedGenerations = {};
10
+ for (const [generationText, secret] of Object.entries(ahead.unusedGenerations)){
11
+ const generation = Number(generationText);
12
+ if (generation >= behind.generation || Object.hasOwn(behind.unusedGenerations, generation)) {
13
+ unusedGenerations[generation] = secret;
14
+ }
15
+ }
16
+ return {
17
+ ...ahead,
18
+ unusedGenerations
19
+ };
20
+ }
21
+ /** Merge same-epoch trees without mutating inputs. The result takes `leafWidth` from `target`. */ export function mergeReceiveSecretTree(target, source) {
22
+ // Each side can expand a different part of the tree. Keep the most-expanded
23
+ // representation of every branch: an ancestor secret must disappear when
24
+ // either side has derived a descendant, or it could derive spent keys again.
25
+ // The descendants include sibling intermediate secrets needed for members
26
+ // who have not sent yet; simply intersecting node maps loses those keys.
27
+ const intermediateNodes = {
28
+ ...target.intermediateNodes,
29
+ ...source.intermediateNodes
30
+ };
31
+ const leafNodes = {
32
+ ...target.leafNodes
33
+ };
34
+ for (const [indexText, node] of Object.entries(source.leafNodes)){
35
+ const index = Number(indexText);
36
+ const prior = leafNodes[index];
37
+ leafNodes[index] = prior == null ? node : {
38
+ handshake: mergeGenerationSecrets(prior.handshake, node.handshake),
39
+ application: mergeGenerationSecrets(prior.application, node.application)
40
+ };
41
+ }
42
+ const occupied = [
43
+ ...Object.keys(intermediateNodes),
44
+ ...Object.keys(leafNodes)
45
+ ].map(Number);
46
+ for (const ancestorText of Object.keys(intermediateNodes)){
47
+ const ancestor = Number(ancestorText);
48
+ let level = 0;
49
+ while((ancestor >> level & 1) === 1)level++;
50
+ const span = 2 ** level - 1;
51
+ if (occupied.some((node)=>node !== ancestor && node >= ancestor - span && node <= ancestor + span)) {
52
+ delete intermediateNodes[ancestor];
53
+ }
54
+ }
55
+ return {
56
+ leafWidth: target.leafWidth,
57
+ intermediateNodes,
58
+ leafNodes
59
+ };
60
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/mls",
3
- "version": "0.10.1",
3
+ "version": "0.10.2",
4
4
  "description": "E2EE group identity and membership for Enkaku using MLS",
5
5
  "keywords": [
6
6
  "mls",
@@ -25,9 +25,9 @@
25
25
  "lib/*"
26
26
  ],
27
27
  "dependencies": {
28
- "@kokuin/capability": "^0.3.1",
28
+ "@kokuin/capability": "^0.4.1",
29
29
  "@kokuin/controller": "^0.1.0",
30
- "@kokuin/token": "^0.5.0",
30
+ "@kokuin/token": "^0.5.1",
31
31
  "@noble/ciphers": "^2.4.0",
32
32
  "@noble/curves": "^2.4.0",
33
33
  "@noble/hashes": "^2.4.0",