@kumiai/mls 0.9.0 → 0.10.1

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 (54) hide show
  1. package/README.md +23 -0
  2. package/lib/anchor.d.ts +10 -4
  3. package/lib/anchor.js +26 -2
  4. package/lib/authentication.d.ts +11 -14
  5. package/lib/authentication.js +127 -86
  6. package/lib/capability.d.ts +37 -0
  7. package/lib/capability.js +141 -0
  8. package/lib/codec.js +2 -1
  9. package/lib/device-proof.d.ts +1 -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 +22 -35
  16. package/lib/group-commit.js +122 -103
  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 +60 -24
  24. package/lib/group-handle.js +331 -77
  25. package/lib/group-info.d.ts +8 -0
  26. package/lib/group-info.js +29 -1
  27. package/lib/group-lifecycle.d.ts +32 -0
  28. package/lib/group-lifecycle.js +300 -0
  29. package/lib/group-membership.js +7 -3
  30. package/lib/group-welcome.d.ts +13 -4
  31. package/lib/group-welcome.js +113 -21
  32. package/lib/group.d.ts +3 -2
  33. package/lib/group.js +2 -1
  34. package/lib/history.d.ts +6 -0
  35. package/lib/history.js +26 -0
  36. package/lib/index.d.ts +10 -4
  37. package/lib/index.js +9 -3
  38. package/lib/lifecycle-proof.d.ts +24 -0
  39. package/lib/lifecycle-proof.js +193 -0
  40. package/lib/lifecycle.d.ts +44 -0
  41. package/lib/lifecycle.js +385 -0
  42. package/lib/policy.d.ts +20 -0
  43. package/lib/policy.js +8 -4
  44. package/lib/recovery-verdict.d.ts +43 -0
  45. package/lib/recovery-verdict.js +135 -0
  46. package/lib/recovery.d.ts +70 -0
  47. package/lib/recovery.js +110 -36
  48. package/lib/registry.d.ts +34 -7
  49. package/lib/registry.js +113 -15
  50. package/lib/roster.d.ts +1 -1
  51. package/lib/roster.js +2 -2
  52. package/lib/types.d.ts +13 -8
  53. package/lib/welcome-refs.d.ts +2 -1
  54. package/package.json +6 -6
package/lib/recovery.d.ts CHANGED
@@ -11,6 +11,25 @@ export declare const SEALED_GROUP_INFO_VERSION = 1;
11
11
  /** The sealed ledger reply shares the frame — `[version][enc][ct]` — and nothing
12
12
  * else: see {@link LEDGER_REPLY}. */
13
13
  export declare const SEALED_LEDGER_VERSION = 1;
14
+ /**
15
+ * The per-kind labels that keep the two reply kinds — GroupInfo vs ledger —
16
+ * cryptographically non-interchangeable: distinct HPKE `info` AND distinct AAD
17
+ * domain, so a reply of one kind fails to open as the other even when group,
18
+ * member, request id and ephemeral key are all identical. Do not rely on distinct
19
+ * `requestID`s for this separation — that is a caller property a reused id loses;
20
+ * these labels carry it unconditionally.
21
+ */
22
+ export type SealedReplyKind = {
23
+ /** HPKE `info` — separates this use from MLS's own use of the same ciphersuite,
24
+ * and from the other reply kind. */
25
+ hpkeInfo: Uint8Array;
26
+ /** Prefix of the AAD, before the group/member/request fields are framed in. */
27
+ aadDomain: Uint8Array;
28
+ /** The frame's version byte. */
29
+ version: number;
30
+ /** Raised when a reply of this kind will not open. */
31
+ fail: (reason: SealedReplyRejection, message: string, options?: ErrorOptions) => Error;
32
+ };
14
33
  /**
15
34
  * The signed payload a recovering peer publishes. The requester DID is the signed
16
35
  * `iss`, never a self-asserted payload field — nothing to disagree with the
@@ -97,6 +116,14 @@ export declare class SealedLedgerError extends Error {
97
116
  constructor(reason: SealedReplyRejection, message: string, options?: ErrorOptions);
98
117
  get reason(): SealedReplyRejection;
99
118
  }
119
+ /**
120
+ * Verify a request token's signature and parse its payload. The requester DID is
121
+ * the verified issuer, never a payload field. Unsigned (`alg: 'none'`) tokens are
122
+ * rejected: `verifyToken` returns them unchecked, so their `iss` is
123
+ * attacker-chosen. `embedLongForm` lets it verify offline — a responder needs no
124
+ * DID resolver to answer.
125
+ */
126
+ export declare function verifyRecoveryRequest(token: string): Promise<VerifiedRecoveryRequest>;
100
127
  export type CreateRecoveryRequestParams = {
101
128
  /** The requester's own (possibly stale) handle: it names the group, and its
102
129
  * ciphersuite is the HPKE the ephemeral keypair must be minted under. */
@@ -122,6 +149,37 @@ export type CreateRecoveryRequestResult = {
122
149
  * group's own ciphersuite HPKE, so no second HPKE enters the system.
123
150
  */
124
151
  export declare function createRecoveryRequest(params: CreateRecoveryRequestParams): Promise<CreateRecoveryRequestResult>;
152
+ /**
153
+ * Answer a request of one kind: verify it, check the requester still holds a leaf
154
+ * in the responder's current ratchet tree, and seal `plaintext` to the ephemeral
155
+ * key *inside the signed request*.
156
+ *
157
+ * Authorization is roster-intrinsic and lives HERE, not in each caller, so a new
158
+ * kind of answer cannot be added without it. Not a permission a host can forget:
159
+ * only DIDs the responder's own tree still carries a leaf for can be answered, so a
160
+ * removed member gets nothing from any responder that has applied its removal.
161
+ *
162
+ * Throws {@link RecoveryRequestError} for every refusal — see
163
+ * {@link RecoveryRequestRejection}.
164
+ */
165
+ export type SealToRequestParams = {
166
+ kind: SealedReplyKind;
167
+ group: GroupHandle;
168
+ request: string;
169
+ plaintext: Uint8Array;
170
+ /** Require the requester to hold a leaf in the current tree. Defaults to true. */
171
+ requireMember?: boolean;
172
+ };
173
+ export declare function sealToRequest(params: SealToRequestParams): Promise<Uint8Array>;
174
+ /**
175
+ * Open a reply of one kind with the key minted for `requestID`; return the sealed
176
+ * plaintext.
177
+ *
178
+ * The AAD is rebuilt from the caller's *own* group id, DID, and request id, so a
179
+ * reply for another member, another request, or another kind (kind is bound into
180
+ * both AAD and HPKE `info`) fails as an AEAD failure, not a skippable comparison.
181
+ */
182
+ export declare function openSealedReply(params: OpenSealedReplyParams): Promise<Uint8Array>;
125
183
  export type SealGroupInfoParams = {
126
184
  /** The responder's current handle. Its ratchet tree — not a roster snapshot or
127
185
  * policy list — is what authorizes the requester. */
@@ -158,6 +216,9 @@ export type OpenSealedGroupInfoParams = {
158
216
  /** The private half retained since {@link createRecoveryRequest}. */
159
217
  ephemeralPrivateKey: Uint8Array;
160
218
  };
219
+ export type OpenSealedReplyParams = OpenSealedGroupInfoParams & {
220
+ kind: SealedReplyKind;
221
+ };
161
222
  /**
162
223
  * Open a sealed reply and return the framed `MLSMessage(GroupInfo)` — the exact
163
224
  * bytes `joinGroupExternal` takes. Throws {@link SealedGroupInfoError}.
@@ -169,6 +230,15 @@ export type OpenSealedGroupInfoParams = {
169
230
  * GroupInfo's group id and genesis anchor must match the group being healed.
170
231
  */
171
232
  export declare function openSealedGroupInfo(params: OpenSealedGroupInfoParams): Promise<Uint8Array>;
233
+ export type RecoveryGroupInfo = {
234
+ groupInfo: Uint8Array;
235
+ /** The responder's ledger tokens; empty outside lifecycle groups. */
236
+ ledger: Array<string>;
237
+ /** The responder's normalized DID. */
238
+ signer: string;
239
+ };
240
+ /** @internal The authenticated recovery inputs retained for candidate judgement. */
241
+ export declare function openRecoveryGroupInfo(params: OpenSealedGroupInfoParams): Promise<RecoveryGroupInfo>;
172
242
  export type SealLedgerParams = {
173
243
  /** The responder's current handle. Its ratchet tree authorizes the requester on
174
244
  * the same terms as {@link sealGroupInfo}, and its own ledger is the only one it
package/lib/recovery.js CHANGED
@@ -1,7 +1,10 @@
1
1
  import { decodeMultibase, encodeMultibase, isVerifiedToken, normalizeDID, stringifyToken, verifyToken } from '@kokuin/token';
2
2
  import { sha256 } from '@noble/hashes/sha2.js';
3
- import { readGroupAnchorExtension } from './anchor.js';
3
+ import { decode, mlsMessageDecoder, wireformats } from 'ts-mls';
4
+ import { LEDGER_HEAD_EXTENSION_TYPE, readGroupAnchorExtension } from './anchor.js';
4
5
  import { exportGroupInfo, inspectGroupInfo, readGroupInfoBinding } from './group.js';
6
+ import { assertHeadMatches, computeHead, decodeLedgerHead } from './head.js';
7
+ import { ledgerEntryDigest } from './ledger.js';
5
8
  const utf8 = new TextEncoder();
6
9
  /** `type` tag on every recovery-request token. Domain-separates it, so a token
7
10
  * minted for another purpose can never pose as a request for group state. */ export const RECOVERY_REQUEST_TYPE = 'kumiai.recovery-request';
@@ -93,25 +96,43 @@ function bytesEqual(a, b) {
93
96
  }
94
97
  return true;
95
98
  }
96
- /** The sealed GroupInfo plaintext: `[len(4)][attestation token][GroupInfo bytes]`,
97
- * big-endian length. Proof and vouched-for GroupInfo are sealed under one AEAD;
98
- * neither can be lifted from the other. */ function frameAttestedGroupInfo(attestation, groupInfo) {
99
+ /** Lifecycle replies length-frame GroupInfo too, followed by the authenticated ledger. */ function frameAttestedGroupInfo(attestation, groupInfo, ledger) {
99
100
  const token = utf8.encode(attestation);
101
+ if (ledger != null) {
102
+ const out = new Uint8Array(8 + token.length + groupInfo.length + ledger.length);
103
+ const view = new DataView(out.buffer);
104
+ view.setUint32(0, token.length, false);
105
+ out.set(token, 4);
106
+ view.setUint32(4 + token.length, groupInfo.length, false);
107
+ out.set(groupInfo, 8 + token.length);
108
+ out.set(ledger, 8 + token.length + groupInfo.length);
109
+ return out;
110
+ }
100
111
  const out = new Uint8Array(4 + token.length + groupInfo.length);
101
112
  new DataView(out.buffer).setUint32(0, token.length, false);
102
113
  out.set(token, 4);
103
114
  out.set(groupInfo, 4 + token.length);
104
115
  return out;
105
116
  }
106
- function unframeAttestedGroupInfo(bytes) {
117
+ function unframeAttestedGroupInfo(bytes, lifecycle) {
107
118
  if (bytes.length < 4) throw new Error('attested GroupInfo frame is truncated');
108
119
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
109
120
  const length = view.getUint32(0, false);
110
121
  if (4 + length > bytes.length) throw new Error('attested GroupInfo frame is truncated');
111
- return {
112
- attestation: new TextDecoder().decode(bytes.subarray(4, 4 + length)),
122
+ const attestation = new TextDecoder().decode(bytes.subarray(4, 4 + length));
123
+ if (!lifecycle) return {
124
+ attestation,
113
125
  groupInfo: bytes.slice(4 + length)
114
126
  };
127
+ if (8 + length > bytes.length) throw new Error('attested GroupInfo frame is truncated');
128
+ const groupInfoLength = view.getUint32(4 + length, false);
129
+ const end = 8 + length + groupInfoLength;
130
+ if (end > bytes.length) throw new Error('attested GroupInfo frame is truncated');
131
+ return {
132
+ attestation,
133
+ groupInfo: bytes.slice(8 + length, end),
134
+ ledger: bytes.slice(end)
135
+ };
115
136
  }
116
137
  /**
117
138
  * The AAD binding a sealed reply to one kind, group, member, and request. The
@@ -132,7 +153,7 @@ function unframeAttestedGroupInfo(bytes) {
132
153
  * rejected: `verifyToken` returns them unchecked, so their `iss` is
133
154
  * attacker-chosen. `embedLongForm` lets it verify offline — a responder needs no
134
155
  * DID resolver to answer.
135
- */ async function verifyRecoveryRequest(token) {
156
+ */ export async function verifyRecoveryRequest(token) {
136
157
  let verified;
137
158
  try {
138
159
  verified = await verifyToken(token);
@@ -199,24 +220,13 @@ function unframeAttestedGroupInfo(bytes) {
199
220
  ephemeralPrivateKey
200
221
  };
201
222
  }
202
- /**
203
- * Answer a request of one kind: verify it, check the requester still holds a leaf
204
- * in the responder's current ratchet tree, and seal `plaintext` to the ephemeral
205
- * key *inside the signed request*.
206
- *
207
- * Authorization is roster-intrinsic and lives HERE, not in each caller, so a new
208
- * kind of answer cannot be added without it. Not a permission a host can forget:
209
- * only DIDs the responder's own tree still carries a leaf for can be answered, so a
210
- * removed member gets nothing from any responder that has applied its removal.
211
- *
212
- * Throws {@link RecoveryRequestError} for every refusal — see
213
- * {@link RecoveryRequestRejection}.
214
- */ async function sealToRequest(kind, group, request, plaintext) {
223
+ export async function sealToRequest(params) {
224
+ const { kind, group, request, plaintext, requireMember = true } = params;
215
225
  const verified = await verifyRecoveryRequest(request);
216
226
  if (verified.groupID !== group.groupID) {
217
227
  throw new RecoveryRequestError('group-mismatch', `recovery request names group ${verified.groupID}, not ${group.groupID}`);
218
228
  }
219
- if (group.findMemberLeafIndex(verified.requesterDID) === undefined) {
229
+ if (requireMember && group.findMemberLeafIndex(verified.requesterDID) === undefined) {
220
230
  throw new RecoveryRequestError('not-a-member', `recovery requester ${verified.requesterDID} has no leaf in the current ratchet tree`);
221
231
  }
222
232
  const { hpke } = group.context.cipherSuite;
@@ -235,7 +245,8 @@ function unframeAttestedGroupInfo(bytes) {
235
245
  * The AAD is rebuilt from the caller's *own* group id, DID, and request id, so a
236
246
  * reply for another member, another request, or another kind (kind is bound into
237
247
  * both AAD and HPKE `info`) fails as an AEAD failure, not a skippable comparison.
238
- */ async function openSealedReply(kind, group, sealed, requestID, ephemeralPrivateKey) {
248
+ */ export async function openSealedReply(params) {
249
+ const { kind, group, sealed, requestID, ephemeralPrivateKey } = params;
239
250
  if (sealed.length < MIN_SEALED_LENGTH || sealed[0] !== kind.version) {
240
251
  throw kind.fail('malformed', 'sealed reply frame is truncated or carries an unknown version');
241
252
  }
@@ -284,18 +295,27 @@ function unframeAttestedGroupInfo(bytes) {
284
295
  const { groupInfo } = await exportGroupInfo({
285
296
  group
286
297
  });
298
+ const ledger = group.anchor.controller == null ? undefined : encodeLedgerTokens(await group.getLedger());
287
299
  const signed = await identity.signToken({
288
300
  type: RECOVERY_GROUPINFO_TYPE,
289
301
  groupID: verified.groupID,
290
302
  requestID: verified.requestID,
291
- groupInfoDigest: encodeMultibase(sha256(groupInfo))
303
+ groupInfoDigest: encodeMultibase(sha256(groupInfo)),
304
+ ...ledger == null ? {} : {
305
+ ledgerDigest: encodeMultibase(sha256(ledger))
306
+ }
292
307
  }, // Self-verifying offline: the healing peer must check the signature without
293
308
  // resolving the responder.
294
309
  {
295
310
  embedLongForm: true
296
311
  });
297
- const plaintext = frameAttestedGroupInfo(stringifyToken(signed), groupInfo);
298
- return await sealToRequest(GROUP_INFO_REPLY, group, request, plaintext);
312
+ const plaintext = frameAttestedGroupInfo(stringifyToken(signed), groupInfo, ledger);
313
+ return await sealToRequest({
314
+ kind: GROUP_INFO_REPLY,
315
+ group,
316
+ request,
317
+ plaintext
318
+ });
299
319
  }
300
320
  /**
301
321
  * Verify the responder's membership attestation and require the signer to hold a
@@ -309,7 +329,8 @@ function unframeAttestedGroupInfo(bytes) {
309
329
  * construction, which is the point and the limit: a member absent from it (never
310
330
  * joined, or removed before the requester's last-known epoch) is refused; one still
311
331
  * in it (including one removed AFTER that epoch) is accepted.
312
- */ async function assertResponderIsMember(attestation, group, requestID, groupInfo) {
332
+ */ async function assertResponderIsMember(params) {
333
+ const { attestation, group, requestID, groupInfo, ledger } = params;
313
334
  let verified;
314
335
  try {
315
336
  verified = await verifyToken(attestation);
@@ -322,13 +343,15 @@ function unframeAttestedGroupInfo(bytes) {
322
343
  if (!isVerifiedToken(verified)) {
323
344
  throw new SealedGroupInfoError('unauthenticated', 'responder attestation is not signed');
324
345
  }
325
- const { iss, type, groupID, requestID: attestedRequestID, groupInfoDigest } = verified.payload;
326
- if (type !== RECOVERY_GROUPINFO_TYPE || groupID !== group.groupID || attestedRequestID !== requestID || typeof groupInfoDigest !== 'string' || groupInfoDigest !== encodeMultibase(sha256(groupInfo))) {
346
+ const { iss, type, groupID, requestID: attestedRequestID, groupInfoDigest, ledgerDigest } = verified.payload;
347
+ if (type !== RECOVERY_GROUPINFO_TYPE || groupID !== group.groupID || attestedRequestID !== requestID || typeof groupInfoDigest !== 'string' || groupInfoDigest !== encodeMultibase(sha256(groupInfo)) || ledger != null && ledgerDigest !== encodeMultibase(sha256(ledger))) {
327
348
  throw new SealedGroupInfoError('unauthenticated', 'responder attestation does not bind this group, request, and GroupInfo');
328
349
  }
329
- if (group.findMemberLeafIndex(normalizeDID(iss)) === undefined) {
350
+ // Lifecycle authority is judged against the derived pending tree and joined registry.
351
+ if (group.anchor.controller == null && group.findMemberLeafIndex(normalizeDID(iss)) === undefined) {
330
352
  throw new SealedGroupInfoError('unauthenticated', "responder holds no leaf in the requester's last-known ratchet tree");
331
353
  }
354
+ return normalizeDID(iss);
332
355
  }
333
356
  /**
334
357
  * Bind the offered GroupInfo to the group being healed: same group id, same
@@ -356,13 +379,23 @@ function unframeAttestedGroupInfo(bytes) {
356
379
  * must place the sealer in this requester's own last-known tree, and the offered
357
380
  * GroupInfo's group id and genesis anchor must match the group being healed.
358
381
  */ export async function openSealedGroupInfo(params) {
382
+ return (await openRecoveryGroupInfo(params)).groupInfo;
383
+ }
384
+ /** @internal The authenticated recovery inputs retained for candidate judgement. */ export async function openRecoveryGroupInfo(params) {
359
385
  const { group, sealed, requestID, ephemeralPrivateKey } = params;
360
- const plaintext = await openSealedReply(GROUP_INFO_REPLY, group, sealed, requestID, ephemeralPrivateKey);
386
+ const plaintext = await openSealedReply({
387
+ kind: GROUP_INFO_REPLY,
388
+ group,
389
+ sealed,
390
+ requestID,
391
+ ephemeralPrivateKey
392
+ });
361
393
  let attestation;
362
394
  let groupInfo;
395
+ let ledger;
363
396
  try {
364
397
  ;
365
- ({ attestation, groupInfo } = unframeAttestedGroupInfo(plaintext));
398
+ ({ attestation, groupInfo, ledger } = unframeAttestedGroupInfo(plaintext, group.anchor.controller != null));
366
399
  } catch (cause) {
367
400
  // biome-ignore lint/style/useErrorCause: cause IS passed; the rule only reads argument 1, and these take (reason, message, options).
368
401
  throw new SealedGroupInfoError('malformed', 'sealed plaintext is not a framed, attested GroupInfo', {
@@ -379,9 +412,39 @@ function unframeAttestedGroupInfo(bytes) {
379
412
  });
380
413
  }
381
414
  // Authenticate the responder, then bind the GroupInfo to this group.
382
- await assertResponderIsMember(attestation, group, requestID, groupInfo);
415
+ const signer = await assertResponderIsMember({
416
+ attestation,
417
+ group,
418
+ requestID,
419
+ groupInfo,
420
+ ledger
421
+ });
383
422
  assertGroupInfoBoundToGroup(groupInfo, group);
384
- return groupInfo;
423
+ if (ledger == null) return {
424
+ groupInfo,
425
+ ledger: [],
426
+ signer
427
+ };
428
+ let tokens;
429
+ try {
430
+ tokens = decodeLedgerTokens(ledger);
431
+ const message = decode(mlsMessageDecoder, groupInfo);
432
+ if (message?.wireformat !== wireformats.mls_group_info) throw new Error('Invalid GroupInfo');
433
+ const extension = message.groupInfo.groupContext.extensions.find((held)=>held.extensionType === LEDGER_HEAD_EXTENSION_TYPE);
434
+ 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)));
437
+ } catch (cause) {
438
+ // 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', {
440
+ cause
441
+ });
442
+ }
443
+ return {
444
+ groupInfo,
445
+ ledger: tokens,
446
+ signer
447
+ };
385
448
  }
386
449
  /**
387
450
  * The whole ordered ledger, framed for sealing: `[count(4)][ (length(4) | token)... ]`,
@@ -447,7 +510,12 @@ function decodeLedgerTokens(bytes) {
447
510
  */ export async function sealLedger(params) {
448
511
  const { group, request } = params;
449
512
  const entries = await group.getLedger();
450
- return await sealToRequest(LEDGER_REPLY, group, request, encodeLedgerTokens(entries));
513
+ return await sealToRequest({
514
+ kind: LEDGER_REPLY,
515
+ group,
516
+ request,
517
+ plaintext: encodeLedgerTokens(entries)
518
+ });
451
519
  }
452
520
  /**
453
521
  * Open a sealed ledger reply and return the responder's whole ordered ledger, as
@@ -464,7 +532,13 @@ function decodeLedgerTokens(bytes) {
464
532
  * gather attempt), not compromise. Throws {@link SealedLedgerError}.
465
533
  */ export async function openSealedLedger(params) {
466
534
  const { group, sealed, requestID, ephemeralPrivateKey } = params;
467
- const plaintext = await openSealedReply(LEDGER_REPLY, group, sealed, requestID, ephemeralPrivateKey);
535
+ const plaintext = await openSealedReply({
536
+ kind: LEDGER_REPLY,
537
+ group,
538
+ sealed,
539
+ requestID,
540
+ ephemeralPrivateKey
541
+ });
468
542
  try {
469
543
  return decodeLedgerTokens(plaintext);
470
544
  } catch (cause) {
package/lib/registry.d.ts CHANGED
@@ -1,11 +1,13 @@
1
+ import type { SignedEvent } from '@kokuin/controller';
1
2
  import type { GroupAnchor } from './anchor.js';
2
3
  import type { FoldDrop, FoldInput } from './fold.js';
4
+ import type { GroupHandle } from './group-handle.js';
3
5
  import type { VerifiedLedgerEntry } from './ledger.js';
4
6
  import { type RosterState } from './roster.js';
5
7
  /** The reserved control type carrying a device-registry mutation. One branch, one namespace slot. */
6
8
  export declare const DEVICE_ENTRY_TYPE = "kumiai.device";
7
9
  /** The device lifecycle operations plus the advisory controller-log beacon. */
8
- export type DeviceOp = 'register' | 'add' | 'revoke' | 'label' | 'beacon';
10
+ export type DeviceOp = 'register' | 'add' | 'revoke' | 'label' | 'beacon' | 'reset' | 'clock';
9
11
  /**
10
12
  * A `kumiai.device` entry's `value`. `controller` names the profile a register/add binds to;
11
13
  * `label` renames; `capability` carries the management-capability proof a manage op is verified
@@ -16,17 +18,40 @@ export type DeviceValue = {
16
18
  controller?: string;
17
19
  label?: string;
18
20
  capability?: string;
21
+ proof?: Array<SignedEvent>;
22
+ revoked?: Array<RevokedEffect>;
23
+ time?: number;
19
24
  /** Beacon only: the length of the controller's FULL log at announcement time. */
20
25
  logLength?: number;
21
26
  /** Beacon only: the head digest of the controller's FULL log at announcement time. */
22
27
  headDigest?: string;
23
28
  };
24
- /** A folded device binding. `controller` is the profile DID; `status` gates the deny set. */
29
+ export type RevokedEffect = {
30
+ did: string;
31
+ cascadedFrom?: string;
32
+ };
33
+ export type Revocation = {
34
+ controller: string;
35
+ logPosition: number;
36
+ reason?: 'reset';
37
+ cascadedFrom?: string;
38
+ };
39
+ /** A folded device binding or permanent revocation. */
25
40
  export type DeviceRecord = {
26
41
  controller: string;
27
42
  status: 'active' | 'revoked';
28
43
  label?: string;
44
+ logPosition?: number;
45
+ reason?: 'reset';
46
+ cascadedFrom?: string;
47
+ };
48
+ export type ControllerProjection = {
49
+ recordedLog: Array<SignedEvent>;
50
+ genFloor: number;
51
+ timeFloor: number;
52
+ beacon?: ControllerBeacon;
29
53
  };
54
+ export declare function controllerProjection(): ControllerProjection;
30
55
  /** An advisory pointer to a controller's FULL log head. Never a validation input. */
31
56
  export type ControllerBeacon = {
32
57
  logLength: number;
@@ -36,22 +61,22 @@ export type ControllerBeacon = {
36
61
  * The group-folded device registry: `device DID -> record`, keyed by normalized DID. A pure
37
62
  * function of the accepted `kumiai.device` entries, folded beside {@link RosterState}. Two views
38
63
  * derive from `devices` and are never stored: {@link controllerOf} and {@link denySetOf}.
39
- * `controllers` is a second, independent per-controller projection fed by the `beacon` op.
64
+ * `controllers` records authenticated logs and floors, with an independent advisory beacon.
40
65
  */
41
66
  export type DeviceRegistry = {
42
67
  devices: ReadonlyMap<string, DeviceRecord>;
43
- controllers: ReadonlyMap<string, ControllerBeacon>;
68
+ controllers: ReadonlyMap<string, ControllerProjection>;
44
69
  };
45
70
  export declare function registrySeed(): DeviceRegistry;
46
71
  /** Structural guard: a value carrying a known `op` (and, for register/add, a string controller). */
47
72
  export declare function isDeviceValue(value: unknown): value is DeviceValue;
73
+ export declare function isLifecycleDeviceValue(value: DeviceValue): boolean;
48
74
  /**
49
75
  * The registry fold step. Pure, order-dependent, authorization-free — a device entry's authority
50
76
  * is the acceptance pipeline's job (a self-register leaf attestation, or a management capability),
51
- * never the fold's. On the trusted fold path a revoke/label always concerns a subject a prior
52
- * register bound, so an absent subject is a no-op guard rather than a real case.
77
+ * never the fold's. Lifecycle effects replay recorded DIDs without consulting a later tree.
53
78
  */
54
- export declare function registryApply(verified: VerifiedLedgerEntry<DeviceValue>, state: DeviceRegistry): DeviceRegistry;
79
+ export declare function registryApply(verified: VerifiedLedgerEntry<DeviceValue>, state: DeviceRegistry, controllerID?: string): DeviceRegistry;
55
80
  /** The profile a device is bound to in the folded registry, or undefined — the authority input. */
56
81
  export declare function controllerOf(registry: DeviceRegistry, deviceDID: string): string | undefined;
57
82
  /** The advisory beacon a controller last announced, or undefined. Never a validation input. */
@@ -87,3 +112,5 @@ export declare function foldControl(entries: Array<FoldInput>, anchor: GroupAnch
87
112
  roster: RosterState;
88
113
  registry: DeviceRegistry;
89
114
  };
115
+ /** A permanent ledger revocation, independent of the controller's current log deny set. */
116
+ export declare function revocationOf(group: GroupHandle, did: string): Revocation | null;
package/lib/registry.js CHANGED
@@ -1,6 +1,14 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
+ import { authenticateLifecycleProof } from './lifecycle-proof.js';
2
3
  import { adminCount, ROLE_ENTRY_TYPE, roleReducer } from './roster.js';
3
4
  /** The reserved control type carrying a device-registry mutation. One branch, one namespace slot. */ export const DEVICE_ENTRY_TYPE = 'kumiai.device';
5
+ export function controllerProjection() {
6
+ return {
7
+ recordedLog: [],
8
+ genFloor: 0,
9
+ timeFloor: 0
10
+ };
11
+ }
4
12
  export function registrySeed() {
5
13
  return {
6
14
  devices: new Map(),
@@ -10,9 +18,11 @@ export function registrySeed() {
10
18
  /** Structural guard: a value carrying a known `op` (and, for register/add, a string controller). */ export function isDeviceValue(value) {
11
19
  if (value == null || typeof value !== 'object') return false;
12
20
  const v = value;
13
- if (v.op !== 'register' && v.op !== 'add' && v.op !== 'revoke' && v.op !== 'label' && v.op !== 'beacon') {
21
+ if (v.op !== 'register' && v.op !== 'add' && v.op !== 'revoke' && v.op !== 'label' && v.op !== 'beacon' && v.op !== 'reset' && v.op !== 'clock') {
14
22
  return false;
15
23
  }
24
+ const proofBearing = v.op === 'reset' || v.op === 'revoke' && v.proof !== undefined;
25
+ if (!proofBearing && ('proof' in v || 'revoked' in v)) return false;
16
26
  if ((v.op === 'register' || v.op === 'add') && typeof v.controller !== 'string') return false;
17
27
  if (v.op === 'beacon' && (typeof v.logLength !== 'number' || typeof v.headDigest !== 'string')) {
18
28
  return false;
@@ -22,19 +32,67 @@ export function registrySeed() {
22
32
  if (v.capability !== undefined && typeof v.capability !== 'string') return false;
23
33
  if (v.logLength !== undefined && typeof v.logLength !== 'number') return false;
24
34
  if (v.headDigest !== undefined && typeof v.headDigest !== 'string') return false;
35
+ if (v.time !== undefined && (typeof v.time !== 'number' || !Number.isFinite(v.time))) return false;
36
+ if (v.proof !== undefined && !Array.isArray(v.proof)) return false;
37
+ if (v.revoked !== undefined && (!Array.isArray(v.revoked) || v.revoked.some((effect)=>{
38
+ if (effect == null || typeof effect !== 'object') return true;
39
+ const record = effect;
40
+ return typeof record.did !== 'string' || record.cascadedFrom !== undefined && typeof record.cascadedFrom !== 'string';
41
+ }))) return false;
42
+ if (v.op === 'clock' && typeof v.time !== 'number') return false;
43
+ if ((v.op === 'reset' || v.proof !== undefined) && (!Array.isArray(v.proof) || !Array.isArray(v.revoked))) return false;
25
44
  return true;
26
45
  }
46
+ export function isLifecycleDeviceValue(value) {
47
+ if (!isDeviceValue(value)) return false;
48
+ return value.op === 'beacon' || value.op === 'clock' || (value.op === 'revoke' || value.op === 'reset') && value.proof !== undefined && value.revoked !== undefined && value.capability === undefined;
49
+ }
27
50
  /**
28
51
  * The registry fold step. Pure, order-dependent, authorization-free — a device entry's authority
29
52
  * is the acceptance pipeline's job (a self-register leaf attestation, or a management capability),
30
- * never the fold's. On the trusted fold path a revoke/label always concerns a subject a prior
31
- * register bound, so an absent subject is a no-op guard rather than a real case.
32
- */ export function registryApply(verified, state) {
53
+ * never the fold's. Lifecycle effects replay recorded DIDs without consulting a later tree.
54
+ */ export function registryApply(verified, state, controllerID) {
33
55
  const subject = normalizeDID(verified.entry.subject);
34
56
  const value = verified.entry.value;
35
57
  const devices = new Map(state.devices);
36
58
  const controllers = new Map(state.controllers);
37
59
  const existing = devices.get(subject);
60
+ if (controllerID != null && (value.op === 'reset' || value.op === 'revoke' || value.op === 'clock')) {
61
+ const controller = normalizeDID(controllerID);
62
+ const previous = controllers.get(controller) ?? controllerProjection();
63
+ if (value.op === 'clock') {
64
+ controllers.set(controller, {
65
+ ...previous,
66
+ timeFloor: Math.max(previous.timeFloor, value.time)
67
+ });
68
+ } else {
69
+ const effect = authenticateLifecycleProof(controller, verified, state);
70
+ controllers.set(controller, {
71
+ ...previous,
72
+ recordedLog: effect.recordedLog,
73
+ genFloor: effect.genFloor
74
+ });
75
+ for (const revoked of value.revoked ?? []){
76
+ const did = normalizeDID(revoked.did);
77
+ if (devices.get(did)?.status === 'revoked') continue;
78
+ devices.set(did, {
79
+ controller,
80
+ status: 'revoked',
81
+ logPosition: effect.logPosition,
82
+ ...value.op === 'reset' ? {
83
+ reason: 'reset'
84
+ } : {},
85
+ ...revoked.cascadedFrom == null ? {} : {
86
+ cascadedFrom: normalizeDID(revoked.cascadedFrom)
87
+ }
88
+ });
89
+ }
90
+ }
91
+ return {
92
+ devices,
93
+ controllers
94
+ };
95
+ }
38
96
  switch(value.op){
39
97
  case 'register':
40
98
  case 'add':
@@ -80,6 +138,12 @@ export function registrySeed() {
80
138
  controllers
81
139
  };
82
140
  }
141
+ case 'reset':
142
+ case 'clock':
143
+ return {
144
+ devices,
145
+ controllers
146
+ };
83
147
  case 'label':
84
148
  {
85
149
  if (existing == null) return {
@@ -101,9 +165,13 @@ export function registrySeed() {
101
165
  {
102
166
  // Advisory, self-scoped: `subject` is the CONTROLLER DID. Last-write-wins; never touches
103
167
  // `devices` or the deny set, never gates validation. Guarded present by isDeviceValue.
168
+ const previous = controllers.get(subject) ?? controllerProjection();
104
169
  controllers.set(subject, {
105
- logLength: value.logLength,
106
- headDigest: value.headDigest
170
+ ...previous,
171
+ beacon: {
172
+ logLength: value.logLength,
173
+ headDigest: value.headDigest
174
+ }
107
175
  });
108
176
  return {
109
177
  devices,
@@ -116,7 +184,7 @@ export function registrySeed() {
116
184
  return registry.devices.get(normalizeDID(deviceDID))?.controller;
117
185
  }
118
186
  /** The advisory beacon a controller last announced, or undefined. Never a validation input. */ export function beaconOf(registry, controllerDID) {
119
- return registry.controllers.get(normalizeDID(controllerDID));
187
+ return registry.controllers.get(normalizeDID(controllerDID))?.beacon;
120
188
  }
121
189
  /**
122
190
  * The deny set Slice 1's seam consumes: the device DIDs at `status: 'revoked'` NOW. Matched, never
@@ -174,16 +242,32 @@ export function registrySeed() {
174
242
  });
175
243
  continue;
176
244
  }
177
- registry = registryApply({
178
- issuer,
179
- entry: {
180
- ...entry,
181
- value: entry.value
182
- }
183
- }, registry);
245
+ if (anchor.controller != null && !isLifecycleDeviceValue(entry.value)) {
246
+ onDrop?.({
247
+ entryID,
248
+ type: entry.type,
249
+ reason: 'device operation is not allowed in a lifecycle group'
250
+ });
251
+ continue;
252
+ }
253
+ try {
254
+ registry = registryApply({
255
+ issuer,
256
+ entry: {
257
+ ...entry,
258
+ value: entry.value
259
+ }
260
+ }, registry, anchor.controller);
261
+ } catch {
262
+ onDrop?.({
263
+ entryID,
264
+ type: entry.type,
265
+ reason: 'invalid lifecycle proof'
266
+ });
267
+ }
184
268
  continue;
185
269
  }
186
- if (entry.type !== ROLE_ENTRY_TYPE) {
270
+ if (anchor.controller != null || entry.type !== ROLE_ENTRY_TYPE) {
187
271
  onDrop?.({
188
272
  entryID,
189
273
  type: entry.type,
@@ -230,3 +314,17 @@ export function registrySeed() {
230
314
  registry
231
315
  };
232
316
  }
317
+ /** A permanent ledger revocation, independent of the controller's current log deny set. */ export function revocationOf(group, did) {
318
+ const record = group.registry.devices.get(normalizeDID(did));
319
+ if (record?.status !== 'revoked' || record.logPosition === undefined) return null;
320
+ return {
321
+ controller: record.controller,
322
+ logPosition: record.logPosition,
323
+ ...record.reason === undefined ? {} : {
324
+ reason: record.reason
325
+ },
326
+ ...record.cascadedFrom === undefined ? {} : {
327
+ cascadedFrom: record.cascadedFrom
328
+ }
329
+ };
330
+ }
package/lib/roster.d.ts CHANGED
@@ -18,7 +18,7 @@ export type RosterState = {
18
18
  export declare function adminCount(state: RosterState): number;
19
19
  /**
20
20
  * Self-referential role reducer. Authority is rooted at the genesis anchor (the
21
- * creator is the epoch-0 admin) and grows only through admins-so-far: every
21
+ * controller or creator is the epoch-0 admin) and grows only through admins-so-far: every
22
22
  * grant or demotion must be issued by a DID already an admin in the state
23
23
  * accumulated from strictly-earlier entries. That state-so-far check is what
24
24
  * makes rotation sound — an admin can demote the very admin that promoted them