@kumiai/mls 0.12.4 → 0.13.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 (64) hide show
  1. package/lib/anchor.d.ts +6 -2
  2. package/lib/anchor.js +1 -1
  3. package/lib/authentication.d.ts +8 -3
  4. package/lib/authentication.js +139 -46
  5. package/lib/capability.js +16 -7
  6. package/lib/controller-ingest.d.ts +14 -2
  7. package/lib/controller-ingest.js +15 -8
  8. package/lib/controller-log.d.ts +12 -6
  9. package/lib/controller-log.js +29 -15
  10. package/lib/device-proof.d.ts +2 -1
  11. package/lib/device-proof.js +2 -1
  12. package/lib/embedded-resolver.d.ts +7 -2
  13. package/lib/embedded-resolver.js +16 -6
  14. package/lib/envelope-fold.d.ts +3 -2
  15. package/lib/envelope-fold.js +14 -6
  16. package/lib/fold.d.ts +17 -3
  17. package/lib/fold.js +9 -3
  18. package/lib/group-commit.d.ts +11 -2
  19. package/lib/group-commit.js +76 -32
  20. package/lib/group-context.d.ts +3 -2
  21. package/lib/group-context.js +6 -2
  22. package/lib/group-create.d.ts +5 -1
  23. package/lib/group-create.js +36 -14
  24. package/lib/group-credential.d.ts +13 -3
  25. package/lib/group-credential.js +17 -6
  26. package/lib/group-device.d.ts +32 -22
  27. package/lib/group-device.js +66 -51
  28. package/lib/group-handle.d.ts +84 -30
  29. package/lib/group-handle.js +368 -154
  30. package/lib/group-lifecycle.d.ts +44 -11
  31. package/lib/group-lifecycle.js +193 -85
  32. package/lib/group-membership.d.ts +6 -1
  33. package/lib/group-membership.js +2 -2
  34. package/lib/group-welcome.d.ts +5 -1
  35. package/lib/group-welcome.js +34 -10
  36. package/lib/head.d.ts +25 -5
  37. package/lib/head.js +17 -8
  38. package/lib/history.d.ts +14 -3
  39. package/lib/history.js +8 -5
  40. package/lib/index.d.ts +27 -1
  41. package/lib/key-package-codec.d.ts +4 -1
  42. package/lib/key-package-codec.js +1 -1
  43. package/lib/ledger.d.ts +14 -6
  44. package/lib/ledger.js +56 -19
  45. package/lib/lifecycle-proof.d.ts +5 -4
  46. package/lib/lifecycle-proof.js +111 -51
  47. package/lib/lifecycle.d.ts +18 -9
  48. package/lib/lifecycle.js +184 -81
  49. package/lib/member-root.d.ts +54 -15
  50. package/lib/member-root.js +115 -53
  51. package/lib/policy.d.ts +5 -1
  52. package/lib/policy.js +1 -1
  53. package/lib/recovery-verdict.d.ts +12 -3
  54. package/lib/recovery-verdict.js +56 -22
  55. package/lib/recovery.d.ts +20 -5
  56. package/lib/recovery.js +117 -46
  57. package/lib/registry.d.ts +46 -10
  58. package/lib/registry.js +64 -38
  59. package/lib/roster.d.ts +7 -1
  60. package/lib/roster.js +18 -7
  61. package/lib/secret-tree.d.ts +5 -1
  62. package/lib/secret-tree.js +1 -1
  63. package/lib/types.d.ts +3 -0
  64. package/package.json +9 -5
package/lib/recovery.js CHANGED
@@ -25,18 +25,26 @@ const GROUP_INFO_REPLY = {
25
25
  hpkeInfo: utf8.encode('kumiai/mls/recovery/v1'),
26
26
  aadDomain: utf8.encode('kumiai/mls/recovery-aad/v1'),
27
27
  version: SEALED_GROUP_INFO_VERSION,
28
- fail: (reason, message, options)=>new SealedGroupInfoError(reason, message, options)
28
+ fail: (reason, message, options)=>new SealedGroupInfoError({
29
+ reason,
30
+ message,
31
+ ...options
32
+ })
29
33
  };
30
34
  const LEDGER_REPLY = {
31
35
  hpkeInfo: utf8.encode('kumiai/mls/recovery-ledger/v1'),
32
36
  aadDomain: utf8.encode('kumiai/mls/recovery-ledger-aad/v1'),
33
37
  version: SEALED_LEDGER_VERSION,
34
- fail: (reason, message, options)=>new SealedLedgerError(reason, message, options)
38
+ fail: (reason, message, options)=>new SealedLedgerError({
39
+ reason,
40
+ message,
41
+ ...options
42
+ })
35
43
  };
36
44
  /** Thrown by {@link sealGroupInfo}. The primitive refuses loudly rather than
37
45
  * returning an empty reply; a responder that wants to stay silent catches this. */ export class RecoveryRequestError extends Error {
38
46
  #reason;
39
- constructor(reason, message, options){
47
+ constructor({ reason, message, ...options }){
40
48
  super(message, options);
41
49
  this.name = 'RecoveryRequestError';
42
50
  this.#reason = reason;
@@ -48,7 +56,7 @@ const LEDGER_REPLY = {
48
56
  /** Thrown by {@link openSealedGroupInfo}. Distinguishes "not addressed to me" from
49
57
  * "corrupt", so a peer sifting a shared lane drops the former quietly. */ export class SealedGroupInfoError extends Error {
50
58
  #reason;
51
- constructor(reason, message, options){
59
+ constructor({ reason, message, ...options }){
52
60
  super(message, options);
53
61
  this.name = 'SealedGroupInfoError';
54
62
  this.#reason = reason;
@@ -61,7 +69,7 @@ const LEDGER_REPLY = {
61
69
  * sifting a shared lane drops `not-for-me` quietly (every other member's reply to
62
70
  * every other request looks like this) and shouts about `malformed`. */ export class SealedLedgerError extends Error {
63
71
  #reason;
64
- constructor(reason, message, options){
72
+ constructor({ reason, message, ...options }){
65
73
  super(message, options);
66
74
  this.name = 'SealedLedgerError';
67
75
  this.#reason = reason;
@@ -153,34 +161,50 @@ function unframeAttestedGroupInfo(bytes, lifecycle) {
153
161
  * rejected: `verifyToken` returns them unchecked, so their `iss` is
154
162
  * attacker-chosen. `embedLongForm` lets it verify offline — a responder needs no
155
163
  * DID resolver to answer.
156
- */ export async function verifyRecoveryRequest(token) {
164
+ */ export async function verifyRecoveryRequest({ token, ...options }) {
157
165
  let verified;
158
166
  try {
159
- verified = await verifyToken(token);
167
+ verified = await verifyToken({
168
+ ...options,
169
+ token: token
170
+ });
160
171
  } catch (cause) {
161
172
  // biome-ignore lint/style/useErrorCause: cause IS passed; the rule only reads argument 1, and these take (reason, message, options).
162
- throw new RecoveryRequestError('unverified', 'recovery request signature did not verify', {
173
+ throw new RecoveryRequestError({
174
+ reason: 'unverified',
175
+ message: 'recovery request signature did not verify',
163
176
  cause
164
177
  });
165
178
  }
166
179
  if (!isVerifiedToken(verified)) {
167
- throw new RecoveryRequestError('unverified', 'recovery request is not signed');
180
+ throw new RecoveryRequestError({
181
+ reason: 'unverified',
182
+ message: 'recovery request is not signed'
183
+ });
168
184
  }
169
185
  const { iss, type, groupID, requestID, ephemeralKey } = verified.payload;
170
186
  if (type !== RECOVERY_REQUEST_TYPE || typeof groupID !== 'string' || typeof requestID !== 'string' || typeof ephemeralKey !== 'string') {
171
- throw new RecoveryRequestError('malformed', 'recovery request payload is malformed');
187
+ throw new RecoveryRequestError({
188
+ reason: 'malformed',
189
+ message: 'recovery request payload is malformed'
190
+ });
172
191
  }
173
192
  let ephemeralPublicKey;
174
193
  try {
175
194
  ephemeralPublicKey = decodeMultibase(ephemeralKey);
176
195
  } catch (cause) {
177
196
  // biome-ignore lint/style/useErrorCause: cause IS passed; the rule only reads argument 1, and these take (reason, message, options).
178
- throw new RecoveryRequestError('malformed', 'recovery request ephemeral key is not multibase', {
197
+ throw new RecoveryRequestError({
198
+ reason: 'malformed',
199
+ message: 'recovery request ephemeral key is not multibase',
179
200
  cause
180
201
  });
181
202
  }
182
203
  if (ephemeralPublicKey.length !== KEM_OUTPUT_LENGTH) {
183
- throw new RecoveryRequestError('malformed', `recovery request ephemeral key must be ${KEM_OUTPUT_LENGTH} bytes`);
204
+ throw new RecoveryRequestError({
205
+ reason: 'malformed',
206
+ message: `recovery request ephemeral key must be ${KEM_OUTPUT_LENGTH} bytes`
207
+ });
184
208
  }
185
209
  return {
186
210
  requesterDID: normalizeDID(iss),
@@ -205,13 +229,12 @@ function unframeAttestedGroupInfo(bytes, lifecycle) {
205
229
  const ephemeralPublicKey = await hpke.exportPublicKey(keyPair.publicKey);
206
230
  const ephemeralPrivateKey = await hpke.exportPrivateKey(keyPair.privateKey);
207
231
  const signed = await identity.signToken({
208
- type: RECOVERY_REQUEST_TYPE,
209
- groupID: group.groupID,
210
- requestID,
211
- ephemeralKey: encodeMultibase(ephemeralPublicKey)
212
- }, // Self-verifying offline: a responder must not need a DID resolver to check
213
- // the signature of a peer it has never resolved.
214
- {
232
+ payload: {
233
+ type: RECOVERY_REQUEST_TYPE,
234
+ groupID: group.groupID,
235
+ requestID,
236
+ ephemeralKey: encodeMultibase(ephemeralPublicKey)
237
+ },
215
238
  embedLongForm: true
216
239
  });
217
240
  return {
@@ -222,12 +245,21 @@ function unframeAttestedGroupInfo(bytes, lifecycle) {
222
245
  }
223
246
  export async function sealToRequest(params) {
224
247
  const { kind, group, request, plaintext, requireMember = true } = params;
225
- const verified = await verifyRecoveryRequest(request);
248
+ const verified = await verifyRecoveryRequest({
249
+ token: request,
250
+ crypto: group.crypto
251
+ });
226
252
  if (verified.groupID !== group.groupID) {
227
- throw new RecoveryRequestError('group-mismatch', `recovery request names group ${verified.groupID}, not ${group.groupID}`);
253
+ throw new RecoveryRequestError({
254
+ reason: 'group-mismatch',
255
+ message: `recovery request names group ${verified.groupID}, not ${group.groupID}`
256
+ });
228
257
  }
229
258
  if (requireMember && group.findMemberLeafIndex(verified.requesterDID) === undefined) {
230
- throw new RecoveryRequestError('not-a-member', `recovery requester ${verified.requesterDID} has no leaf in the current ratchet tree`);
259
+ throw new RecoveryRequestError({
260
+ reason: 'not-a-member',
261
+ message: `recovery requester ${verified.requesterDID} has no leaf in the current ratchet tree`
262
+ });
231
263
  }
232
264
  const { hpke } = group.context.cipherSuite;
233
265
  const aad = recoveryAAD(kind, group.groupID, verified.requesterDID, verified.requestID);
@@ -291,22 +323,24 @@ export async function sealToRequest(params) {
291
323
  if (normalizeDID(identity.id) !== normalizeDID(group.credential.id)) {
292
324
  throw new Error(`sealGroupInfo: identity.id (${identity.id}) must match the responding handle credential (${group.credential.id})`);
293
325
  }
294
- const verified = await verifyRecoveryRequest(request);
326
+ const verified = await verifyRecoveryRequest({
327
+ token: request,
328
+ crypto: group.crypto
329
+ });
295
330
  const { groupInfo } = await exportGroupInfo({
296
331
  group
297
332
  });
298
333
  const ledger = group.anchor.controller == null ? undefined : encodeLedgerTokens(await group.getLedger());
299
334
  const signed = await identity.signToken({
300
- type: RECOVERY_GROUPINFO_TYPE,
301
- groupID: verified.groupID,
302
- requestID: verified.requestID,
303
- groupInfoDigest: encodeMultibase(sha256(groupInfo)),
304
- ...ledger == null ? {} : {
305
- ledgerDigest: encodeMultibase(sha256(ledger))
306
- }
307
- }, // Self-verifying offline: the healing peer must check the signature without
308
- // resolving the responder.
309
- {
335
+ payload: {
336
+ type: RECOVERY_GROUPINFO_TYPE,
337
+ groupID: verified.groupID,
338
+ requestID: verified.requestID,
339
+ groupInfoDigest: encodeMultibase(sha256(groupInfo)),
340
+ ...ledger == null ? {} : {
341
+ ledgerDigest: encodeMultibase(sha256(ledger))
342
+ }
343
+ },
310
344
  embedLongForm: true
311
345
  });
312
346
  const plaintext = frameAttestedGroupInfo(stringifyToken(signed), groupInfo, ledger);
@@ -333,23 +367,37 @@ export async function sealToRequest(params) {
333
367
  const { attestation, group, requestID, groupInfo, ledger } = params;
334
368
  let verified;
335
369
  try {
336
- verified = await verifyToken(attestation);
370
+ verified = await verifyToken({
371
+ crypto: group.crypto,
372
+ token: attestation
373
+ });
337
374
  } catch (cause) {
338
375
  // biome-ignore lint/style/useErrorCause: cause IS passed; the rule only reads argument 1, and these take (reason, message, options).
339
- throw new SealedGroupInfoError('unauthenticated', 'responder attestation signature did not verify', {
376
+ throw new SealedGroupInfoError({
377
+ reason: 'unauthenticated',
378
+ message: 'responder attestation signature did not verify',
340
379
  cause
341
380
  });
342
381
  }
343
382
  if (!isVerifiedToken(verified)) {
344
- throw new SealedGroupInfoError('unauthenticated', 'responder attestation is not signed');
383
+ throw new SealedGroupInfoError({
384
+ reason: 'unauthenticated',
385
+ message: 'responder attestation is not signed'
386
+ });
345
387
  }
346
388
  const { iss, type, groupID, requestID: attestedRequestID, groupInfoDigest, ledgerDigest } = verified.payload;
347
389
  if (type !== RECOVERY_GROUPINFO_TYPE || groupID !== group.groupID || attestedRequestID !== requestID || typeof groupInfoDigest !== 'string' || groupInfoDigest !== encodeMultibase(sha256(groupInfo)) || ledger != null && ledgerDigest !== encodeMultibase(sha256(ledger))) {
348
- throw new SealedGroupInfoError('unauthenticated', 'responder attestation does not bind this group, request, and GroupInfo');
390
+ throw new SealedGroupInfoError({
391
+ reason: 'unauthenticated',
392
+ message: 'responder attestation does not bind this group, request, and GroupInfo'
393
+ });
349
394
  }
350
395
  // Lifecycle authority is judged against the derived pending tree and joined registry.
351
396
  if (group.anchor.controller == null && group.findMemberLeafIndex(normalizeDID(iss)) === undefined) {
352
- throw new SealedGroupInfoError('unauthenticated', "responder holds no leaf in the requester's last-known ratchet tree");
397
+ throw new SealedGroupInfoError({
398
+ reason: 'unauthenticated',
399
+ message: "responder holds no leaf in the requester's last-known ratchet tree"
400
+ });
353
401
  }
354
402
  return normalizeDID(iss);
355
403
  }
@@ -361,12 +409,18 @@ export async function sealToRequest(params) {
361
409
  */ function assertGroupInfoBoundToGroup(groupInfo, group) {
362
410
  const binding = readGroupInfoBinding(groupInfo);
363
411
  if (binding.groupID !== group.groupID) {
364
- throw new SealedGroupInfoError('group-mismatch', `sealed GroupInfo names group ${binding.groupID}, not ${group.groupID}`);
412
+ throw new SealedGroupInfoError({
413
+ reason: 'group-mismatch',
414
+ message: `sealed GroupInfo names group ${binding.groupID}, not ${group.groupID}`
415
+ });
365
416
  }
366
417
  const ownAnchor = readGroupAnchorExtension(group);
367
418
  const ownData = ownAnchor?.extensionData instanceof Uint8Array ? ownAnchor.extensionData : null;
368
419
  if (ownData == null || binding.anchorExtensionData == null || !bytesEqual(ownData, binding.anchorExtensionData)) {
369
- throw new SealedGroupInfoError('group-mismatch', 'sealed GroupInfo carries a different genesis anchor than the group being healed');
420
+ throw new SealedGroupInfoError({
421
+ reason: 'group-mismatch',
422
+ message: 'sealed GroupInfo carries a different genesis anchor than the group being healed'
423
+ });
370
424
  }
371
425
  }
372
426
  /**
@@ -398,7 +452,9 @@ export async function sealToRequest(params) {
398
452
  ({ attestation, groupInfo, ledger } = unframeAttestedGroupInfo(plaintext, group.anchor.controller != null));
399
453
  } catch (cause) {
400
454
  // biome-ignore lint/style/useErrorCause: cause IS passed; the rule only reads argument 1, and these take (reason, message, options).
401
- throw new SealedGroupInfoError('malformed', 'sealed plaintext is not a framed, attested GroupInfo', {
455
+ throw new SealedGroupInfoError({
456
+ reason: 'malformed',
457
+ message: 'sealed plaintext is not a framed, attested GroupInfo',
402
458
  cause
403
459
  });
404
460
  }
@@ -407,7 +463,9 @@ export async function sealToRequest(params) {
407
463
  inspectGroupInfo(groupInfo);
408
464
  } catch (cause) {
409
465
  // biome-ignore lint/style/useErrorCause: cause IS passed; the rule only reads argument 1, and these take (reason, message, options).
410
- throw new SealedGroupInfoError('malformed', 'sealed plaintext is not a framed MLSMessage(GroupInfo)', {
466
+ throw new SealedGroupInfoError({
467
+ reason: 'malformed',
468
+ message: 'sealed plaintext is not a framed MLSMessage(GroupInfo)',
411
469
  cause
412
470
  });
413
471
  }
@@ -432,11 +490,22 @@ export async function sealToRequest(params) {
432
490
  if (message?.wireformat !== wireformats.mls_group_info) throw new Error('Invalid GroupInfo');
433
491
  const extension = message.groupInfo.groupContext.extensions.find((held)=>held.extensionType === LEDGER_HEAD_EXTENSION_TYPE);
434
492
  const head = extension?.extensionData instanceof Uint8Array ? decodeLedgerHead(extension.extensionData) : null;
435
- if (head == null) throw new SealedGroupInfoError('malformed', 'GroupInfo has no ledger head');
436
- assertHeadMatches(head.head, computeHead(group.groupID, tokens.map(ledgerEntryDigest)));
493
+ if (head == null) throw new SealedGroupInfoError({
494
+ reason: 'malformed',
495
+ message: 'GroupInfo has no ledger head'
496
+ });
497
+ assertHeadMatches({
498
+ expected: head.head,
499
+ actual: computeHead({
500
+ groupID: group.groupID,
501
+ entryIDs: tokens.map(ledgerEntryDigest)
502
+ })
503
+ });
437
504
  } catch (cause) {
438
505
  // biome-ignore lint/style/useErrorCause: cause is passed in the third argument.
439
- throw new SealedGroupInfoError('malformed', 'recovery ledger does not reproduce the GroupInfo head', {
506
+ throw new SealedGroupInfoError({
507
+ reason: 'malformed',
508
+ message: 'recovery ledger does not reproduce the GroupInfo head',
440
509
  cause
441
510
  });
442
511
  }
@@ -543,7 +612,9 @@ function decodeLedgerTokens(bytes) {
543
612
  return decodeLedgerTokens(plaintext);
544
613
  } catch (cause) {
545
614
  // biome-ignore lint/style/useErrorCause: cause IS passed; the rule only reads argument 1, and these take (reason, message, options).
546
- throw new SealedLedgerError('malformed', 'sealed plaintext is not a framed ledger', {
615
+ throw new SealedLedgerError({
616
+ reason: 'malformed',
617
+ message: 'sealed plaintext is not a framed ledger',
547
618
  cause
548
619
  });
549
620
  }
package/lib/registry.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type ControllerLog } from '@kokuin/controller';
2
+ import { type CryptoOptions } from '@kokuin/token';
2
3
  import type { GroupAnchor } from './anchor.js';
3
4
  import type { MLSCredentialIdentity } from './credential.js';
4
5
  import type { FoldDrop, FoldInput } from './fold.js';
@@ -85,23 +86,48 @@ export declare function isLifecycleDeviceValue(value: DeviceValue): boolean;
85
86
  * is the acceptance pipeline's job (a self-register leaf attestation, or a management capability),
86
87
  * never the fold's. Lifecycle effects replay recorded DIDs without consulting a later tree.
87
88
  */
88
- export declare function registryApply(verified: VerifiedLedgerEntry<DeviceValue>, state: DeviceRegistry, controllerID?: string): DeviceRegistry;
89
+ export declare function registryApply(verified: VerifiedLedgerEntry<DeviceValue>, state: DeviceRegistry, controllerID?: string, options?: CryptoOptions): Promise<DeviceRegistry>;
89
90
  /** Only reset removal without a cascade permits a later admission. */
90
91
  export declare function isResetOnly(record: DeviceRecord): boolean;
91
92
  /** Structural admission exception. Callers still authenticate the capability and holder grant. */
92
- export declare function mayReadmitResetDevice(registry: DeviceRegistry, parsed: MLSCredentialIdentity): boolean;
93
+ export declare function mayReadmitResetDevice(registry: DeviceRegistry, parsed: MLSCredentialIdentity, options?: CryptoOptions): Promise<boolean>;
94
+ export type ControllerOfParams = {
95
+ registry: DeviceRegistry;
96
+ deviceDID: string;
97
+ };
93
98
  /** The profile a device is bound to in the folded registry, or undefined — the authority input. */
94
- export declare function controllerOf(registry: DeviceRegistry, deviceDID: string): string | undefined;
99
+ export declare function controllerOf({ registry, deviceDID }: ControllerOfParams): string | undefined;
100
+ export type BeaconOfParams = {
101
+ registry: DeviceRegistry;
102
+ controllerDID: string;
103
+ };
95
104
  /** The advisory beacon a controller last announced, or undefined. Never a validation input. */
96
- export declare function beaconOf(registry: DeviceRegistry, controllerDID: string): ControllerBeacon | undefined;
97
- export declare function recordedLogOf(registry: DeviceRegistry, controller: string): ControllerLog | undefined;
98
- export declare function assertRetainsKnownEffects(controller: string, known: DeviceRegistry, candidate: DeviceRegistry): void;
99
- export declare function registryForLog(controller: string, log: ControllerLog): DeviceRegistry;
105
+ export declare function beaconOf({ registry, controllerDID, }: BeaconOfParams): ControllerBeacon | undefined;
106
+ export type RecordedLogOfParams = {
107
+ registry: DeviceRegistry;
108
+ controller: string;
109
+ };
110
+ export declare function recordedLogOf({ registry, controller, }: RecordedLogOfParams): ControllerLog | undefined;
111
+ export type AssertRetainsKnownEffectsParams = {
112
+ controller: string;
113
+ known: DeviceRegistry;
114
+ candidate: DeviceRegistry;
115
+ } & CryptoOptions;
116
+ export declare function assertRetainsKnownEffects({ controller, known, candidate, ...options }: AssertRetainsKnownEffectsParams): Promise<void>;
117
+ export type RegistryForLogParams = {
118
+ controller: string;
119
+ log: ControllerLog;
120
+ } & CryptoOptions;
121
+ export declare function registryForLog({ controller, log, ...options }: RegistryForLogParams): Promise<DeviceRegistry>;
100
122
  /**
101
123
  * The deny set Slice 1's seam consumes: the device DIDs at `status: 'revoked'` NOW. Matched, never
102
124
  * enumerated by consumers (`has`), holding device DIDs only, per the kokuin deny-set rule.
103
125
  */
104
126
  export declare function denySetOf(registry: DeviceRegistry): ReadonlySet<string>;
127
+ export type AuthorityParams = {
128
+ registry: DeviceRegistry;
129
+ issuer: string;
130
+ };
105
131
  /**
106
132
  * The universal rule: an ACTIVE binding resolves the issuer to its controller; anything else
107
133
  * resolves to the issuer itself. A revoked binding confers no authority until accepted re-entry.
@@ -110,7 +136,13 @@ export declare function denySetOf(registry: DeviceRegistry): ReadonlySet<string>
110
136
  * {@link controllerOf} is the RAW lookup, deliberately status-blind, since the deviceRevoked event
111
137
  * emission and the revoke/label gate read the surviving binding of a just-revoked device.)
112
138
  */
113
- export declare function authority(registry: DeviceRegistry, issuer: string): string;
139
+ export declare function authority({ registry, issuer }: AuthorityParams): string;
140
+ export type FoldControlParams = {
141
+ entries: Array<FoldInput>;
142
+ anchor: GroupAnchor;
143
+ groupID: string;
144
+ onDrop?: (drop: FoldDrop) => void;
145
+ } & CryptoOptions;
114
146
  /**
115
147
  * Fold the whole control ledger into BOTH projections in one ordered pass, so a role entry's
116
148
  * authority resolves against the registry-so-far (device entries strictly earlier), never a
@@ -124,9 +156,13 @@ export declare function authority(registry: DeviceRegistry, issuer: string): str
124
156
  * and must not empty the admin set. Every other type, a groupID mismatch, or a malformed value is
125
157
  * dropped (never thrown), routed through `onDrop` exactly as {@link foldRoster}.
126
158
  */
127
- export declare function foldControl(entries: Array<FoldInput>, anchor: GroupAnchor, groupID: string, onDrop?: (drop: FoldDrop) => void): {
159
+ export declare function foldControl({ entries, anchor, groupID, onDrop, ...options }: FoldControlParams): Promise<{
128
160
  roster: RosterState;
129
161
  registry: DeviceRegistry;
162
+ }>;
163
+ export type RevocationOfParams = {
164
+ group: GroupHandle;
165
+ did: string;
130
166
  };
131
167
  /** A ledger revocation, independent of the controller's current log deny set. */
132
- export declare function revocationOf(group: GroupHandle, did: string): Revocation | null;
168
+ export declare function revocationOf({ group, did }: RevocationOfParams): Revocation | null;
package/lib/registry.js CHANGED
@@ -73,7 +73,7 @@ export function isLifecycleDeviceValue(value) {
73
73
  * The registry fold step. Pure, order-dependent, authorization-free — a device entry's authority
74
74
  * is the acceptance pipeline's job (a self-register leaf attestation, or a management capability),
75
75
  * never the fold's. Lifecycle effects replay recorded DIDs without consulting a later tree.
76
- */ export function registryApply(verified, state, controllerID) {
76
+ */ export async function registryApply(verified, state, controllerID, options) {
77
77
  const subject = normalizeDID(verified.entry.subject);
78
78
  const value = verified.entry.value;
79
79
  const devices = new Map(state.devices);
@@ -84,7 +84,7 @@ export function isLifecycleDeviceValue(value) {
84
84
  const previous = controllers.get(controller) ?? controllerProjection();
85
85
  if (value.op === 'clock') {
86
86
  if (value.attest === true) {
87
- const folded = previous.recordedLog == null ? undefined : foldControllerLog(controller, previous.recordedLog);
87
+ const folded = previous.recordedLog == null ? undefined : await foldControllerLog(controller, previous.recordedLog, options);
88
88
  // Only an effective incarnation attests; the head also holds removed and denied ones.
89
89
  const member = folded?.ok ? [
90
90
  ...folded.head.members.values()
@@ -103,13 +103,13 @@ export function isLifecycleDeviceValue(value) {
103
103
  });
104
104
  }
105
105
  } else {
106
- const effect = authenticateLifecycleProof(controller, verified, state);
106
+ const effect = await authenticateLifecycleProof(controller, verified, state, options);
107
107
  let projection = {
108
108
  ...previous,
109
109
  recordedLog: effect.recordedLog,
110
110
  genFloor: effect.genFloor
111
111
  };
112
- if (value.op === 'seed') projection = seedEffects(controller, devices, projection);
112
+ if (value.op === 'seed') projection = await seedEffects(controller, devices, projection, options);
113
113
  controllers.set(controller, projection);
114
114
  const resetRef = effect.resetRef;
115
115
  const denials = new Map((value.effects ?? []).flatMap((claim)=>claim.kind === 'deny' ? [
@@ -157,7 +157,12 @@ export function isLifecycleDeviceValue(value) {
157
157
  for (const [add, member] of removedMembers){
158
158
  if (!('event' in member.proofRef)) continue;
159
159
  const chain = effect.recordedLog.chain;
160
- const index = memberDropIndices(controller, chain, add).at(-1) ?? memberTombstoneIndices(controller, chain, add, member.did).at(-1);
160
+ const index = (await memberDropIndices({
161
+ did: controller,
162
+ chain,
163
+ add,
164
+ ...options
165
+ })).at(-1) ?? (await memberTombstoneIndices(controller, chain, add, member.did, options)).at(-1);
161
166
  if (index != null) removedMembers.set(add, {
162
167
  ...member,
163
168
  proofRef: {
@@ -176,7 +181,7 @@ export function isLifecycleDeviceValue(value) {
176
181
  });
177
182
  for (const [did, held] of devices){
178
183
  if (held.controller !== controller || held.proofRef == null || !('event' in held.proofRef)) continue;
179
- const index = revokeIndices(controller, effect.recordedLog.chain, held.cascadedFrom ?? did).at(-1);
184
+ const index = (await revokeIndices(controller, effect.recordedLog.chain, held.cascadedFrom ?? did, options)).at(-1);
180
185
  if (index != null) devices.set(did, {
181
186
  ...held,
182
187
  proofRef: {
@@ -280,35 +285,39 @@ export function isLifecycleDeviceValue(value) {
280
285
  /** Only reset removal without a cascade permits a later admission. */ export function isResetOnly(record) {
281
286
  return record.status === 'revoked' && record.reason === 'reset' && record.cascadedFrom == null;
282
287
  }
283
- /** Structural admission exception. Callers still authenticate the capability and holder grant. */ export function mayReadmitResetDevice(registry, parsed) {
288
+ /** Structural admission exception. Callers still authenticate the capability and holder grant. */ export async function mayReadmitResetDevice(registry, parsed, options) {
284
289
  const record = registry.devices.get(normalizeDID(parsed.id));
285
290
  const binding = parsed.controller;
286
291
  if (record == null || !isResetOnly(record) || binding == null || normalizeDID(binding.id) !== record.controller) return false;
287
- const folded = foldChain(binding.id, binding.prefix);
292
+ const folded = await foldChain(binding.id, binding.prefix, options);
288
293
  return folded.ok && (folded.states.at(-1)?.gen ?? 0) >= (registry.controllers.get(record.controller)?.genFloor ?? 0);
289
294
  }
290
- /** The profile a device is bound to in the folded registry, or undefined — the authority input. */ export function controllerOf(registry, deviceDID) {
295
+ /** The profile a device is bound to in the folded registry, or undefined — the authority input. */ export function controllerOf({ registry, deviceDID }) {
291
296
  return registry.devices.get(normalizeDID(deviceDID))?.controller;
292
297
  }
293
- /** The advisory beacon a controller last announced, or undefined. Never a validation input. */ export function beaconOf(registry, controllerDID) {
298
+ /** The advisory beacon a controller last announced, or undefined. Never a validation input. */ export function beaconOf({ registry, controllerDID }) {
294
299
  return registry.controllers.get(normalizeDID(controllerDID))?.beacon;
295
300
  }
296
- export function recordedLogOf(registry, controller) {
301
+ export function recordedLogOf({ registry, controller }) {
297
302
  return registry.controllers.get(normalizeDID(controller))?.recordedLog;
298
303
  }
299
- export function assertRetainsKnownEffects(controller, known, candidate) {
304
+ export async function assertRetainsKnownEffects({ controller, known, candidate, ...options }) {
300
305
  const did = normalizeDID(controller);
301
306
  const held = known.controllers.get(did);
302
307
  const offered = candidate.controllers.get(did);
303
- const before = held?.recordedLog == null ? undefined : foldControllerLog(did, held.recordedLog);
304
- const after = offered?.recordedLog == null ? undefined : foldControllerLog(did, offered.recordedLog);
308
+ const before = held?.recordedLog == null ? undefined : await foldControllerLog(did, held.recordedLog, options);
309
+ const after = offered?.recordedLog == null ? undefined : await foldControllerLog(did, offered.recordedLog, options);
305
310
  if (before?.ok && (!after?.ok || after.head.saturated)) throw new RecoveryKnowledgeError('epoch-event');
306
311
  if (held?.recordedLog != null && offered?.recordedLog != null) {
307
- const branches = resolveBranches(did, [
308
- held.recordedLog.chain,
309
- offered.recordedLog.chain
310
- ]);
311
- const winner = branches.ok ? foldChain(did, branches.winner) : undefined;
312
+ const branches = await resolveBranches({
313
+ ...options,
314
+ did: did,
315
+ chains: [
316
+ held.recordedLog.chain,
317
+ offered.recordedLog.chain
318
+ ]
319
+ });
320
+ const winner = branches.ok ? await foldChain(did, branches.winner, options) : undefined;
312
321
  if (!winner?.ok || after?.ok && after.head.epoch !== winner.head.epoch) throw new RecoveryKnowledgeError('forked');
313
322
  }
314
323
  if ((offered?.timeFloor ?? 0) < (held?.timeFloor ?? 0) || (offered?.genFloor ?? 0) < (held?.genFloor ?? 0)) throw new RecoveryKnowledgeError('floor');
@@ -335,14 +344,19 @@ export function assertRetainsKnownEffects(controller, known, candidate) {
335
344
  }
336
345
  }
337
346
  }
338
- export function registryForLog(controller, log) {
339
- const { log: recordedLog, after } = ingestControllerLog(controller, undefined, log);
347
+ export async function registryForLog({ controller, log, ...options }) {
348
+ const { log: recordedLog, after } = await ingestControllerLog({
349
+ controller,
350
+ recorded: undefined,
351
+ proof: log,
352
+ ...options
353
+ });
340
354
  const devices = new Map();
341
- const projection = seedEffects(normalizeDID(controller), devices, {
355
+ const projection = await seedEffects(normalizeDID(controller), devices, {
342
356
  ...controllerProjection(),
343
357
  recordedLog,
344
358
  genFloor: after.head.gen
345
- });
359
+ }, options);
346
360
  return {
347
361
  devices,
348
362
  controllers: new Map([
@@ -353,12 +367,18 @@ export function registryForLog(controller, log) {
353
367
  ])
354
368
  };
355
369
  }
356
- function seedEffects(controller, devices, projection) {
370
+ async function seedEffects(controller, devices, projection, options) {
357
371
  const log = projection.recordedLog;
358
- const folded = foldControllerLog(controller, log);
372
+ const folded = await foldControllerLog(controller, log, options);
359
373
  if (!folded.ok) throw new RevokeProofError('effects-mismatch');
360
374
  const removedMembers = new Map(projection.removedMembers);
361
- for (const claim of claimsFor(controller, undefined, log, 0)){
375
+ for (const claim of (await claimsFor({
376
+ controller,
377
+ recorded: undefined,
378
+ merged: log,
379
+ genFloor: 0,
380
+ ...options
381
+ }))){
362
382
  if (claim.kind === 'deny') {
363
383
  devices.set(normalizeDID(claim.did), {
364
384
  controller,
@@ -398,7 +418,7 @@ function seedEffects(controller, devices, projection) {
398
418
  * (Note the split:
399
419
  * {@link controllerOf} is the RAW lookup, deliberately status-blind, since the deviceRevoked event
400
420
  * emission and the revoke/label gate read the surviving binding of a just-revoked device.)
401
- */ export function authority(registry, issuer) {
421
+ */ export function authority({ registry, issuer }) {
402
422
  const norm = normalizeDID(issuer);
403
423
  const record = registry.devices.get(norm);
404
424
  return record != null && record.status === 'active' ? record.controller : norm;
@@ -415,7 +435,7 @@ function seedEffects(controller, devices, projection) {
415
435
  * `kumiai.role` entry is authorized by `roster.roles.get(authority(registry, issuer)) === 'admin'`
416
436
  * and must not empty the admin set. Every other type, a groupID mismatch, or a malformed value is
417
437
  * dropped (never thrown), routed through `onDrop` exactly as {@link foldRoster}.
418
- */ export function foldControl(entries, anchor, groupID, onDrop) {
438
+ */ export async function foldControl({ entries, anchor, groupID, onDrop, ...options }) {
419
439
  let roster = roleReducer.seed(anchor);
420
440
  let registry = registrySeed();
421
441
  for (const [position, { verified, entryID }] of entries.entries()){
@@ -447,13 +467,13 @@ function seedEffects(controller, devices, projection) {
447
467
  }
448
468
  try {
449
469
  if (entry.value.op === 'seed' && position !== 0) throw new RevokeProofError('detached');
450
- registry = registryApply({
470
+ registry = await registryApply({
451
471
  issuer,
452
472
  entry: {
453
473
  ...entry,
454
474
  value: entry.value
455
475
  }
456
- }, registry, anchor.controller);
476
+ }, registry, anchor.controller, options);
457
477
  } catch {
458
478
  onDrop?.({
459
479
  entryID,
@@ -479,7 +499,10 @@ function seedEffects(controller, devices, projection) {
479
499
  });
480
500
  continue;
481
501
  }
482
- const auth = authority(registry, issuer);
502
+ const auth = authority({
503
+ registry,
504
+ issuer
505
+ });
483
506
  if (roster.roles.get(auth) !== 'admin') {
484
507
  onDrop?.({
485
508
  entryID,
@@ -489,12 +512,15 @@ function seedEffects(controller, devices, projection) {
489
512
  continue;
490
513
  }
491
514
  const next = roleReducer.apply({
492
- issuer,
493
- entry: {
494
- ...entry,
495
- value: entry.value
496
- }
497
- }, roster);
515
+ verified: {
516
+ issuer,
517
+ entry: {
518
+ ...entry,
519
+ value: entry.value
520
+ }
521
+ },
522
+ stateSoFar: roster
523
+ });
498
524
  if (adminCount(next) === 0) {
499
525
  onDrop?.({
500
526
  entryID,
@@ -510,7 +536,7 @@ function seedEffects(controller, devices, projection) {
510
536
  registry
511
537
  };
512
538
  }
513
- /** A ledger revocation, independent of the controller's current log deny set. */ export function revocationOf(group, did) {
539
+ /** A ledger revocation, independent of the controller's current log deny set. */ export function revocationOf({ group, did }) {
514
540
  const record = group.registry.devices.get(normalizeDID(did));
515
541
  if (record?.status !== 'revoked' || record.proofRef === undefined) return null;
516
542
  return {
package/lib/roster.d.ts CHANGED
@@ -29,6 +29,12 @@ export declare function adminCount(state: RosterState): number;
29
29
  * composable seed / authority / apply the fold turns on.
30
30
  */
31
31
  export declare const roleReducer: LedgerReducer<RoleValue, RosterState>;
32
+ export type FoldRosterParams = {
33
+ entries: Array<FoldInput<RoleValue>>;
34
+ anchor: GroupAnchor;
35
+ groupID: string;
36
+ onDrop?: (drop: FoldDrop) => void;
37
+ };
32
38
  /**
33
39
  * Fold a group's `kumiai.role` ledger into the current roster.
34
40
  *
@@ -42,4 +48,4 @@ export declare const roleReducer: LedgerReducer<RoleValue, RosterState>;
42
48
  * through `verifyAuthority` so they reach the optional `onDrop` observer that
43
49
  * {@link foldLedger} calls; only there does the fold surface a skip.
44
50
  */
45
- export declare function foldRoster(entries: Array<FoldInput<RoleValue>>, anchor: GroupAnchor, groupID: string, onDrop?: (drop: FoldDrop) => void): RosterState;
51
+ export declare function foldRoster({ entries, anchor, groupID, onDrop }: FoldRosterParams): RosterState;