@kumiai/mls 0.10.0 → 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.
Files changed (53) hide show
  1. package/lib/anchor.d.ts +10 -4
  2. package/lib/anchor.js +26 -2
  3. package/lib/authentication.d.ts +24 -12
  4. package/lib/authentication.js +192 -83
  5. package/lib/capability.d.ts +37 -0
  6. package/lib/capability.js +141 -0
  7. package/lib/credential.d.ts +7 -7
  8. package/lib/credential.js +15 -10
  9. package/lib/device-proof.d.ts +2 -0
  10. package/lib/device-proof.js +8 -12
  11. package/lib/envelope-fold.d.ts +16 -1
  12. package/lib/envelope-fold.js +49 -9
  13. package/lib/errors.d.ts +18 -0
  14. package/lib/errors.js +33 -0
  15. package/lib/group-commit.d.ts +24 -35
  16. package/lib/group-commit.js +139 -110
  17. package/lib/group-context.d.ts +6 -2
  18. package/lib/group-context.js +11 -4
  19. package/lib/group-create.js +56 -11
  20. package/lib/group-credential.d.ts +3 -1
  21. package/lib/group-credential.js +17 -3
  22. package/lib/group-device.js +34 -21
  23. package/lib/group-handle.d.ts +31 -8
  24. package/lib/group-handle.js +275 -58
  25. package/lib/group-lifecycle.d.ts +49 -0
  26. package/lib/group-lifecycle.js +341 -0
  27. package/lib/group-membership.js +7 -3
  28. package/lib/group-welcome.d.ts +11 -2
  29. package/lib/group-welcome.js +122 -22
  30. package/lib/group.d.ts +2 -1
  31. package/lib/group.js +1 -0
  32. package/lib/history.d.ts +6 -0
  33. package/lib/history.js +26 -0
  34. package/lib/index.d.ts +12 -5
  35. package/lib/index.js +10 -3
  36. package/lib/lifecycle-proof.d.ts +33 -0
  37. package/lib/lifecycle-proof.js +218 -0
  38. package/lib/lifecycle.d.ts +46 -0
  39. package/lib/lifecycle.js +410 -0
  40. package/lib/policy.d.ts +20 -0
  41. package/lib/policy.js +8 -5
  42. package/lib/recovery-verdict.d.ts +43 -0
  43. package/lib/recovery-verdict.js +135 -0
  44. package/lib/recovery.d.ts +70 -0
  45. package/lib/recovery.js +110 -36
  46. package/lib/registry.d.ts +34 -7
  47. package/lib/registry.js +113 -15
  48. package/lib/roster.d.ts +1 -1
  49. package/lib/roster.js +2 -2
  50. package/lib/secret-tree.d.ts +3 -0
  51. package/lib/secret-tree.js +60 -0
  52. package/lib/types.d.ts +13 -8
  53. package/package.json +5 -5
@@ -0,0 +1,410 @@
1
+ import { foldLog } from '@kokuin/controller';
2
+ import { normalizeDID } from '@kokuin/token';
3
+ import { defaultCredentialTypes, defaultProposalTypes, isDefaultCredential, isDefaultProposal, nodeTypes } from 'ts-mls';
4
+ import { LEDGER_HEAD_EXTENSION_TYPE } from './anchor.js';
5
+ import { checkHolderEvidence, verifyLeafCredential } from './authentication.js';
6
+ import { assertCapabilityLifetime, MAX_LEAF_LIFETIME, MAX_TRUSTED_GRANT_LIFETIME, readCapability } from './capability.js';
7
+ import { parseMLSCredentialIdentity } from './credential.js';
8
+ import { LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
9
+ import { assertBindingAuthorTime, makeMLSCredential } from './group-credential.js';
10
+ import { decodeLedgerHead, extendHead, genesisHead, headsMatch } from './head.js';
11
+ import { HISTORY_HORIZON, historySize } from './history.js';
12
+ import { isEvidencedChild, verifyLifecycleProof } from './lifecycle-proof.js';
13
+ import { evaluateGroupContextExtensions } from './policy.js';
14
+ import { DEVICE_ENTRY_TYPE, denySetOf } from './registry.js';
15
+ export function rejectionReason(error) {
16
+ if (error instanceof LeafLapsedError) return 'lapse';
17
+ if (error instanceof LeafBindingError) {
18
+ if (error.reason === 'generation-floor') return 'floor';
19
+ return [
20
+ 'denied-id',
21
+ 'identity-change'
22
+ ].includes(error.reason) ? 'invalid' : 'binding';
23
+ }
24
+ if (error instanceof RevokeProofError && [
25
+ 'generation-floor',
26
+ 'time-regression'
27
+ ].includes(error.reason)) return 'floor';
28
+ return 'invalid';
29
+ }
30
+ function identity(leaf) {
31
+ if (!isDefaultCredential(leaf.credential) || leaf.credential.credentialType !== defaultCredentialTypes.basic) {
32
+ throw new LeafBindingError('identity-change');
33
+ }
34
+ return parseMLSCredentialIdentity(leaf.credential.identity);
35
+ }
36
+ export function leafAt(tree, index) {
37
+ const node = tree[index * 2];
38
+ return node?.nodeType === nodeTypes.leaf ? node.leaf : undefined;
39
+ }
40
+ function attestedTime(leaf, controllerID) {
41
+ const binding = identity(leaf).controller;
42
+ if (binding == null || normalizeDID(binding.id) !== normalizeDID(controllerID)) return 0;
43
+ const payload = readCapability(binding.capability).payload;
44
+ const parent = Array.isArray(payload.cap) ? payload.cap[0] : payload.cap;
45
+ return parent == null ? payload.iat : readCapability(parent).payload.iat;
46
+ }
47
+ function timeOf(tree, controllerID, floor) {
48
+ let time = floor;
49
+ for (const node of tree){
50
+ if (node?.nodeType === nodeTypes.leaf) time = Math.max(time, attestedTime(node.leaf, controllerID));
51
+ }
52
+ return time;
53
+ }
54
+ export function treeTime(group, controllerID) {
55
+ const floor = group.anchor.controller == null ? 0 : group.registry.controllers.get(normalizeDID(controllerID))?.timeFloor ?? 0;
56
+ return timeOf(group.state.ratchetTree, controllerID, floor);
57
+ }
58
+ export function isLapsed(group, leaf) {
59
+ const controller = group.anchor.controller;
60
+ if (controller == null) return false;
61
+ const binding = identity(leaf).controller;
62
+ return binding != null && readCapability(binding.capability).payload.exp < treeTime(group, controller);
63
+ }
64
+ function bytesEqual(a, b) {
65
+ return a.length === b.length && a.every((byte, index)=>byte === b[index]);
66
+ }
67
+ function credentialEqual(a, b) {
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
+ }
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) {
82
+ const parsed = identity(leaf);
83
+ const binding = parsed.controller;
84
+ const controller = group.anchor.controller;
85
+ if (controller != null && binding == null) throw new LeafBindingError('floating-refused');
86
+ if (controller != null && binding != null && normalizeDID(binding.id) !== normalizeDID(controller)) throw new LeafBindingError('controller-mismatch');
87
+ const denied = denySetOf(group.registry);
88
+ if (denied.has(normalizeDID(parsed.id))) throw new LeafBindingError('denied-id');
89
+ const record = group.registry.devices.get(normalizeDID(parsed.id));
90
+ if (record != null && (binding == null || normalizeDID(binding.id) !== record.controller)) throw new LeafBindingError('controller-mismatch');
91
+ if (previous != null) {
92
+ const old = identity(previous);
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');
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');
95
+ }
96
+ if (binding == null) return;
97
+ const payload = readCapability(binding.capability).payload;
98
+ checkHolderEvidence(parsed, leaf.signaturePublicKey, controller == null ? MAX_TRUSTED_GRANT_LIFETIME : group.anchor.trustedGrantLifetime ?? 2_592_000);
99
+ assertCapabilityLifetime(payload, controller == null ? MAX_LEAF_LIFETIME : group.anchor.leafLifetime ?? 86_400);
100
+ const parent = Array.isArray(payload.cap) ? payload.cap[0] : payload.cap;
101
+ if (parent != null) assertCapabilityLifetime(readCapability(parent).payload, controller == null ? MAX_TRUSTED_GRANT_LIFETIME : group.anchor.trustedGrantLifetime ?? 2_592_000);
102
+ if (payload.cap != null && denied.has(normalizeDID(payload.iss)) && !(welcome && isEvidencedChild(group, leaf, denied))) throw new LeafBindingError('denied-issuer');
103
+ const folded = foldLog(binding.id, binding.prefix);
104
+ if (!folded.ok) throw new LeafBindingError('controller-mismatch');
105
+ if (controller != null && (folded.states.at(-1)?.gen ?? 0) < (group.registry.controllers.get(normalizeDID(controller))?.genFloor ?? 0)) throw new LeafBindingError('generation-floor');
106
+ }
107
+ function checkAdmissionExpiry(group, leaf) {
108
+ const binding = identity(leaf).controller;
109
+ if (binding != null && readCapability(binding.capability).payload.exp <= treeTime(group, binding.id)) throw new LeafLapsedError('lapsed');
110
+ }
111
+ function checkEntry(group, leaf, previous) {
112
+ checkBinding(group, leaf, previous);
113
+ checkAdmissionExpiry(group, leaf);
114
+ }
115
+ async function validateBoundLeaf(group, leaf, previous, welcome = false) {
116
+ checkBinding(group, leaf, previous, welcome);
117
+ await verifyLeafCredential(leaf.credential, leaf.signaturePublicKey, {
118
+ deviceDenySet: ()=>denySetOf(group.registry),
119
+ mayKeepDeniedIssuer: ()=>welcome && group.anchor.controller != null,
120
+ leafLifetime: ()=>group.anchor.controller == null ? undefined : group.anchor.leafLifetime ?? 86_400,
121
+ trustedGrantLifetime: ()=>group.anchor.controller == null ? undefined : group.anchor.trustedGrantLifetime ?? 2_592_000
122
+ });
123
+ }
124
+ export async function validateEntry(group, leaf, previous) {
125
+ await validateBoundLeaf(group, leaf, previous);
126
+ checkAdmissionExpiry(group, leaf);
127
+ }
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) {
133
+ const denied = denySetOf(registry);
134
+ const controller = group.anchor.controller;
135
+ for (const [position, node] of tree.entries()){
136
+ if (node?.nodeType !== nodeTypes.leaf) continue;
137
+ const parsed = identity(node.leaf);
138
+ if (denied.has(normalizeDID(parsed.id))) throw new LeafBindingError('denied-id');
139
+ if (parsed.controller == null) {
140
+ if (controller != null) throw new LeafBindingError('floating-refused');
141
+ continue;
142
+ }
143
+ const binding = parsed.controller;
144
+ const payload = readCapability(binding.capability).payload;
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');
146
+ if (controller != null) {
147
+ const folded = foldLog(binding.id, binding.prefix);
148
+ if (normalizeDID(binding.id) !== normalizeDID(controller) || !folded.ok) throw new LeafBindingError('controller-mismatch');
149
+ if ((folded.states.at(-1)?.gen ?? 0) < (registry.controllers.get(normalizeDID(controller))?.genFloor ?? 0)) throw new LeafBindingError('generation-floor');
150
+ }
151
+ }
152
+ }
153
+ export async function validateWelcomeTree(group) {
154
+ for (const [index, node] of group.state.ratchetTree.entries()){
155
+ if (node?.nodeType !== nodeTypes.leaf) continue;
156
+ await validateBoundLeaf(group, node.leaf, undefined, true);
157
+ if (index === group.state.privatePath.leafIndex * 2) checkAdmissionExpiry(group, node.leaf);
158
+ }
159
+ checkSurvivors(group, group.state.ratchetTree, group.registry, {
160
+ kind: 'welcome'
161
+ });
162
+ }
163
+ /** The callback judges proposals; survivors check the path before any state is installed. */ export async function prepareLifecycleGate(params) {
164
+ const { group, entries, candidateRegistry, context, externalLeaf } = params;
165
+ const controller = group.anchor.controller;
166
+ if (controller == null) {
167
+ for (const { entry, issuer } of entries){
168
+ if (entry.type !== DEVICE_ENTRY_TYPE) continue;
169
+ const capability = entry.value.capability;
170
+ const binding = group.bindingOfDID(issuer);
171
+ if (capability != null && binding?.controller != null && readCapability(capability).payload.exp < treeTime(group, binding.controller)) throw new LeafLapsedError('lapsed');
172
+ }
173
+ }
174
+ const before = group.state.ratchetTree;
175
+ const ledger = group.ledger.map(({ verified })=>verified);
176
+ const afterLedger = [
177
+ ...ledger,
178
+ ...entries
179
+ ];
180
+ const beforeSize = controller == null ? 0 : historySize(before, ledger);
181
+ const beforeTime = controller == null ? 0 : treeTime(group, controller);
182
+ const lapsed = new Set();
183
+ if (controller != null) {
184
+ for(let index = 0; index * 2 < before.length; index++){
185
+ const leaf = leafAt(before, index);
186
+ const binding = leaf == null ? undefined : identity(leaf).controller;
187
+ if (binding != null && readCapability(binding.capability).payload.exp < beforeTime) lapsed.add(index);
188
+ }
189
+ }
190
+ const opOf = ({ entry })=>entry.value.op;
191
+ const lifecycleEntries = entries.filter((verified)=>verified.entry.type === DEVICE_ENTRY_TYPE && [
192
+ 'revoke',
193
+ 'reset',
194
+ 'clock'
195
+ ].includes(opOf(verified)));
196
+ const proofs = lifecycleEntries.filter((verified)=>opOf(verified) !== 'clock');
197
+ const clocks = lifecycleEntries.filter((verified)=>opOf(verified) === 'clock');
198
+ // A proof commit enacts its proof and at most one clock, nothing else.
199
+ const proofCarriesOtherEntries = proofs.length > 0 && entries.length !== proofs.length + clocks.length;
200
+ if (controller != null && (proofs.length > 1 || clocks.length > 1 || proofCarriesOtherEntries)) throw new RevokeProofError('effects-mismatch');
201
+ const expectedRemoves = new Set();
202
+ if (controller != null) {
203
+ for (const entry of lifecycleEntries){
204
+ const effects = await verifyLifecycleProof(group, entry);
205
+ if (opOf(entry) !== 'clock') for (const index of effects.removeLeafIndices)expectedRemoves.add(index);
206
+ }
207
+ }
208
+ if (externalLeaf != null) await validateEntry(group, externalLeaf);
209
+ let incomingCommit;
210
+ function checkSize(tree) {
211
+ if (controller == null) return;
212
+ const size = historySize(tree, afterLedger);
213
+ if (size > HISTORY_HORIZON && size > beforeSize) throw new LeafBindingError('history-horizon');
214
+ }
215
+ function checkTime(tree) {
216
+ if (controller == null) return;
217
+ const floor = candidateRegistry.controllers.get(normalizeDID(controller))?.timeFloor ?? 0;
218
+ if (timeOf(tree, controller, floor) < beforeTime) throw new RevokeProofError('time-regression');
219
+ }
220
+ function checkRegistryAdds(proposals) {
221
+ for (const { entry } of entries){
222
+ if (entry.type !== DEVICE_ENTRY_TYPE) continue;
223
+ const value = entry.value;
224
+ if (value.op !== 'register' && value.op !== 'add') continue;
225
+ const subject = normalizeDID(entry.subject);
226
+ const held = group.registry.devices.get(subject);
227
+ if (held != null && held.controller !== normalizeDID(value.controller)) throw new LeafBindingError('controller-mismatch');
228
+ const current = group.bindingOfDID(subject);
229
+ if (current != null && current.controller !== normalizeDID(value.controller)) throw new LeafBindingError('controller-mismatch');
230
+ for (const { proposal } of proposals){
231
+ if (!isDefaultProposal(proposal) || proposal.proposalType !== defaultProposalTypes.add) continue;
232
+ const parsed = identity(proposal.add.keyPackage.leafNode);
233
+ if (normalizeDID(parsed.id) === subject && (parsed.controller == null || normalizeDID(parsed.controller.id) !== normalizeDID(value.controller))) throw new LeafBindingError('controller-mismatch');
234
+ }
235
+ }
236
+ }
237
+ const check = (incoming)=>{
238
+ const proposals = incoming.kind === 'commit' ? incoming.proposals : [
239
+ incoming.proposal
240
+ ];
241
+ if (incoming.kind === 'commit') incomingCommit = incoming;
242
+ checkRegistryAdds(proposals);
243
+ const external = proposals.some(({ proposal })=>proposal.proposalType === defaultProposalTypes.external_init);
244
+ const removes = proposals.filter(({ proposal })=>isDefaultProposal(proposal) && proposal.proposalType === defaultProposalTypes.remove);
245
+ if (external) {
246
+ if (incoming.kind !== 'commit' || externalLeaf == null || proposals.length !== 2 || removes.length !== 1) throw new Error('Invalid external replacement');
247
+ const remove = removes[0]?.proposal;
248
+ if (remove == null || !isDefaultProposal(remove) || remove.proposalType !== defaultProposalTypes.remove) throw new Error('Missing replacement target');
249
+ const old = leafAt(before, remove.remove.removed);
250
+ if (old == null) throw new LeafBindingError('identity-change');
251
+ checkEntry(group, externalLeaf, old);
252
+ const tree = before.slice();
253
+ tree[remove.remove.removed * 2] = {
254
+ nodeType: nodeTypes.leaf,
255
+ leaf: externalLeaf
256
+ };
257
+ checkTime(tree);
258
+ checkSize(tree);
259
+ return;
260
+ }
261
+ if (controller != null && proofs.length > 0) {
262
+ const actual = removes.map(({ proposal })=>isDefaultProposal(proposal) && proposal.proposalType === defaultProposalTypes.remove ? proposal.remove.removed : -1);
263
+ if (actual.length !== expectedRemoves.size || new Set(actual).size !== expectedRemoves.size || actual.some((index)=>!expectedRemoves.has(index))) throw new RevokeProofError('removes-mismatch');
264
+ if (incoming.kind !== 'commit' || incoming.senderLeafIndex == null || expectedRemoves.has(incoming.senderLeafIndex)) throw new RevokeProofError('effects-mismatch');
265
+ }
266
+ const tree = before.slice();
267
+ for (const { proposal, senderLeafIndex: proposalSender } of proposals){
268
+ if (!isDefaultProposal(proposal)) {
269
+ if (controller != null) throw new Error('Unsupported lifecycle proposal');
270
+ continue;
271
+ }
272
+ const sender = proposalSender ?? (incoming.kind === 'commit' ? incoming.senderLeafIndex : undefined);
273
+ if (controller != null && proofs.length > 0 && proposal.proposalType !== defaultProposalTypes.remove && proposal.proposalType !== defaultProposalTypes.group_context_extensions) throw new RevokeProofError('effects-mismatch');
274
+ switch(proposal.proposalType){
275
+ case defaultProposalTypes.add:
276
+ {
277
+ checkEntry(group, proposal.add.keyPackage.leafNode);
278
+ const parsed = identity(proposal.add.keyPackage.leafNode);
279
+ const record = candidateRegistry.devices.get(normalizeDID(parsed.id));
280
+ if (record != null && (parsed.controller == null || normalizeDID(parsed.controller.id) !== record.controller)) throw new LeafBindingError('controller-mismatch');
281
+ tree.push({
282
+ nodeType: nodeTypes.leaf,
283
+ leaf: proposal.add.keyPackage.leafNode
284
+ });
285
+ break;
286
+ }
287
+ case defaultProposalTypes.update:
288
+ {
289
+ const old = sender == null ? undefined : leafAt(before, sender);
290
+ if (old == null || sender == null) throw new LeafBindingError('identity-change');
291
+ checkEntry(group, proposal.update.leafNode, old);
292
+ tree[sender * 2] = {
293
+ nodeType: nodeTypes.leaf,
294
+ leaf: proposal.update.leafNode
295
+ };
296
+ break;
297
+ }
298
+ case defaultProposalTypes.remove:
299
+ {
300
+ const target = proposal.remove.removed;
301
+ const old = leafAt(before, target);
302
+ // A self-removal proposal is honoured only when another member commits it.
303
+ const selfRemoval = proposalSender === target && (incoming.kind === 'proposal' || incoming.senderLeafIndex !== target);
304
+ const authorised = proofs.length > 0 || lapsed.has(target) || selfRemoval;
305
+ if (controller != null && (old == null || !authorised)) throw new Error('Unauthorised Remove');
306
+ tree[target * 2] = undefined;
307
+ break;
308
+ }
309
+ case defaultProposalTypes.group_context_extensions:
310
+ if (evaluateGroupContextExtensions(proposal.groupContextExtensions.extensions, context) === 'reject') throw new Error('Invalid extensions');
311
+ break;
312
+ default:
313
+ if (controller != null) throw new Error('Unsupported lifecycle proposal');
314
+ }
315
+ }
316
+ if (incoming.kind === 'commit' && context.commitEnactsEntries && !proposals.some(({ proposal })=>proposal.proposalType === defaultProposalTypes.group_context_extensions)) throw new Error('Missing head move');
317
+ if (controller != null && incoming.kind === 'commit' && incoming.senderLeafIndex != null) {
318
+ const sender = leafAt(before, incoming.senderLeafIndex);
319
+ // A lapsed sender may only commit clock entries and the head move they need.
320
+ const changesMoreThanHead = proposals.some(({ proposal })=>proposal.proposalType !== defaultProposalTypes.group_context_extensions);
321
+ const enactsNonClock = entries.some((verified)=>verified.entry.type !== DEVICE_ENTRY_TYPE || opOf(verified) !== 'clock');
322
+ if (sender != null && lapsed.has(incoming.senderLeafIndex) && (changesMoreThanHead || enactsNonClock)) throw new LeafLapsedError('lapsed');
323
+ }
324
+ if (incoming.kind === 'commit') checkTime(tree);
325
+ checkSize(tree);
326
+ checkSurvivors(group, tree, candidateRegistry, {
327
+ kind: 'commit',
328
+ before
329
+ });
330
+ };
331
+ const postApply = async (state)=>{
332
+ if (incomingCommit == null || state.groupActiveState.kind === 'removedFromGroup') return;
333
+ const external = incomingCommit.senderLeafIndex == null;
334
+ const senderIndex = incomingCommit.senderLeafIndex;
335
+ const hasRemoves = incomingCommit.proposals.some(({ proposal })=>proposal.proposalType === defaultProposalTypes.remove);
336
+ if (!external && senderIndex != null) {
337
+ const next = leafAt(state.ratchetTree, senderIndex);
338
+ const old = leafAt(before, senderIndex);
339
+ if (next != null && old != null && (!credentialEqual(next, old) || !bytesEqual(next.signaturePublicKey, old.signaturePublicKey))) {
340
+ if (controller != null && (hasRemoves || proofs.length > 0)) throw new LeafBindingError('identity-change');
341
+ await validateEntry(group, next, old);
342
+ }
343
+ }
344
+ if (controller != null && senderIndex != null) {
345
+ const old = leafAt(before, senderIndex);
346
+ const next = leafAt(state.ratchetTree, senderIndex);
347
+ if (old != null && lapsed.has(senderIndex) && (next == null || credentialEqual(old, next) || readCapability(identity(next).controller?.capability ?? '').payload.exp < beforeTime)) throw new LeafLapsedError('lapsed');
348
+ }
349
+ checkTime(state.ratchetTree);
350
+ checkSize(state.ratchetTree);
351
+ checkSurvivors(group, state.ratchetTree, candidateRegistry, {
352
+ kind: 'commit',
353
+ before
354
+ });
355
+ };
356
+ return {
357
+ check,
358
+ postApply
359
+ };
360
+ }
361
+ /** Historical messages use the tree and clock floor authenticated in their own epoch. */ export function assertSenderNotLapsed(params) {
362
+ const { group, tree, leafIndex, extensions } = params;
363
+ const controller = group.anchor.controller;
364
+ if (controller == null || leafIndex == null) return;
365
+ const leaf = leafAt(tree, leafIndex);
366
+ if (leaf == null) return;
367
+ const data = extensions.find((extension)=>extension.extensionType === LEDGER_HEAD_EXTENSION_TYPE)?.extensionData;
368
+ const expected = data instanceof Uint8Array ? decodeLedgerHead(data) : null;
369
+ if (expected == null) throw new Error('Missing epoch ledger head');
370
+ let head = genesisHead(group.groupID);
371
+ let floor = 0;
372
+ for (const held of group.ledger){
373
+ if (headsMatch(head, expected.head)) break;
374
+ head = extendHead(head, [
375
+ held.entryID
376
+ ]);
377
+ const { entry } = held.verified;
378
+ if (entry.type !== DEVICE_ENTRY_TYPE) continue;
379
+ const value = entry.value;
380
+ if (value.op === 'clock') floor = Math.max(floor, value.time ?? 0);
381
+ }
382
+ if (!headsMatch(head, expected.head)) throw new Error('Unknown epoch ledger head');
383
+ const binding = identity(leaf).controller;
384
+ if (binding != null && readCapability(binding.capability).payload.exp < timeOf(tree, controller, floor)) throw new LeafLapsedError('lapsed');
385
+ }
386
+ /** @internal Check a replacement against the complete external admission predicates. */ export async function assertRecoveryBinding(params) {
387
+ const { group, identity: ownIdentity, controller } = params;
388
+ assertBindingAuthorTime(controller);
389
+ const index = group.findMemberLeafIndex(normalizeDID(ownIdentity.id));
390
+ const old = index == null ? undefined : leafAt(group.state.ratchetTree, index);
391
+ if (old == null || index == null) throw new LeafBindingError('identity-change');
392
+ const leaf = {
393
+ ...old,
394
+ signaturePublicKey: ownIdentity.publicKey,
395
+ credential: makeMLSCredential(ownIdentity, controller)
396
+ };
397
+ await validateEntry(group, leaf, old);
398
+ const tree = group.state.ratchetTree.slice();
399
+ tree[index * 2] = {
400
+ nodeType: nodeTypes.leaf,
401
+ leaf
402
+ };
403
+ const controllerID = group.anchor.controller;
404
+ if (controllerID == null) return;
405
+ const floor = group.registry.controllers.get(normalizeDID(controllerID))?.timeFloor ?? 0;
406
+ if (timeOf(tree, controllerID, floor) < treeTime(group, controllerID)) throw new RevokeProofError('effects-mismatch');
407
+ const ledger = group.ledger.map(({ verified })=>verified);
408
+ const size = historySize(tree, ledger);
409
+ if (size > HISTORY_HORIZON && size > historySize(group.state.ratchetTree, ledger)) throw new LeafBindingError('history-horizon');
410
+ }
package/lib/policy.d.ts CHANGED
@@ -55,6 +55,26 @@ type IncomingMessage = {
55
55
  kind: 'proposal';
56
56
  proposal: ProposalWithSender;
57
57
  };
58
+ /**
59
+ * The group-context-extensions rule: an admin may replace the extension list only to move the
60
+ * ledger-head to the head this commit's envelope accounts for, or to also install
61
+ * {@link RESERVED_EXTENSION_TYPE} empty in a standard group. Lifecycle groups permit only the
62
+ * head move. A GCE proposal replaces the *entire* list, so the
63
+ * proposed list must positionally equal the current one — same length, types, positions,
64
+ * byte-identical data — except the ledger_head entry (must equal the expected head) and at
65
+ * most one added `RESERVED_EXTENSION_TYPE` entry with empty data. This pins every other
66
+ * extension, so an admin can't inject or strip one (e.g. external_senders, which lets a
67
+ * non-member inject proposals) inside a head move, nor install the reserved type with
68
+ * non-empty data — it isn't consumed by anything yet, so no policy exists for its data.
69
+ *
70
+ * The head must equal the current head extended by the envelope's entry ids in order; moved to
71
+ * anything else, or moved by a commit enacting nothing, and it stops proving what the group
72
+ * enacted.
73
+ */
74
+ export declare function evaluateGroupContextExtensions(extensions: Array<{
75
+ extensionType: number;
76
+ extensionData: unknown;
77
+ }>, context: CommitPolicyContext): IncomingMessageAction;
58
78
  /**
59
79
  * Pure receiving-side commit policy: given the resolved context, decides whether an incoming
60
80
  * commit or standalone proposal is admissible. Never throws.
package/lib/policy.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
2
  import { defaultProposalTypes, isDefaultProposal } from 'ts-mls';
3
- import { LEDGER_HEAD_EXTENSION_TYPE, RESERVED_EXTENSION_TYPE } from './anchor.js';
3
+ import { decodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, LEDGER_HEAD_EXTENSION_TYPE, RESERVED_EXTENSION_TYPE } from './anchor.js';
4
4
  import { didFromCredential } from './credential.js';
5
5
  function bytesEqual(a, b) {
6
6
  if (a.length !== b.length) {
@@ -42,7 +42,8 @@ function bytesEqual(a, b) {
42
42
  /**
43
43
  * The group-context-extensions rule: an admin may replace the extension list only to move the
44
44
  * ledger-head to the head this commit's envelope accounts for, or to also install
45
- * {@link RESERVED_EXTENSION_TYPE} empty. A GCE proposal replaces the *entire* list, so the
45
+ * {@link RESERVED_EXTENSION_TYPE} empty in a standard group. Lifecycle groups permit only the
46
+ * head move. A GCE proposal replaces the *entire* list, so the
46
47
  * proposed list must positionally equal the current one — same length, types, positions,
47
48
  * byte-identical data — except the ledger_head entry (must equal the expected head) and at
48
49
  * most one added `RESERVED_EXTENSION_TYPE` entry with empty data. This pins every other
@@ -53,7 +54,7 @@ function bytesEqual(a, b) {
53
54
  * The head must equal the current head extended by the envelope's entry ids in order; moved to
54
55
  * anything else, or moved by a commit enacting nothing, and it stops proving what the group
55
56
  * enacted.
56
- */ function evaluateGroupContextExtensions(extensions, context) {
57
+ */ export function evaluateGroupContextExtensions(extensions, context) {
57
58
  const expected = context.currentExtensions.map((ext)=>ext.extensionType === LEDGER_HEAD_EXTENSION_TYPE ? {
58
59
  extensionType: LEDGER_HEAD_EXTENSION_TYPE,
59
60
  extensionData: context.expectedHeadExtensionData
@@ -64,7 +65,9 @@ function bytesEqual(a, b) {
64
65
  // rejected as before.
65
66
  let candidate = extensions;
66
67
  const reservedAlreadyInstalled = expected.some((ext)=>ext.extensionType === RESERVED_EXTENSION_TYPE);
67
- if (!reservedAlreadyInstalled && extensions.length === expected.length + 1) {
68
+ const anchorData = expected.find((ext)=>ext.extensionType === GROUP_ANCHOR_EXTENSION_TYPE)?.extensionData;
69
+ const lifecycle = anchorData instanceof Uint8Array && decodeGroupAnchor(anchorData)?.controller != null;
70
+ if (!lifecycle && !reservedAlreadyInstalled && extensions.length === expected.length + 1) {
68
71
  const reservedIndex = extensions.findIndex((ext)=>{
69
72
  return ext.extensionType === RESERVED_EXTENSION_TYPE && ext.extensionData instanceof Uint8Array && ext.extensionData.length === 0;
70
73
  });
@@ -108,7 +111,7 @@ function bytesEqual(a, b) {
108
111
  // A credential that names no DID (non-`basic`, or malformed) is rejected rather than
109
112
  // trusted. `didFromCredential` is total, so nothing here can throw past this boundary.
110
113
  const addedDID = didFromCredential(proposal.add.keyPackage.leafNode.credential);
111
- if (addedDID === undefined) {
114
+ if (addedDID === null) {
112
115
  return 'reject';
113
116
  }
114
117
  // Bind the leaf that joins to the roster this commit produces, mirroring the binding
@@ -0,0 +1,43 @@
1
+ import { type SigningIdentity } from '@kokuin/token';
2
+ import type { GroupHandle } from './group-handle.js';
3
+ import { type OpenSealedGroupInfoParams } from './recovery.js';
4
+ import type { DeviceRegistry } from './registry.js';
5
+ export type RecoveryRefusalReason = 'binding' | 'lapse' | 'floor' | 'policy' | 'invalid';
6
+ export type RecoveryVerdict = {
7
+ groupID: string;
8
+ requestID: string;
9
+ position: string;
10
+ commitDigest: string;
11
+ } & ({
12
+ verdict: 'confirmed';
13
+ epoch: number;
14
+ tag: string;
15
+ } | {
16
+ verdict: 'superseded';
17
+ } | {
18
+ verdict: 'refused';
19
+ reason: RecoveryRefusalReason;
20
+ });
21
+ export type OpenedRecoveryVerdict = {
22
+ signer: string;
23
+ verdict: RecoveryVerdict;
24
+ };
25
+ export declare function confirmationKey(group: GroupHandle, position: string, commitDigest: string): Promise<Uint8Array>;
26
+ export declare function confirmationTag(key: Uint8Array, requestID: string): string;
27
+ export type SealRecoveryVerdictParams = {
28
+ group: GroupHandle;
29
+ identity: SigningIdentity;
30
+ /** The signed recovery request token being answered. */
31
+ request: string;
32
+ verdict: RecoveryVerdict;
33
+ };
34
+ export declare function sealRecoveryVerdict(params: SealRecoveryVerdictParams): Promise<Uint8Array>;
35
+ export declare function openRecoveryVerdict(params: OpenSealedGroupInfoParams): Promise<OpenedRecoveryVerdict>;
36
+ export type RecoverySignerEligibleParams = {
37
+ group: GroupHandle;
38
+ known: DeviceRegistry;
39
+ signer: string;
40
+ /** Seconds since epoch; defaults to the current time. */
41
+ now?: number;
42
+ };
43
+ export declare function recoverySignerEligible(params: RecoverySignerEligibleParams): boolean;
@@ -0,0 +1,135 @@
1
+ import { foldLog } from '@kokuin/controller';
2
+ import { encodeMultibase, isVerifiedToken, normalizeDID, stringifyToken, verifyToken } from '@kokuin/token';
3
+ import { hmac } from '@noble/hashes/hmac.js';
4
+ import { sha256 } from '@noble/hashes/sha2.js';
5
+ import { readCapability } from './capability.js';
6
+ import { openSealedReply, sealToRequest, verifyRecoveryRequest } from './recovery.js';
7
+ const utf8 = new TextEncoder();
8
+ const VERDICT_TYPE = 'kumiai.recovery-verdict';
9
+ const VERDICT_REPLY = {
10
+ hpkeInfo: utf8.encode('kumiai/mls/recovery-verdict/v1'),
11
+ aadDomain: utf8.encode('kumiai/mls/recovery-verdict-aad/v1'),
12
+ version: 1,
13
+ fail: (_reason, message, options)=>new Error(message, options)
14
+ };
15
+ function frame(value) {
16
+ const bytes = utf8.encode(value);
17
+ const out = new Uint8Array(4 + bytes.length);
18
+ new DataView(out.buffer).setUint32(0, bytes.length, false);
19
+ out.set(bytes, 4);
20
+ return out;
21
+ }
22
+ export async function confirmationKey(group, position, commitDigest) {
23
+ const fields = [
24
+ group.groupID,
25
+ position,
26
+ commitDigest
27
+ ].map(frame);
28
+ const context = new Uint8Array(fields.reduce((size, field)=>size + field.length, 0));
29
+ let offset = 0;
30
+ for (const field of fields){
31
+ context.set(field, offset);
32
+ offset += field.length;
33
+ }
34
+ return await group.exportSecret('kumiai.rejoin-confirm', context, 32);
35
+ }
36
+ export function confirmationTag(key, requestID) {
37
+ return encodeMultibase(hmac(sha256, key, utf8.encode(requestID)));
38
+ }
39
+ function isRecoveryVerdict(value) {
40
+ if (value == null || typeof value !== 'object') return false;
41
+ const v = value;
42
+ if (![
43
+ v.groupID,
44
+ v.requestID,
45
+ v.position,
46
+ v.commitDigest
47
+ ].every((field)=>typeof field === 'string' && field.length > 0)) return false;
48
+ return v.verdict === 'superseded' || v.verdict === 'confirmed' && Number.isSafeInteger(v.epoch) && v.epoch >= 0 && typeof v.tag === 'string' || v.verdict === 'refused' && [
49
+ 'binding',
50
+ 'lapse',
51
+ 'floor',
52
+ 'policy',
53
+ 'invalid'
54
+ ].includes(v.reason);
55
+ }
56
+ export async function sealRecoveryVerdict(params) {
57
+ const { group, identity, request, verdict } = params;
58
+ const verified = await verifyRecoveryRequest(request);
59
+ if (normalizeDID(identity.id) !== normalizeDID(group.credential.id) || !isRecoveryVerdict(verdict) || verdict.groupID !== group.groupID || verdict.groupID !== verified.groupID || verdict.requestID !== verified.requestID) throw new Error('Recovery verdict does not bind the signed request');
60
+ const token = await identity.signToken({
61
+ ...verdict,
62
+ type: VERDICT_TYPE
63
+ }, {
64
+ embedLongForm: true
65
+ });
66
+ // A refusal can answer an agent whose leaf the responder no longer holds.
67
+ return await sealToRequest({
68
+ kind: VERDICT_REPLY,
69
+ group,
70
+ request,
71
+ plaintext: utf8.encode(stringifyToken(token)),
72
+ requireMember: false
73
+ });
74
+ }
75
+ export async function openRecoveryVerdict(params) {
76
+ const { group, sealed, requestID, ephemeralPrivateKey } = params;
77
+ const plaintext = await openSealedReply({
78
+ kind: VERDICT_REPLY,
79
+ group,
80
+ sealed,
81
+ requestID,
82
+ ephemeralPrivateKey
83
+ });
84
+ const token = await verifyToken(new TextDecoder().decode(plaintext));
85
+ if (!isVerifiedToken(token) || token.payload.type !== VERDICT_TYPE || !isRecoveryVerdict(token.payload) || token.payload.groupID !== group.groupID || token.payload.requestID !== requestID) throw new Error('Unauthenticated recovery verdict');
86
+ const { groupID, position, commitDigest } = token.payload;
87
+ const binding = {
88
+ groupID,
89
+ requestID,
90
+ position,
91
+ commitDigest
92
+ };
93
+ const verdict = token.payload.verdict === 'confirmed' ? {
94
+ ...binding,
95
+ verdict: 'confirmed',
96
+ epoch: token.payload.epoch,
97
+ tag: token.payload.tag
98
+ } : token.payload.verdict === 'refused' ? {
99
+ ...binding,
100
+ verdict: 'refused',
101
+ reason: token.payload.reason
102
+ } : {
103
+ ...binding,
104
+ verdict: 'superseded'
105
+ };
106
+ return {
107
+ signer: normalizeDID(token.payload.iss),
108
+ verdict
109
+ };
110
+ }
111
+ export function recoverySignerEligible(params) {
112
+ const { group, known, signer, now = Date.now() / 1000 } = params;
113
+ const controller = group.anchor.controller;
114
+ if (controller == null) return false;
115
+ try {
116
+ const binding = group.bindingOfDID(signer);
117
+ if (binding?.controller !== controller || binding.capability == null || binding.prefix == null) return false;
118
+ const payload = readCapability(binding.capability).payload;
119
+ if (known.devices.get(normalizeDID(signer))?.status === 'revoked' || payload.cap != null && known.devices.get(normalizeDID(payload.iss))?.status === 'revoked') return false;
120
+ const folded = foldLog(controller, binding.prefix);
121
+ const projection = known.controllers.get(normalizeDID(controller));
122
+ if (!folded.ok || (folded.states.at(-1)?.gen ?? 0) < (projection?.genFloor ?? 0)) return false;
123
+ let time = projection?.timeFloor ?? 0;
124
+ for (const member of group.listMembers()){
125
+ const leaf = group.bindingOfDID(member.id);
126
+ if (leaf?.controller !== controller || leaf.capability == null) continue;
127
+ const capability = readCapability(leaf.capability).payload;
128
+ const parent = Array.isArray(capability.cap) ? capability.cap[0] : capability.cap;
129
+ time = Math.max(time, parent == null ? capability.iat : readCapability(parent).payload.iat);
130
+ }
131
+ return payload.exp >= Math.max(time, now - 300);
132
+ } catch {
133
+ return false;
134
+ }
135
+ }