@kumiai/mls 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +29 -1
  2. package/lib/authentication.d.ts +6 -2
  3. package/lib/authentication.js +207 -51
  4. package/lib/capability.d.ts +4 -0
  5. package/lib/capability.js +22 -10
  6. package/lib/controller-ingest.d.ts +19 -0
  7. package/lib/controller-ingest.js +117 -0
  8. package/lib/controller-log.d.ts +4 -3
  9. package/lib/controller-log.js +41 -14
  10. package/lib/credential.d.ts +8 -5
  11. package/lib/credential.js +32 -3
  12. package/lib/device-proof.d.ts +5 -0
  13. package/lib/embedded-resolver.d.ts +8 -18
  14. package/lib/embedded-resolver.js +52 -24
  15. package/lib/errors.d.ts +8 -2
  16. package/lib/errors.js +11 -0
  17. package/lib/group-commit.d.ts +11 -2
  18. package/lib/group-commit.js +154 -46
  19. package/lib/group-context.d.ts +4 -2
  20. package/lib/group-context.js +30 -6
  21. package/lib/group-create.js +44 -16
  22. package/lib/group-credential.js +22 -1
  23. package/lib/group-device.js +5 -15
  24. package/lib/group-handle.d.ts +12 -1
  25. package/lib/group-handle.js +89 -12
  26. package/lib/group-lifecycle.d.ts +31 -5
  27. package/lib/group-lifecycle.js +253 -155
  28. package/lib/group-membership.js +1 -1
  29. package/lib/group-welcome.d.ts +4 -0
  30. package/lib/group-welcome.js +14 -2
  31. package/lib/history.d.ts +6 -0
  32. package/lib/history.js +20 -1
  33. package/lib/index.d.ts +12 -7
  34. package/lib/index.js +11 -6
  35. package/lib/lifecycle-proof.d.ts +15 -6
  36. package/lib/lifecycle-proof.js +195 -126
  37. package/lib/lifecycle.d.ts +9 -6
  38. package/lib/lifecycle.js +194 -84
  39. package/lib/member-root.d.ts +88 -0
  40. package/lib/member-root.js +469 -0
  41. package/lib/recovery-verdict.d.ts +1 -1
  42. package/lib/recovery-verdict.js +30 -13
  43. package/lib/registry.d.ts +17 -6
  44. package/lib/registry.js +204 -20
  45. package/lib/stale-leaf.d.ts +2 -0
  46. package/lib/stale-leaf.js +9 -4
  47. package/lib/types.d.ts +3 -0
  48. package/package.json +4 -4
package/lib/lifecycle.js CHANGED
@@ -1,18 +1,22 @@
1
+ import { decodeKey } from '@kokuin/controller';
1
2
  import { normalizeDID } from '@kokuin/token';
2
3
  import { defaultCredentialTypes, defaultProposalTypes, isDefaultCredential, isDefaultProposal, nodeTypes } from 'ts-mls';
3
4
  import { LEDGER_HEAD_EXTENSION_TYPE } from './anchor.js';
4
5
  import { checkHolderEvidence, verifyLeafCredential } from './authentication.js';
5
- import { assertCapabilityLifetime, MAX_LEAF_LIFETIME, MAX_TRUSTED_GRANT_LIFETIME, readCapability } from './capability.js';
6
- import { foldChain } from './controller-log.js';
6
+ import { assertCapabilityLifetime, capabilityKey, MAX_LEAF_LIFETIME, MAX_TRUSTED_GRANT_LIFETIME, readCapability } from './capability.js';
7
+ import { foldChain, foldControllerLog } from './controller-log.js';
7
8
  import { parseMLSCredentialIdentity } from './credential.js';
9
+ import { prefixRelation } from './embedded-resolver.js';
8
10
  import { LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
9
11
  import { assertBindingAuthorTime, makeMLSCredential } from './group-credential.js';
10
- import { decodeLedgerHead, extendHead, genesisHead, headsMatch } from './head.js';
12
+ import { registryAt } from './group-handle.js';
13
+ import { decodeLedgerHead } from './head.js';
11
14
  import { HISTORY_HORIZON, historySize } from './history.js';
12
15
  import { isEvidencedChild, verifyLifecycleProof } from './lifecycle-proof.js';
16
+ import { effectiveAttestingMembers, effectiveAuthorityOf, memberRootStatus, memberRootsOf } from './member-root.js';
13
17
  import { evaluateGroupContextExtensions } from './policy.js';
14
- import { DEVICE_ENTRY_TYPE, denySetOf, mayReadmitResetDevice } from './registry.js';
15
- import { assertNewerBinding, stalePairedAdd } from './stale-leaf.js';
18
+ import { DEVICE_ENTRY_TYPE, denySetOf, mayReadmitResetDevice, registryApply } from './registry.js';
19
+ import { assertNewerBinding, bindingIssuedAt, stalePairedAdd } from './stale-leaf.js';
16
20
  export function rejectionReason(error) {
17
21
  if (error instanceof LeafLapsedError) return 'lapse';
18
22
  if (error instanceof LeafBindingError) {
@@ -38,29 +42,87 @@ export function leafAt(tree, index) {
38
42
  const node = tree[index * 2];
39
43
  return node?.nodeType === nodeTypes.leaf ? node.leaf : undefined;
40
44
  }
41
- function attestedTime(leaf, controllerID) {
42
- const binding = identity(leaf).controller;
43
- if (binding == null || normalizeDID(binding.id) !== normalizeDID(controllerID)) return 0;
44
- const payload = readCapability(binding.capability).payload;
45
- const parent = Array.isArray(payload.cap) ? payload.cap[0] : payload.cap;
46
- return parent == null ? payload.iat : readCapability(parent).payload.iat;
47
- }
48
- function timeOf(tree, controllerID, floor) {
49
- let time = floor;
45
+ export function attestedTreeTime(tree, registry, controllerID) {
46
+ const controller = normalizeDID(controllerID);
47
+ const projection = registry.controllers.get(controller);
48
+ const folded = projection?.recordedLog == null ? undefined : foldControllerLog(controller, projection.recordedLog);
49
+ const head = folded?.ok && !folded.head.saturated ? folded.head : undefined;
50
+ const effective = new Map(effectiveAttestingMembers(head, projection));
51
+ const attestations = new Map();
52
+ for (const member of effective.values())attestations.set(member.key, projection?.attestations.get(member.key) ?? 0);
53
+ let rootTime = 0;
50
54
  for (const node of tree){
51
- if (node?.nodeType === nodeTypes.leaf) time = Math.max(time, attestedTime(node.leaf, controllerID));
55
+ if (node?.nodeType !== nodeTypes.leaf) continue;
56
+ const binding = identity(node.leaf).controller;
57
+ if (binding?.capability == null || binding.member != null || normalizeDID(binding.id) !== controller) continue;
58
+ const payload = readCapability(binding.capability).payload;
59
+ const parent = Array.isArray(payload.cap) ? payload.cap[0] : payload.cap;
60
+ const attested = parent == null ? payload : readCapability(parent).payload;
61
+ if (attested.mbr == null) {
62
+ if (normalizeDID(attested.iss) === controller) rootTime = Math.max(rootTime, attested.iat);
63
+ continue;
64
+ }
65
+ const member = effective.get(attested.mbr.add);
66
+ if (member == null || attested.mbr.g !== head?.gen || normalizeDID(member.did) !== normalizeDID(attested.iss)) continue;
67
+ attestations.set(member.key, Math.max(attestations.get(member.key) ?? 0, attested.iat));
52
68
  }
53
- return time;
69
+ const times = [
70
+ ...attestations.values()
71
+ ].sort((a, b)=>b - a);
72
+ const quorum = times.length === 1 ? times[0] : times[1];
73
+ return Math.max(projection?.timeFloor ?? 0, rootTime, quorum ?? 0);
54
74
  }
55
- export function treeTime(group, controllerID) {
56
- const floor = group.anchor.controller == null ? 0 : group.registry.controllers.get(normalizeDID(controllerID))?.timeFloor ?? 0;
57
- return timeOf(group.state.ratchetTree, controllerID, floor);
75
+ export function treeTime(group, controllerID, registry = group.registry) {
76
+ return attestedTreeTime(group.state.ratchetTree, group.anchor.controller == null ? {
77
+ ...registry,
78
+ controllers: new Map()
79
+ } : registry, controllerID);
58
80
  }
59
- export function isLapsed(group, leaf) {
81
+ export function isLapsed(group, leaf, registry = group.registry) {
60
82
  const controller = group.anchor.controller;
61
83
  if (controller == null) return false;
62
84
  const binding = identity(leaf).controller;
63
- return binding != null && readCapability(binding.capability).payload.exp < treeTime(group, controller);
85
+ const expiry = binding == null ? undefined : leafExpiry(binding, registry, controller);
86
+ return expiry != null && expiry < treeTime(group, controller, registry);
87
+ }
88
+ export function leafExpiry(binding, registry, controller) {
89
+ const did = normalizeDID(controller);
90
+ const projection = registry.controllers.get(did);
91
+ if (binding.member == null) {
92
+ if (binding.capability == null) throw new LeafBindingError('controller-mismatch');
93
+ const { payload } = readCapability(binding.capability);
94
+ const authority = effectiveAuthorityOf({
95
+ did: payload.aud,
96
+ binding,
97
+ leafKey: capabilityKey(payload).publicKey
98
+ }, registry, controller);
99
+ return 'root' in authority && authority.expiry != null ? Math.min(payload.exp, authority.expiry) : payload.exp;
100
+ }
101
+ if (normalizeDID(binding.id) !== did) return undefined;
102
+ const log = projection?.recordedLog;
103
+ if (log == null || prefixRelation(log, binding.prefix) !== 'contained') return undefined;
104
+ const folded = foldControllerLog(did, log);
105
+ if (!folded.ok) return undefined;
106
+ const member = folded.head.members.get(binding.member.add);
107
+ const memberDID = member?.did ?? projection?.removedMembers.get(binding.member.add)?.did;
108
+ if (memberDID == null) return undefined;
109
+ const survivor = projection?.survivorGrants.get(normalizeDID(memberDID));
110
+ const leafKey = member == null ? survivor == null ? undefined : capabilityKey(readCapability(survivor).payload).publicKey : decodeKey(member.key).publicKey;
111
+ if (leafKey != null) {
112
+ const authority = effectiveAuthorityOf({
113
+ did: memberDID,
114
+ binding,
115
+ leafKey
116
+ }, registry, controller);
117
+ if ('root' in authority && authority.expiry != null) return authority.expiry;
118
+ }
119
+ const status = memberRootStatus(registry, did, {
120
+ kind: 'member',
121
+ did: memberDID,
122
+ add: binding.member.add,
123
+ gen: binding.member.g
124
+ });
125
+ return status.status === 'effective' ? status.lease : undefined;
64
126
  }
65
127
  function bytesEqual(a, b) {
66
128
  return a.length === b.length && a.every((byte, index)=>byte === b[index]);
@@ -75,57 +137,87 @@ function credentialEqual(a, b) {
75
137
  */ function replacesRevokedIssuer(group, binding, old) {
76
138
  const controller = group.anchor.controller;
77
139
  if (controller == null || normalizeDID(binding.id) !== normalizeDID(controller)) return false;
140
+ if (binding.member != null || old.member != null || old.capability == null) return false;
141
+ if (binding.capability == null) throw new LeafBindingError('controller-mismatch');
78
142
  if (readCapability(binding.capability).payload.cap !== undefined) return false;
79
143
  const current = readCapability(old.capability).payload;
80
144
  return current.cap !== undefined && group.registry.devices.get(normalizeDID(current.iss))?.status === 'revoked';
81
145
  }
82
- function checkBinding(group, leaf, previous, /** The leaf arrives in a Welcome tree rather than as an entry. */ welcome = false) {
146
+ function checkBinding(group, leaf, previous, /** The leaf arrives in a Welcome tree rather than as an entry. */ welcome = false, judging = {
147
+ registry: group.registry,
148
+ stage: 'full',
149
+ mode: 'admit'
150
+ }) {
83
151
  const parsed = identity(leaf);
84
152
  const binding = parsed.controller;
85
153
  const controller = group.anchor.controller;
86
154
  if (controller != null && binding == null) throw new LeafBindingError('floating-refused');
87
155
  if (controller != null && binding != null && normalizeDID(binding.id) !== normalizeDID(controller)) throw new LeafBindingError('controller-mismatch');
88
- const denied = denySetOf(group.registry);
89
- if (denied.has(normalizeDID(parsed.id)) && !mayReadmitResetDevice(group.registry, parsed)) throw new LeafBindingError('denied-id');
90
- const record = group.registry.devices.get(normalizeDID(parsed.id));
156
+ if (controller == null && binding != null && memberRootsOf(binding, parsed.id).some(({ root })=>root.kind === 'member')) throw new LeafBindingError('controller-mismatch');
157
+ const registry = judging.registry;
158
+ const full = judging.stage === 'full';
159
+ const denied = full && registry != null ? denySetOf(registry) : new Set();
160
+ if (denied.has(normalizeDID(parsed.id)) && !mayReadmitResetDevice(registry ?? group.registry, parsed)) throw new LeafBindingError('denied-id');
161
+ const record = full ? registry?.devices.get(normalizeDID(parsed.id)) : undefined;
91
162
  if (record != null && (binding == null || normalizeDID(binding.id) !== record.controller)) throw new LeafBindingError('controller-mismatch');
92
163
  if (previous != null) {
93
164
  const old = identity(previous);
94
165
  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');
95
- 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');
166
+ if (binding != null && old.controller != null && bindingIssuedAt(binding) < bindingIssuedAt(old.controller) && !replacesRevokedIssuer(group, binding, old.controller)) throw new LeafBindingError('renewal-order');
96
167
  }
97
168
  if (binding == null) return;
98
- const payload = readCapability(binding.capability).payload;
99
169
  checkHolderEvidence(parsed, leaf.signaturePublicKey, controller == null ? MAX_TRUSTED_GRANT_LIFETIME : group.anchor.trustedGrantLifetime ?? 2_592_000);
100
- assertCapabilityLifetime(payload, controller == null ? MAX_LEAF_LIFETIME : group.anchor.leafLifetime ?? 86_400);
101
- const parent = Array.isArray(payload.cap) ? payload.cap[0] : payload.cap;
102
- if (parent != null) assertCapabilityLifetime(readCapability(parent).payload, controller == null ? MAX_TRUSTED_GRANT_LIFETIME : group.anchor.trustedGrantLifetime ?? 2_592_000);
103
- if (payload.cap != null && denied.has(normalizeDID(payload.iss)) && !(welcome && isEvidencedChild(group, leaf, denied))) throw new LeafBindingError('denied-issuer');
170
+ if (binding.member == null) {
171
+ if (binding.capability == null) throw new LeafBindingError('controller-mismatch');
172
+ const payload = readCapability(binding.capability).payload;
173
+ assertCapabilityLifetime(payload, controller == null ? MAX_LEAF_LIFETIME : group.anchor.leafLifetime ?? 86_400);
174
+ const parent = Array.isArray(payload.cap) ? payload.cap[0] : payload.cap;
175
+ if (parent != null) assertCapabilityLifetime(readCapability(parent).payload, controller == null ? MAX_TRUSTED_GRANT_LIFETIME : group.anchor.trustedGrantLifetime ?? 2_592_000);
176
+ if (payload.cap != null && denied.has(normalizeDID(payload.iss)) && !((welcome || judging.mode === 'retain') && isEvidencedChild(group, leaf, denied))) throw new LeafBindingError('denied-issuer');
177
+ }
104
178
  const folded = foldChain(binding.id, binding.prefix);
105
179
  if (!folded.ok) throw new LeafBindingError('controller-mismatch');
106
- if (controller != null && (folded.states.at(-1)?.gen ?? 0) < (group.registry.controllers.get(normalizeDID(controller))?.genFloor ?? 0)) throw new LeafBindingError('generation-floor');
180
+ if (full && controller != null && (folded.states.at(-1)?.gen ?? 0) < (registry?.controllers.get(normalizeDID(controller))?.genFloor ?? 0)) throw new LeafBindingError('generation-floor');
107
181
  }
108
- function checkAdmissionExpiry(group, leaf) {
182
+ function checkAdmissionExpiry(group, leaf, registry = group.registry) {
109
183
  const binding = identity(leaf).controller;
110
- if (binding != null && readCapability(binding.capability).payload.exp <= treeTime(group, binding.id)) throw new LeafLapsedError('lapsed');
184
+ if (binding == null) return;
185
+ const expiry = leafExpiry(binding, registry, binding.id);
186
+ if (expiry == null) throw new LeafBindingError('member-unavailable');
187
+ if (expiry <= treeTime(group, binding.id, registry)) throw new LeafLapsedError('lapsed');
111
188
  }
112
- function checkEntry(group, leaf, previous) {
113
- checkBinding(group, leaf, previous);
114
- checkAdmissionExpiry(group, leaf);
189
+ function checkEntry(group, leaf, previous, judging = {
190
+ registry: group.registry,
191
+ stage: 'full',
192
+ mode: 'admit'
193
+ }) {
194
+ checkBinding(group, leaf, previous, false, judging);
195
+ if (judging.mode === 'admit') checkAdmissionExpiry(group, leaf, judging.registry);
115
196
  }
116
- async function validateBoundLeaf(group, leaf, previous, welcome = false) {
117
- checkBinding(group, leaf, previous, welcome);
197
+ async function validateBoundLeaf(group, leaf, previous, welcome = false, judging = {
198
+ registry: group.registry,
199
+ stage: 'full',
200
+ mode: 'admit'
201
+ }) {
202
+ checkBinding(group, leaf, previous, welcome, judging);
118
203
  await verifyLeafCredential(leaf.credential, leaf.signaturePublicKey, {
119
- deviceDenySet: ()=>denySetOf(group.registry),
120
- deviceRegistry: ()=>group.anchor.controller == null ? undefined : group.registry,
121
- mayKeepDeniedIssuer: ()=>welcome && group.anchor.controller != null,
204
+ judging: ()=>({
205
+ ...judging,
206
+ registry: group.anchor.controller == null ? undefined : judging.registry
207
+ }),
208
+ deviceDenySet: ()=>judging.registry == null ? new Set() : denySetOf(judging.registry),
209
+ mayKeepDeniedIssuer: ()=>(welcome || judging.mode === 'retain') && group.anchor.controller != null,
122
210
  leafLifetime: ()=>group.anchor.controller == null ? undefined : group.anchor.leafLifetime ?? 86_400,
123
211
  trustedGrantLifetime: ()=>group.anchor.controller == null ? undefined : group.anchor.trustedGrantLifetime ?? 2_592_000
124
212
  });
125
213
  }
126
- export async function validateEntry(group, leaf, previous) {
127
- await validateBoundLeaf(group, leaf, previous);
128
- checkAdmissionExpiry(group, leaf);
214
+ export async function validateEntry(group, leaf, previous, judging = {
215
+ registry: group.registry,
216
+ stage: 'full',
217
+ mode: 'admit'
218
+ }) {
219
+ await validateBoundLeaf(group, leaf, previous, false, judging);
220
+ if (judging.mode === 'admit') checkAdmissionExpiry(group, leaf, judging.registry);
129
221
  }
130
222
  /** The same credential and key a tree already holds at that leaf index. */ export function isUnchangedLeaf(tree, index, leaf) {
131
223
  const held = leafAt(tree, index);
@@ -143,22 +235,32 @@ function checkSurvivors(group, tree, registry, origin) {
143
235
  continue;
144
236
  }
145
237
  const binding = parsed.controller;
146
- const payload = readCapability(binding.capability).payload;
147
- 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');
238
+ const payload = binding.member != null || binding.capability == null ? undefined : readCapability(binding.capability).payload;
239
+ 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');
148
240
  if (controller != null) {
149
241
  const folded = foldChain(binding.id, binding.prefix);
150
242
  if (normalizeDID(binding.id) !== normalizeDID(controller) || !folded.ok) throw new LeafBindingError('controller-mismatch');
151
243
  if ((folded.states.at(-1)?.gen ?? 0) < (registry.controllers.get(normalizeDID(controller))?.genFloor ?? 0)) throw new LeafBindingError('generation-floor');
244
+ const authority = effectiveAuthorityOf({
245
+ did: parsed.id,
246
+ binding,
247
+ leafKey: node.leaf.signaturePublicKey
248
+ }, registry, controller);
249
+ if ('status' in authority && authority.status === 'removed') throw new LeafBindingError('member-removed');
152
250
  }
153
251
  }
154
252
  }
155
- export async function validateWelcomeTree(group) {
253
+ export async function validateWelcomeTree(group, judging = {
254
+ registry: group.registry,
255
+ stage: 'full',
256
+ mode: 'rejudge'
257
+ }) {
156
258
  for (const [index, node] of group.state.ratchetTree.entries()){
157
259
  if (node?.nodeType !== nodeTypes.leaf) continue;
158
- await validateBoundLeaf(group, node.leaf, undefined, true);
159
- if (index === group.state.privatePath.leafIndex * 2) checkAdmissionExpiry(group, node.leaf);
260
+ await validateBoundLeaf(group, node.leaf, undefined, true, judging);
261
+ if (judging.stage === 'full' && index === group.state.privatePath.leafIndex * 2) checkAdmissionExpiry(group, node.leaf, judging.registry);
160
262
  }
161
- checkSurvivors(group, group.state.ratchetTree, group.registry, {
263
+ if (judging.stage === 'full') checkSurvivors(group, group.state.ratchetTree, judging.registry ?? group.registry, {
162
264
  kind: 'welcome'
163
265
  });
164
266
  }
@@ -170,7 +272,7 @@ export async function validateWelcomeTree(group) {
170
272
  if (entry.type !== DEVICE_ENTRY_TYPE) continue;
171
273
  const capability = entry.value.capability;
172
274
  const binding = group.bindingOfDID(issuer);
173
- if (capability != null && binding?.controller != null && readCapability(capability).payload.exp < treeTime(group, binding.controller)) throw new LeafLapsedError('lapsed');
275
+ if (capability != null && binding?.controller != null && readCapability(capability).payload.exp < treeTime(group, binding.controller, candidateRegistry)) throw new LeafLapsedError('lapsed');
174
276
  }
175
277
  }
176
278
  const before = group.state.ratchetTree;
@@ -186,28 +288,47 @@ export async function validateWelcomeTree(group) {
186
288
  for(let index = 0; index * 2 < before.length; index++){
187
289
  const leaf = leafAt(before, index);
188
290
  const binding = leaf == null ? undefined : identity(leaf).controller;
189
- if (binding != null && readCapability(binding.capability).payload.exp < beforeTime) lapsed.add(index);
291
+ const expiry = binding == null ? undefined : leafExpiry(binding, group.registry, controller);
292
+ if (expiry != null && expiry < beforeTime) lapsed.add(index);
190
293
  }
191
294
  }
192
295
  const opOf = ({ entry })=>entry.value.op;
193
296
  const lifecycleEntries = entries.filter((verified)=>verified.entry.type === DEVICE_ENTRY_TYPE && [
194
297
  'revoke',
195
298
  'reset',
196
- 'clock'
299
+ 'clock',
300
+ 'log',
301
+ 'seed'
302
+ ].includes(opOf(verified)));
303
+ const logs = lifecycleEntries.filter((verified)=>opOf(verified) === 'log');
304
+ if (controller != null && lifecycleEntries.some((verified)=>opOf(verified) === 'seed')) throw new RevokeProofError('detached');
305
+ const proofs = lifecycleEntries.filter((verified)=>[
306
+ 'revoke',
307
+ 'reset'
197
308
  ].includes(opOf(verified)));
198
- const proofs = lifecycleEntries.filter((verified)=>opOf(verified) !== 'clock');
199
309
  const clocks = lifecycleEntries.filter((verified)=>opOf(verified) === 'clock');
200
310
  // A proof commit enacts its proof and at most one clock, nothing else.
201
311
  const proofCarriesOtherEntries = proofs.length > 0 && entries.length !== proofs.length + clocks.length;
202
- if (controller != null && (proofs.length > 1 || clocks.length > 1 || proofCarriesOtherEntries)) throw new RevokeProofError('effects-mismatch');
312
+ if (controller != null && (proofs.length > 1 || logs.length > 1 || clocks.length > 1 || logs.length > 0 && proofs.length > 0 || proofCarriesOtherEntries)) throw new RevokeProofError('effects-mismatch');
203
313
  const expectedRemoves = new Set();
204
314
  if (controller != null) {
315
+ let registry = group.registry;
205
316
  for (const entry of lifecycleEntries){
206
- const effects = await verifyLifecycleProof(group, entry);
207
- if (opOf(entry) !== 'clock') for (const index of effects.removeLeafIndices)expectedRemoves.add(index);
317
+ const verified = entry;
318
+ const effects = await verifyLifecycleProof(group, verified, registry);
319
+ registry = registryApply(verified, registry, controller);
320
+ if ([
321
+ 'revoke',
322
+ 'reset'
323
+ ].includes(opOf(entry))) for (const index of effects.removeLeafIndices)expectedRemoves.add(index);
208
324
  }
209
325
  }
210
- if (externalLeaf != null) await validateEntry(group, externalLeaf);
326
+ const judging = (index, leaf)=>({
327
+ registry: candidateRegistry,
328
+ stage: 'full',
329
+ mode: index != null && isUnchangedLeaf(before, index, leaf) ? 'retain' : 'admit'
330
+ });
331
+ if (externalLeaf != null) await validateEntry(group, externalLeaf, undefined, judging(undefined, externalLeaf));
211
332
  let incomingCommit;
212
333
  function checkSize(tree) {
213
334
  if (controller == null) return;
@@ -216,8 +337,7 @@ export async function validateWelcomeTree(group) {
216
337
  }
217
338
  function checkTime(tree) {
218
339
  if (controller == null) return;
219
- const floor = candidateRegistry.controllers.get(normalizeDID(controller))?.timeFloor ?? 0;
220
- if (timeOf(tree, controller, floor) < beforeTime) throw new RevokeProofError('time-regression');
340
+ if (attestedTreeTime(tree, candidateRegistry, controller) < beforeTime) throw new RevokeProofError('time-regression');
221
341
  }
222
342
  function checkRegistryAdds(proposals) {
223
343
  for (const { entry } of entries){
@@ -250,7 +370,7 @@ export async function validateWelcomeTree(group) {
250
370
  if (remove == null || !isDefaultProposal(remove) || remove.proposalType !== defaultProposalTypes.remove) throw new Error('Missing replacement target');
251
371
  const old = leafAt(before, remove.remove.removed);
252
372
  if (old == null) throw new LeafBindingError('identity-change');
253
- checkEntry(group, externalLeaf, old);
373
+ checkEntry(group, externalLeaf, old, judging(remove.remove.removed, externalLeaf));
254
374
  const tree = before.slice();
255
375
  tree[remove.remove.removed * 2] = {
256
376
  nodeType: nodeTypes.leaf,
@@ -276,7 +396,7 @@ export async function validateWelcomeTree(group) {
276
396
  switch(proposal.proposalType){
277
397
  case defaultProposalTypes.add:
278
398
  {
279
- checkEntry(group, proposal.add.keyPackage.leafNode);
399
+ checkEntry(group, proposal.add.keyPackage.leafNode, undefined, judging(undefined, proposal.add.keyPackage.leafNode));
280
400
  const parsed = identity(proposal.add.keyPackage.leafNode);
281
401
  const record = candidateRegistry.devices.get(normalizeDID(parsed.id));
282
402
  if (record != null && (parsed.controller == null || normalizeDID(parsed.controller.id) !== record.controller)) throw new LeafBindingError('controller-mismatch');
@@ -290,7 +410,7 @@ export async function validateWelcomeTree(group) {
290
410
  {
291
411
  const old = sender == null ? undefined : leafAt(before, sender);
292
412
  if (old == null || sender == null) throw new LeafBindingError('identity-change');
293
- checkEntry(group, proposal.update.leafNode, old);
413
+ checkEntry(group, proposal.update.leafNode, old, judging(sender, proposal.update.leafNode));
294
414
  tree[sender * 2] = {
295
415
  nodeType: nodeTypes.leaf,
296
416
  leaf: proposal.update.leafNode
@@ -316,7 +436,7 @@ export async function validateWelcomeTree(group) {
316
436
  ]
317
437
  });
318
438
  if (replacement != null && old != null) {
319
- checkEntry(group, replacement, old);
439
+ checkEntry(group, replacement, old, judging(target, replacement));
320
440
  assertNewerBinding(replacement, old);
321
441
  }
322
442
  if (controller != null && (old == null || !(authorised || replacement != null))) throw new Error('Unauthorised Remove');
@@ -355,13 +475,15 @@ export async function validateWelcomeTree(group) {
355
475
  const old = leafAt(before, senderIndex);
356
476
  if (next != null && old != null && (!credentialEqual(next, old) || !bytesEqual(next.signaturePublicKey, old.signaturePublicKey))) {
357
477
  if (controller != null && (hasRemoves || proofs.length > 0)) throw new LeafBindingError('identity-change');
358
- await validateEntry(group, next, old);
478
+ await validateEntry(group, next, old, judging(senderIndex, next));
359
479
  }
360
480
  }
361
481
  if (controller != null && senderIndex != null) {
362
482
  const old = leafAt(before, senderIndex);
363
483
  const next = leafAt(state.ratchetTree, senderIndex);
364
- if (old != null && lapsed.has(senderIndex) && (next == null || credentialEqual(old, next) || readCapability(identity(next).controller?.capability ?? '').payload.exp < beforeTime)) throw new LeafLapsedError('lapsed');
484
+ const binding = next == null ? undefined : identity(next).controller;
485
+ const expiry = binding == null ? undefined : leafExpiry(binding, candidateRegistry, controller);
486
+ if (old != null && lapsed.has(senderIndex) && (next == null || credentialEqual(old, next) || expiry == null || expiry < treeTime(group, controller, candidateRegistry))) throw new LeafLapsedError('lapsed');
365
487
  }
366
488
  checkTime(state.ratchetTree);
367
489
  checkSize(state.ratchetTree);
@@ -375,7 +497,7 @@ export async function validateWelcomeTree(group) {
375
497
  postApply
376
498
  };
377
499
  }
378
- /** Historical messages use the tree and clock floor authenticated in their own epoch. */ export function assertSenderNotLapsed(params) {
500
+ /** Historical messages use the tree and registry authenticated in their own epoch. */ export function assertSenderNotLapsed(params) {
379
501
  const { group, tree, leafIndex, extensions } = params;
380
502
  const controller = group.anchor.controller;
381
503
  if (controller == null || leafIndex == null) return;
@@ -384,21 +506,10 @@ export async function validateWelcomeTree(group) {
384
506
  const data = extensions.find((extension)=>extension.extensionType === LEDGER_HEAD_EXTENSION_TYPE)?.extensionData;
385
507
  const expected = data instanceof Uint8Array ? decodeLedgerHead(data) : null;
386
508
  if (expected == null) throw new Error('Missing epoch ledger head');
387
- let head = genesisHead(group.groupID);
388
- let floor = 0;
389
- for (const held of group.ledger){
390
- if (headsMatch(head, expected.head)) break;
391
- head = extendHead(head, [
392
- held.entryID
393
- ]);
394
- const { entry } = held.verified;
395
- if (entry.type !== DEVICE_ENTRY_TYPE) continue;
396
- const value = entry.value;
397
- if (value.op === 'clock') floor = Math.max(floor, value.time ?? 0);
398
- }
399
- if (!headsMatch(head, expected.head)) throw new Error('Unknown epoch ledger head');
509
+ const registry = registryAt(group, expected.head);
400
510
  const binding = identity(leaf).controller;
401
- if (binding != null && readCapability(binding.capability).payload.exp < timeOf(tree, controller, floor)) throw new LeafLapsedError('lapsed');
511
+ const expiry = binding == null ? undefined : leafExpiry(binding, registry, controller);
512
+ if (expiry != null && expiry < attestedTreeTime(tree, registry, controller)) throw new LeafLapsedError('lapsed');
402
513
  }
403
514
  /** @internal Check a replacement against the complete external admission predicates. */ export async function assertRecoveryBinding(params) {
404
515
  const { group, identity: ownIdentity, controller } = params;
@@ -419,8 +530,7 @@ export async function validateWelcomeTree(group) {
419
530
  };
420
531
  const controllerID = group.anchor.controller;
421
532
  if (controllerID == null) return;
422
- const floor = group.registry.controllers.get(normalizeDID(controllerID))?.timeFloor ?? 0;
423
- if (timeOf(tree, controllerID, floor) < treeTime(group, controllerID)) throw new RevokeProofError('effects-mismatch');
533
+ if (attestedTreeTime(tree, group.registry, controllerID) < treeTime(group, controllerID)) throw new RevokeProofError('effects-mismatch');
424
534
  const ledger = group.ledger.map(({ verified })=>verified);
425
535
  const size = historySize(tree, ledger);
426
536
  if (size > HISTORY_HORIZON && size > historySize(group.state.ratchetTree, ledger)) throw new LeafBindingError('history-horizon');
@@ -0,0 +1,88 @@
1
+ import { type ControllerLog, type KeyState, type MemberState } from '@kokuin/controller';
2
+ import type { ControllerBinding } from './credential.js';
3
+ import type { ControllerProjection, DeviceRegistry, RevokedEffect } from './registry.js';
4
+ export type MemberRoot = {
5
+ kind: 'root';
6
+ controller: string;
7
+ } | {
8
+ kind: 'member';
9
+ did: string;
10
+ add: string;
11
+ gen: number;
12
+ };
13
+ export type EvidenceSlot = 'capability' | 'parent' | 'holder' | 'membership' | 'survivor';
14
+ export type ProofRef = {
15
+ chainIndex: number;
16
+ } | {
17
+ snapshot: number;
18
+ } | {
19
+ event: string;
20
+ epoch?: string;
21
+ };
22
+ export type EffectClaim = {
23
+ kind: 'deny';
24
+ did: string;
25
+ ref: ProofRef;
26
+ } | {
27
+ kind: 'remove';
28
+ member: {
29
+ did: string;
30
+ add: string;
31
+ };
32
+ ref: ProofRef;
33
+ };
34
+ export type RemovedMember = {
35
+ did: string;
36
+ gen: number;
37
+ proofRef: ProofRef;
38
+ };
39
+ export type RemovedEffect = {
40
+ did: string;
41
+ cascadedFrom: string;
42
+ };
43
+ /** Decode only; callers authenticate the tokens and membership references. */
44
+ export declare function memberRootsOf(binding: ControllerBinding, leafDID: string): Array<{
45
+ slot: EvidenceSlot;
46
+ root: MemberRoot;
47
+ }>;
48
+ export declare function effectOf(controller: string, log: ControllerLog, claim: EffectClaim, genFloor: number): void;
49
+ export declare function effectProofContext(controller: string, log: ControllerLog): {
50
+ effectOf: (claim: EffectClaim, genFloor: number) => void;
51
+ claimsFor: (recorded: ControllerLog | undefined, genFloor: number) => EffectClaim[];
52
+ };
53
+ export declare function claimsFor(controller: string, recorded: ControllerLog | undefined, merged: ControllerLog, genFloor: number): Array<EffectClaim>;
54
+ export type MemberRootStatus = {
55
+ status: 'root';
56
+ } | {
57
+ status: 'effective';
58
+ key: Uint8Array;
59
+ lease: number;
60
+ } | {
61
+ status: 'removed';
62
+ } | {
63
+ status: 'unavailable';
64
+ why: 'no-log' | 'saturated' | 'unknown-incarnation' | 'prefix';
65
+ };
66
+ export declare function effectiveAttestingMembers(head: KeyState | undefined, projection: ControllerProjection | undefined, time?: number): Array<[string, MemberState]>;
67
+ export declare function memberRootStatus(registry: DeviceRegistry, controller: string, root: MemberRoot): MemberRootStatus;
68
+ export type LeafRef = {
69
+ did: string;
70
+ binding: ControllerBinding;
71
+ leafKey: Uint8Array;
72
+ };
73
+ export declare function effectiveAuthorityOf(leaf: LeafRef, registry: DeviceRegistry, controller: string): {
74
+ root: MemberRoot;
75
+ slot: EvidenceSlot;
76
+ expiry?: number;
77
+ } | {
78
+ status: 'removed';
79
+ } | {
80
+ status: 'unavailable';
81
+ };
82
+ export declare function cascadeOf(leaves: ReadonlyArray<LeafRef & {
83
+ leafIndex: number;
84
+ }>, claims: ReadonlyArray<EffectClaim>, before: DeviceRegistry, after: DeviceRegistry, controller: string): {
85
+ revoked: Array<RevokedEffect>;
86
+ removed: Array<RemovedEffect>;
87
+ removeLeafIndices: Array<number>;
88
+ };