@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.
package/lib/lifecycle.js CHANGED
@@ -2,16 +2,16 @@ 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
- import { DEVICE_ENTRY_TYPE, denySetOf } from './registry.js';
14
+ import { DEVICE_ENTRY_TYPE, denySetOf, mayReadmitResetDevice } from './registry.js';
15
15
  export function rejectionReason(error) {
16
16
  if (error instanceof LeafLapsedError) return 'lapse';
17
17
  if (error instanceof LeafBindingError) {
@@ -67,27 +67,39 @@ 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;
74
85
  if (controller != null && binding == null) throw new LeafBindingError('floating-refused');
75
86
  if (controller != null && binding != null && normalizeDID(binding.id) !== normalizeDID(controller)) throw new LeafBindingError('controller-mismatch');
76
87
  const denied = denySetOf(group.registry);
77
- if (denied.has(normalizeDID(parsed.id))) throw new LeafBindingError('denied-id');
88
+ if (denied.has(normalizeDID(parsed.id)) && !mayReadmitResetDevice(group.registry, parsed)) throw new LeafBindingError('denied-id');
78
89
  const record = group.registry.devices.get(normalizeDID(parsed.id));
79
90
  if (record != null && (binding == null || normalizeDID(binding.id) !== record.controller)) throw new LeafBindingError('controller-mismatch');
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,12 @@ 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
+ deviceRegistry: ()=>group.anchor.controller == null ? undefined : group.registry,
120
+ mayKeepDeniedIssuer: ()=>welcome && group.anchor.controller != null,
107
121
  leafLifetime: ()=>group.anchor.controller == null ? undefined : group.anchor.leafLifetime ?? 86_400,
108
122
  trustedGrantLifetime: ()=>group.anchor.controller == null ? undefined : group.anchor.trustedGrantLifetime ?? 2_592_000
109
123
  });
@@ -112,20 +126,24 @@ export async function validateEntry(group, leaf, previous) {
112
126
  await validateBoundLeaf(group, leaf, previous);
113
127
  checkAdmissionExpiry(group, leaf);
114
128
  }
115
- function checkSurvivors(group, tree, registry) {
129
+ /** The same credential and key a tree already holds at that leaf index. */ export function isUnchangedLeaf(tree, index, leaf) {
130
+ const held = leafAt(tree, index);
131
+ return held != null && credentialEqual(held, leaf) && bytesEqual(held.signaturePublicKey, leaf.signaturePublicKey);
132
+ }
133
+ function checkSurvivors(group, tree, registry, origin) {
116
134
  const denied = denySetOf(registry);
117
135
  const controller = group.anchor.controller;
118
- for (const node of tree){
136
+ for (const [position, node] of tree.entries()){
119
137
  if (node?.nodeType !== nodeTypes.leaf) continue;
120
138
  const parsed = identity(node.leaf);
121
- if (denied.has(normalizeDID(parsed.id))) throw new LeafBindingError('denied-id');
139
+ if (denied.has(normalizeDID(parsed.id)) && !mayReadmitResetDevice(registry, parsed)) throw new LeafBindingError('denied-id');
122
140
  if (parsed.controller == null) {
123
141
  if (controller != null) throw new LeafBindingError('floating-refused');
124
142
  continue;
125
143
  }
126
144
  const binding = parsed.controller;
127
145
  const payload = readCapability(binding.capability).payload;
128
- if (payload.cap != null && denied.has(normalizeDID(payload.iss))) throw new LeafBindingError('denied-issuer');
146
+ 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
147
  if (controller != null) {
130
148
  const folded = foldLog(binding.id, binding.prefix);
131
149
  if (normalizeDID(binding.id) !== normalizeDID(controller) || !folded.ok) throw new LeafBindingError('controller-mismatch');
@@ -136,10 +154,12 @@ function checkSurvivors(group, tree, registry) {
136
154
  export async function validateWelcomeTree(group) {
137
155
  for (const [index, node] of group.state.ratchetTree.entries()){
138
156
  if (node?.nodeType !== nodeTypes.leaf) continue;
139
- await validateBoundLeaf(group, node.leaf);
157
+ await validateBoundLeaf(group, node.leaf, undefined, true);
140
158
  if (index === group.state.privatePath.leafIndex * 2) checkAdmissionExpiry(group, node.leaf);
141
159
  }
142
- checkSurvivors(group, group.state.ratchetTree, group.registry);
160
+ checkSurvivors(group, group.state.ratchetTree, group.registry, {
161
+ kind: 'welcome'
162
+ });
143
163
  }
144
164
  /** The callback judges proposals; survivors check the path before any state is installed. */ export async function prepareLifecycleGate(params) {
145
165
  const { group, entries, candidateRegistry, context, externalLeaf } = params;
@@ -304,7 +324,10 @@ export async function validateWelcomeTree(group) {
304
324
  }
305
325
  if (incoming.kind === 'commit') checkTime(tree);
306
326
  checkSize(tree);
307
- checkSurvivors(group, tree, candidateRegistry);
327
+ checkSurvivors(group, tree, candidateRegistry, {
328
+ kind: 'commit',
329
+ before
330
+ });
308
331
  };
309
332
  const postApply = async (state)=>{
310
333
  if (incomingCommit == null || state.groupActiveState.kind === 'removedFromGroup') return;
@@ -326,7 +349,10 @@ export async function validateWelcomeTree(group) {
326
349
  }
327
350
  checkTime(state.ratchetTree);
328
351
  checkSize(state.ratchetTree);
329
- checkSurvivors(group, state.ratchetTree, candidateRegistry);
352
+ checkSurvivors(group, state.ratchetTree, candidateRegistry, {
353
+ kind: 'commit',
354
+ before
355
+ });
330
356
  };
331
357
  return {
332
358
  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
package/lib/registry.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import type { SignedEvent } from '@kokuin/controller';
1
+ import { type SignedEvent } from '@kokuin/controller';
2
2
  import type { GroupAnchor } from './anchor.js';
3
+ import type { MLSCredentialIdentity } from './credential.js';
3
4
  import type { FoldDrop, FoldInput } from './fold.js';
4
5
  import type { GroupHandle } from './group-handle.js';
5
6
  import type { VerifiedLedgerEntry } from './ledger.js';
@@ -36,7 +37,7 @@ export type Revocation = {
36
37
  reason?: 'reset';
37
38
  cascadedFrom?: string;
38
39
  };
39
- /** A folded device binding or permanent revocation. */
40
+ /** A folded device binding or revocation. Reset-only removal permits fresh admission. */
40
41
  export type DeviceRecord = {
41
42
  controller: string;
42
43
  status: 'active' | 'revoked';
@@ -77,6 +78,10 @@ export declare function isLifecycleDeviceValue(value: DeviceValue): boolean;
77
78
  * never the fold's. Lifecycle effects replay recorded DIDs without consulting a later tree.
78
79
  */
79
80
  export declare function registryApply(verified: VerifiedLedgerEntry<DeviceValue>, state: DeviceRegistry, controllerID?: string): DeviceRegistry;
81
+ /** Only reset removal without a cascade permits a later admission. */
82
+ export declare function isResetOnly(record: DeviceRecord): boolean;
83
+ /** Structural admission exception. Callers still authenticate the capability and holder grant. */
84
+ export declare function mayReadmitResetDevice(registry: DeviceRegistry, parsed: MLSCredentialIdentity): boolean;
80
85
  /** The profile a device is bound to in the folded registry, or undefined — the authority input. */
81
86
  export declare function controllerOf(registry: DeviceRegistry, deviceDID: string): string | undefined;
82
87
  /** The advisory beacon a controller last announced, or undefined. Never a validation input. */
@@ -88,9 +93,9 @@ export declare function beaconOf(registry: DeviceRegistry, controllerDID: string
88
93
  export declare function denySetOf(registry: DeviceRegistry): ReadonlySet<string>;
89
94
  /**
90
95
  * The universal rule: an ACTIVE binding resolves the issuer to its controller; anything else
91
- * resolves to the issuer itself. A revoked binding confers no authority — terminal revocation only
92
- * ever subtracts — so a revoked device re-entering as a floating leaf, or a role entry it signed
93
- * before revocation but enacted after, must not resolve to its former controller. (Note the split:
96
+ * resolves to the issuer itself. A revoked binding confers no authority until accepted re-entry.
97
+ * Floating leaves and entries enacted while revoked cannot resolve to the former controller.
98
+ * (Note the split:
94
99
  * {@link controllerOf} is the RAW lookup, deliberately status-blind, since the deviceRevoked event
95
100
  * emission and the revoke/label gate read the surviving binding of a just-revoked device.)
96
101
  */
@@ -112,5 +117,5 @@ export declare function foldControl(entries: Array<FoldInput>, anchor: GroupAnch
112
117
  roster: RosterState;
113
118
  registry: DeviceRegistry;
114
119
  };
115
- /** A permanent ledger revocation, independent of the controller's current log deny set. */
120
+ /** A ledger revocation, independent of the controller's current log deny set. */
116
121
  export declare function revocationOf(group: GroupHandle, did: string): Revocation | null;
package/lib/registry.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { foldLog } from '@kokuin/controller';
1
2
  import { normalizeDID } from '@kokuin/token';
2
3
  import { authenticateLifecycleProof } from './lifecycle-proof.js';
3
4
  import { adminCount, ROLE_ENTRY_TYPE, roleReducer } from './roster.js';
@@ -74,7 +75,8 @@ export function isLifecycleDeviceValue(value) {
74
75
  });
75
76
  for (const revoked of value.revoked ?? []){
76
77
  const did = normalizeDID(revoked.did);
77
- if (devices.get(did)?.status === 'revoked') continue;
78
+ const held = devices.get(did);
79
+ if (held?.status === 'revoked' && (value.op === 'reset' || !isResetOnly(held))) continue;
78
80
  devices.set(did, {
79
81
  controller,
80
82
  status: 'revoked',
@@ -97,11 +99,8 @@ export function isLifecycleDeviceValue(value) {
97
99
  case 'register':
98
100
  case 'add':
99
101
  {
100
- // Terminal revocation: once a subject is revoked, no later register/add re-activates it. The
101
- // fold only ever subtracts authority — to re-authorize a device, a fresh device DID is minted.
102
- // The record is left frozen at 'revoked' (the acceptance gate still verified the entry, but the
103
- // fold does not resurrect a revoked binding). Keeps determinism: every member applies this rule.
104
- if (existing?.status === 'revoked') {
102
+ // Acceptance checks fresh evidence before reactivating a reset-only binding.
103
+ if (existing?.status === 'revoked' && !isResetOnly(existing)) {
105
104
  return {
106
105
  devices,
107
106
  controllers
@@ -129,8 +128,9 @@ export function isLifecycleDeviceValue(value) {
129
128
  devices,
130
129
  controllers
131
130
  };
131
+ const { reason: _reason, ...terminal } = existing;
132
132
  devices.set(subject, {
133
- ...existing,
133
+ ...terminal,
134
134
  status: 'revoked'
135
135
  });
136
136
  return {
@@ -180,6 +180,16 @@ export function isLifecycleDeviceValue(value) {
180
180
  }
181
181
  }
182
182
  }
183
+ /** Only reset removal without a cascade permits a later admission. */ export function isResetOnly(record) {
184
+ return record.status === 'revoked' && record.reason === 'reset' && record.cascadedFrom == null;
185
+ }
186
+ /** Structural admission exception. Callers still authenticate the capability and holder grant. */ export function mayReadmitResetDevice(registry, parsed) {
187
+ const record = registry.devices.get(normalizeDID(parsed.id));
188
+ const binding = parsed.controller;
189
+ if (record == null || !isResetOnly(record) || binding == null || normalizeDID(binding.id) !== record.controller) return false;
190
+ const folded = foldLog(binding.id, binding.prefix);
191
+ return folded.ok && (folded.states.at(-1)?.gen ?? 0) >= (registry.controllers.get(record.controller)?.genFloor ?? 0);
192
+ }
183
193
  /** The profile a device is bound to in the folded registry, or undefined — the authority input. */ export function controllerOf(registry, deviceDID) {
184
194
  return registry.devices.get(normalizeDID(deviceDID))?.controller;
185
195
  }
@@ -198,9 +208,9 @@ export function isLifecycleDeviceValue(value) {
198
208
  }
199
209
  /**
200
210
  * The universal rule: an ACTIVE binding resolves the issuer to its controller; anything else
201
- * resolves to the issuer itself. A revoked binding confers no authority — terminal revocation only
202
- * ever subtracts — so a revoked device re-entering as a floating leaf, or a role entry it signed
203
- * before revocation but enacted after, must not resolve to its former controller. (Note the split:
211
+ * resolves to the issuer itself. A revoked binding confers no authority until accepted re-entry.
212
+ * Floating leaves and entries enacted while revoked cannot resolve to the former controller.
213
+ * (Note the split:
204
214
  * {@link controllerOf} is the RAW lookup, deliberately status-blind, since the deviceRevoked event
205
215
  * emission and the revoke/label gate read the surviving binding of a just-revoked device.)
206
216
  */ export function authority(registry, issuer) {
@@ -314,7 +324,7 @@ export function isLifecycleDeviceValue(value) {
314
324
  registry
315
325
  };
316
326
  }
317
- /** A permanent ledger revocation, independent of the controller's current log deny set. */ export function revocationOf(group, did) {
327
+ /** A ledger revocation, independent of the controller's current log deny set. */ export function revocationOf(group, did) {
318
328
  const record = group.registry.devices.get(normalizeDID(did));
319
329
  if (record?.status !== 'revoked' || record.logPosition === undefined) return null;
320
330
  return {
@@ -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.3",
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",