@kumiai/mls 0.10.7 → 0.10.9

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.
package/README.md CHANGED
@@ -32,7 +32,7 @@ Decoding requires the body's canonical re-encoding to match its stored bytes bef
32
32
  ## Capabilities
33
33
 
34
34
  - `createGroup` — creator opens a new group as its sole member and first admin
35
- - `createInvite` + `commitInvite` — an admin signs the invitee's role entry and produces the MLS Commit + Welcome
35
+ - `createInvite` + `commitInvite` — an admin signs the invitee's role entry and produces the MLS Commit + Welcome. In a lifecycle group, admitting a DID that still holds a stale leaf removes that leaf in the same commit when the new key package carries a strictly newer binding; two leaves for the DID throw `DuplicateMemberLeafError`
36
36
  - `processWelcome` — invitee joins after folding the ledger the invite carries and checking its head
37
37
  - `commitLedgerEntries` — an admin promotes or demotes by committing signed `kumiai.role` entries
38
38
  - `removeMember` — an admin evicts a leaf and rotates keys
@@ -62,6 +62,16 @@ export type GroupMember = {
62
62
  controller?: string;
63
63
  /** For a bound leaf: the controller's advisory folded log beacon, when one has been announced. */
64
64
  controllerBeacon?: ControllerBeacon;
65
+ /**
66
+ * Names the KeyPackage this leaf was Added from (its leaf node's HPKE key), present only while
67
+ * the leaf still holds that KeyPackage's leaf node — until the member's own first path or
68
+ * Update replaces it. Absent on a leaf that entered by external commit.
69
+ *
70
+ * Only an Add puts a KeyPackage leaf node into the tree, so a value present after a commit and
71
+ * absent before it means the commit Added a leaf — including an Add of a DID the group already
72
+ * held (a stale-leaf replacement), which an `id` diff cannot see.
73
+ */
74
+ admission?: string;
65
75
  };
66
76
  export declare function parseMLSCredentialIdentity(identity: Uint8Array): MLSCredentialIdentity;
67
77
  /**
@@ -12,6 +12,7 @@ import { ledgerEntryDigest, signLedgerEntry, verifyLedgerEntry } from './ledger.
12
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
+ import { staleLeafIndex } from './stale-leaf.js';
15
16
  /** The supplied key package names a different identity from the invite's recipient. */ export class InviteRecipientMismatchError extends Error {
16
17
  #groupID;
17
18
  #expectedDID;
@@ -367,9 +368,19 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
367
368
  keyPackage
368
369
  }
369
370
  };
371
+ // A lifecycle group re-admitting a device replaces the leaf it still holds for that DID.
372
+ const stale = group.anchor.controller == null ? undefined : staleLeafIndex(group.state.ratchetTree, keyPackage.leafNode);
370
373
  const result = await commitWithEntries({
371
374
  group,
372
- extraProposals: [
375
+ extraProposals: stale == null ? [
376
+ addProposal
377
+ ] : [
378
+ {
379
+ proposalType: defaultProposalTypes.remove,
380
+ remove: {
381
+ removed: stale
382
+ }
383
+ },
373
384
  addProposal
374
385
  ],
375
386
  enacted,
@@ -1,6 +1,7 @@
1
1
  import { assertTimeClaimsValid, decodeSignedToken, normalizeDID } from '@kokuin/token';
2
+ import { toB64 } from '@sozai/codec';
2
3
  import { EventEmitter } from '@sozai/event';
3
- import { contentTypes, createApplicationMessage, createProposal, decode, defaultCredentialTypes, defaultKeyRetentionConfig, defaultProposalTypes, encode, isDefaultCredential, mlsExporter, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, UsageError, wireformats } from 'ts-mls';
4
+ import { contentTypes, createApplicationMessage, createProposal, decode, defaultCredentialTypes, defaultKeyRetentionConfig, defaultProposalTypes, encode, isDefaultCredential, leafNodeSources, mlsExporter, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, UsageError, wireformats } from 'ts-mls';
4
5
  import { readGroupAnchor } from './anchor.js';
5
6
  import { verifyLeafCredential } from './authentication.js';
6
7
  import { encodeClientState } from './codec.js';
@@ -673,6 +674,9 @@ function ledgerLogEntry(entryID, token, verified) {
673
674
  // trusts the host's own persisted state, so neither gate runs on that path.
674
675
  const controller = parsed.controller ? parsed.controller.id : undefined;
675
676
  const beacon = controller != null ? beaconOf(this.#registry, controller) : undefined;
677
+ // A KeyPackage leaf node is unique to its KeyPackage by its fresh HPKE key, and stays
678
+ // in the tree only until the member's own path or Update replaces it.
679
+ const admission = node.leaf.leafNodeSource === leafNodeSources.key_package ? toB64(node.leaf.hpkePublicKey) : undefined;
676
680
  yield {
677
681
  leafIndex: i / 2,
678
682
  id: parsed.id,
@@ -682,6 +686,9 @@ function ledgerLogEntry(entryID, token, verified) {
682
686
  } : {},
683
687
  ...beacon ? {
684
688
  controllerBeacon: beacon
689
+ } : {},
690
+ ...admission != null ? {
691
+ admission
685
692
  } : {}
686
693
  };
687
694
  }
package/lib/index.d.ts CHANGED
@@ -25,5 +25,6 @@ export { confirmationKey, confirmationTag, type OpenedRecoveryVerdict, openRecov
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
27
  export { mergeReceiveSecretTree } from './secret-tree.js';
28
+ export { DuplicateMemberLeafError } from './stale-leaf.js';
28
29
  export type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
29
30
  export { welcomeKeyPackageRefs } from './welcome-refs.js';
package/lib/index.js CHANGED
@@ -22,4 +22,5 @@ export { confirmationKey, confirmationTag, openRecoveryVerdict, recoverySignerEl
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
24
  export { mergeReceiveSecretTree } from './secret-tree.js';
25
+ export { DuplicateMemberLeafError } from './stale-leaf.js';
25
26
  export { welcomeKeyPackageRefs } from './welcome-refs.js';
package/lib/lifecycle.js CHANGED
@@ -12,6 +12,7 @@ import { HISTORY_HORIZON, historySize } from './history.js';
12
12
  import { isEvidencedChild, verifyLifecycleProof } from './lifecycle-proof.js';
13
13
  import { evaluateGroupContextExtensions } from './policy.js';
14
14
  import { DEVICE_ENTRY_TYPE, denySetOf, mayReadmitResetDevice } from './registry.js';
15
+ import { assertNewerBinding, stalePairedAdd } from './stale-leaf.js';
15
16
  export function rejectionReason(error) {
16
17
  if (error instanceof LeafLapsedError) return 'lapse';
17
18
  if (error instanceof LeafBindingError) {
@@ -303,7 +304,22 @@ export async function validateWelcomeTree(group) {
303
304
  // A self-removal proposal is honoured only when another member commits it.
304
305
  const selfRemoval = proposalSender === target && (incoming.kind === 'proposal' || incoming.senderLeafIndex !== target);
305
306
  const authorised = proofs.length > 0 || lapsed.has(target) || selfRemoval;
306
- if (controller != null && (old == null || !authorised)) throw new Error('Unauthorised Remove');
307
+ // Admitting a fresh key package may replace its DID's one stale leaf in the same commit.
308
+ const replacement = controller == null || authorised || old == null || incoming.kind !== 'commit' || incoming.senderLeafIndex == null ? undefined : stalePairedAdd({
309
+ before,
310
+ target,
311
+ proposals,
312
+ committer: incoming.senderLeafIndex,
313
+ denied: [
314
+ denySetOf(group.registry),
315
+ denySetOf(candidateRegistry)
316
+ ]
317
+ });
318
+ if (replacement != null && old != null) {
319
+ checkEntry(group, replacement, old);
320
+ assertNewerBinding(replacement, old);
321
+ }
322
+ if (controller != null && (old == null || !(authorised || replacement != null))) throw new Error('Unauthorised Remove');
307
323
  tree[target * 2] = undefined;
308
324
  break;
309
325
  }
@@ -0,0 +1,35 @@
1
+ import { type ClientState, type LeafNode, type ProposalWithSender } from 'ts-mls';
2
+ /** More than one leaf of a lifecycle group names the DID an admission would replace. */
3
+ export declare class DuplicateMemberLeafError extends Error {
4
+ #private;
5
+ constructor(did: string);
6
+ get did(): string;
7
+ }
8
+ /**
9
+ * A replacement carries a controller grant issued strictly after the replaced leaf's, so a key
10
+ * package published under the leaf's current grant cannot evict that leaf.
11
+ */
12
+ export declare function assertNewerBinding(leaf: LeafNode, replaced: LeafNode): void;
13
+ /**
14
+ * The leaf an admission of `leaf` replaces: the one leaf the tree already holds for the same DID,
15
+ * or `undefined` when it holds none. Two or more such leaves are ambiguous and refused.
16
+ */
17
+ export declare function staleLeafIndex(tree: ClientState['ratchetTree'], leaf: LeafNode): number | undefined;
18
+ export type StaleLeafReplacementParams = {
19
+ /** The tree before the commit. */
20
+ before: ClientState['ratchetTree'];
21
+ /** The leaf a Remove targets. */
22
+ target: number;
23
+ /** Every proposal the commit carries. */
24
+ proposals: Array<ProposalWithSender>;
25
+ /** The committer's leaf. */
26
+ committer: number;
27
+ /** The deny sets the replaced DID must be absent from. */
28
+ denied: Array<ReadonlySet<string>>;
29
+ };
30
+ /**
31
+ * The added leaf that replaces `target` in the same commit, when the commit is an admission of a
32
+ * fresh key package for the DID whose only leaf `target` is. The caller still judges that leaf as
33
+ * the replacement of `target`; this only finds the pairing.
34
+ */
35
+ export declare function stalePairedAdd(params: StaleLeafReplacementParams): LeafNode | undefined;
@@ -0,0 +1,75 @@
1
+ import { normalizeDID } from '@kokuin/token';
2
+ import { defaultCredentialTypes, defaultProposalTypes, isDefaultCredential, isDefaultProposal, nodeTypes } from 'ts-mls';
3
+ import { readCapability } from './capability.js';
4
+ import { parseMLSCredentialIdentity } from './credential.js';
5
+ import { LeafBindingError } from './errors.js';
6
+ /** More than one leaf of a lifecycle group names the DID an admission would replace. */ export class DuplicateMemberLeafError extends Error {
7
+ #did;
8
+ constructor(did){
9
+ super(`The group holds more than one leaf for ${did}`);
10
+ this.name = 'DuplicateMemberLeafError';
11
+ this.#did = did;
12
+ }
13
+ get did() {
14
+ return this.#did;
15
+ }
16
+ }
17
+ function leafDID(leaf) {
18
+ if (!isDefaultCredential(leaf.credential) || leaf.credential.credentialType !== defaultCredentialTypes.basic) return undefined;
19
+ try {
20
+ const { id } = parseMLSCredentialIdentity(leaf.credential.identity);
21
+ return id === '' ? undefined : normalizeDID(id);
22
+ } catch {
23
+ return undefined;
24
+ }
25
+ }
26
+ function bindingTime(leaf) {
27
+ if (!isDefaultCredential(leaf.credential) || leaf.credential.credentialType !== defaultCredentialTypes.basic) return undefined;
28
+ const binding = parseMLSCredentialIdentity(leaf.credential.identity).controller;
29
+ return binding == null ? undefined : readCapability(binding.capability).payload.iat;
30
+ }
31
+ /**
32
+ * A replacement carries a controller grant issued strictly after the replaced leaf's, so a key
33
+ * package published under the leaf's current grant cannot evict that leaf.
34
+ */ export function assertNewerBinding(leaf, replaced) {
35
+ const next = bindingTime(leaf);
36
+ const previous = bindingTime(replaced);
37
+ if (next == null || previous == null || next <= previous) throw new LeafBindingError('renewal-order');
38
+ }
39
+ function leafIndicesOf(tree, did) {
40
+ const indices = [];
41
+ for (const [position, node] of tree.entries()){
42
+ if (node?.nodeType === nodeTypes.leaf && leafDID(node.leaf) === did) indices.push(position / 2);
43
+ }
44
+ return indices;
45
+ }
46
+ /**
47
+ * The leaf an admission of `leaf` replaces: the one leaf the tree already holds for the same DID,
48
+ * or `undefined` when it holds none. Two or more such leaves are ambiguous and refused.
49
+ */ export function staleLeafIndex(tree, leaf) {
50
+ const did = leafDID(leaf);
51
+ if (did == null) return undefined;
52
+ const indices = leafIndicesOf(tree, did);
53
+ if (indices.length > 1) throw new DuplicateMemberLeafError(did);
54
+ return indices[0];
55
+ }
56
+ /**
57
+ * The added leaf that replaces `target` in the same commit, when the commit is an admission of a
58
+ * fresh key package for the DID whose only leaf `target` is. The caller still judges that leaf as
59
+ * the replacement of `target`; this only finds the pairing.
60
+ */ export function stalePairedAdd(params) {
61
+ const { before, target, proposals, committer, denied } = params;
62
+ if (target === committer) return undefined;
63
+ const node = before[target * 2];
64
+ if (node?.nodeType !== nodeTypes.leaf) return undefined;
65
+ const did = leafDID(node.leaf);
66
+ if (did == null || leafIndicesOf(before, did).length !== 1) return undefined;
67
+ if (denied.some((set)=>[
68
+ ...set
69
+ ].some((held)=>normalizeDID(held) === did))) return undefined;
70
+ const removes = proposals.filter(({ proposal })=>isDefaultProposal(proposal) && proposal.proposalType === defaultProposalTypes.remove && proposal.remove.removed === target);
71
+ const adds = proposals.flatMap(({ proposal })=>isDefaultProposal(proposal) && proposal.proposalType === defaultProposalTypes.add && leafDID(proposal.add.keyPackage.leafNode) === did ? [
72
+ proposal.add.keyPackage.leafNode
73
+ ] : []);
74
+ return removes.length === 1 && adds.length === 1 ? adds[0] : undefined;
75
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/mls",
3
- "version": "0.10.7",
3
+ "version": "0.10.9",
4
4
  "description": "E2EE group identity and membership for Enkaku using MLS",
5
5
  "keywords": [
6
6
  "mls",