@kumiai/mls 0.5.0 → 0.7.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.
@@ -1,15 +1,18 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
+ import { EventEmitter } from '@sozai/event';
2
3
  import { contentTypes, createApplicationMessage, decode, encode, mlsExporter, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, wireformats } from 'ts-mls';
3
4
  import { readGroupAnchor } from './anchor.js';
4
5
  import { parseMLSCredentialIdentity } from './credential.js';
6
+ import { verifyDeviceEntry } from './device-proof.js';
5
7
  import { decodeControlEnvelope } from './envelope.js';
6
8
  import { foldEnvelope, GROUP_TYPE_PREFIX } from './envelope-fold.js';
9
+ import { deviceDenyHolderFor } from './group-context.js';
7
10
  import { readMessageEpoch } from './group-info.js';
8
11
  import { assertHeadMatches, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, headsMatch, readLedgerHead, readLedgerHeadExtension } from './head.js';
9
12
  import { ledgerEntryDigest, verifyLedgerEntry } from './ledger.js';
10
13
  import { createMutex } from './mutex.js';
11
14
  import { defaultCommitPolicy, MissingLedgerEntriesError } from './policy.js';
12
- import { foldRoster } from './roster.js';
15
+ import { beaconOf, controllerOf, DEVICE_ENTRY_TYPE, denySetOf, foldControl, isDeviceValue } from './registry.js';
13
16
  import { readSenderLeafIndex } from './sender-data.js';
14
17
  /** One serializer per live handle, so its state-mutating operations run one at a
15
18
  * time in issue order. Keyed weakly: the entry is collected with the handle, and
@@ -22,6 +25,14 @@ export function mutexFor(handle) {
22
25
  }
23
26
  return mutex;
24
27
  }
28
+ /** One event emitter per live handle, shared across every handle derived from it (deriveGroup),
29
+ * so a subscription on an early handle keeps receiving events fired on its post-commit successors.
30
+ * Keyed weakly, mirroring MUTEXES. */ const EMITTERS = new WeakMap();
31
+ /** The full emitter for a handle — module-internal, for deriveGroup to share it onward. */ export function emitterOf(group) {
32
+ const emitter = EMITTERS.get(group);
33
+ if (emitter == null) throw new Error('unreachable: every GroupHandle sets its emitter in the constructor');
34
+ return emitter;
35
+ }
25
36
  /** Overwrite retired secret buffers ts-mls hands back as `consumed`, so key
26
37
  * material does not linger in the heap after the state that used it is replaced. */ function zeroAll(buffers) {
27
38
  for (const buffer of buffers)buffer.fill(0);
@@ -144,22 +155,20 @@ export function mutexFor(handle) {
144
155
  }
145
156
  }
146
157
  /**
147
- * Project a held ledger into the roster. foldRoster drops every non-`kumiai.role`
148
- * entry by type, so the mixed-type log is fed in whole. Replayed in order, repeats
149
- * and all: a claim re-enacted at a later position must undo what came between.
150
- */ function foldLedgerRoster(ledger, anchor, groupID) {
158
+ * Project a held ledger into BOTH the roster and the device registry in one ordered pass
159
+ * (see {@link foldControl}), so a role entry's authority resolves against the registry-so-far.
160
+ * The mixed-type log is fed in whole; foldControl drops every unrelated entry by type.
161
+ */ function foldLedgerControl(ledger, anchor, groupID) {
151
162
  const entries = ledger.map(({ verified, entryID })=>({
152
163
  verified,
153
164
  entryID
154
165
  }));
155
- return foldRoster(entries, anchor, groupID);
166
+ return foldControl(entries, anchor, groupID);
156
167
  }
157
168
  /** Mutable wrapper around MLS group state + Enkaku credential. */ export class GroupHandle {
158
169
  #state;
159
170
  #credential;
160
171
  #context;
161
- #cache;
162
- #resolver;
163
172
  #commitPolicy;
164
173
  #resolveLedgerEntries;
165
174
  #onLedgerEntries;
@@ -170,12 +179,11 @@ export function mutexFor(handle) {
170
179
  /** Entry bodies by content id, for resolving the ids an envelope names. A body is
171
180
  * the same wherever it appears in the log, so this store is keyed. */ #entryBodies;
172
181
  #roster;
182
+ #registry;
173
183
  constructor(params){
174
184
  this.#state = params.state;
175
185
  this.#credential = params.credential;
176
186
  this.#context = params.context;
177
- this.#cache = params.cache;
178
- this.#resolver = params.resolver;
179
187
  this.#commitPolicy = params.commitPolicy;
180
188
  this.#resolveLedgerEntries = params.resolveLedgerEntries;
181
189
  this.#onLedgerEntries = params.onLedgerEntries;
@@ -197,7 +205,15 @@ export function mutexFor(handle) {
197
205
  verified
198
206
  }
199
207
  ]));
200
- this.#roster = foldLedgerRoster(this.#ledger, anchor, this.groupID);
208
+ const folded = foldLedgerControl(this.#ledger, anchor, this.groupID);
209
+ this.#roster = folded.roster;
210
+ this.#registry = folded.registry;
211
+ // Point this context's deny holder at THIS handle. deriveGroup shares the context object, so a
212
+ // derived (post-commit) handle re-points it to itself — always the newest, live registry. A
213
+ // context not built by resolveMlsContext (none in the codebase) simply has no holder.
214
+ const denyHolder = deviceDenyHolderFor(this.#context);
215
+ if (denyHolder != null) denyHolder.provider = ()=>this.currentDenySet();
216
+ EMITTERS.set(this, params.events ?? new EventEmitter());
201
217
  }
202
218
  get groupID() {
203
219
  return this.#credential.groupID;
@@ -217,12 +233,6 @@ export function mutexFor(handle) {
217
233
  get context() {
218
234
  return this.#context;
219
235
  }
220
- get cache() {
221
- return this.#cache;
222
- }
223
- get resolver() {
224
- return this.#resolver;
225
- }
226
236
  /** The commit policy enforced by processMessage, if any. Carried onto
227
237
  * handles derived from this one (commitInvite/removeMember). */ get commitPolicy() {
228
238
  return this.#commitPolicy;
@@ -250,6 +260,68 @@ export function mutexFor(handle) {
250
260
  /** The control roster folded from the anchor and every applied ledger entry. */ get roster() {
251
261
  return this.#roster;
252
262
  }
263
+ /** The device registry folded from the anchor and every applied ledger entry. */ get registry() {
264
+ return this.#registry;
265
+ }
266
+ /**
267
+ * The device deny set the auth service consumes: the DIDs revoked in the CURRENTLY folded
268
+ * registry (pre-commit). Matched, never enumerated by consumers. A revoke takes deny-effect from
269
+ * the next epoch, so a commit never denies the leaves it is itself validating.
270
+ */ currentDenySet() {
271
+ return denySetOf(this.#registry);
272
+ }
273
+ /** Listen-only view of this group's events. Consumers subscribe; they cannot emit. */ get events() {
274
+ return emitterOf(this);
275
+ }
276
+ /**
277
+ * The device bindings currently at `status: 'revoked'` — an enumerable notification/tracking
278
+ * surface for consumers deciding where else to revoke. Distinct from currentDenySet(), the
279
+ * opaque matched-never-enumerated validation deny set; this is never a gating input.
280
+ */ revokedDevices() {
281
+ const out = [];
282
+ for (const [device, record] of this.#registry.devices){
283
+ if (record.status === 'revoked') {
284
+ out.push({
285
+ device,
286
+ controller: record.controller,
287
+ ...record.label !== undefined ? {
288
+ label: record.label
289
+ } : {}
290
+ });
291
+ }
292
+ }
293
+ return out;
294
+ }
295
+ /**
296
+ * @internal Fire notification events for the device entries just enacted in one operation.
297
+ * Called from the commit path, from bootstrapLedger, and from the local write APIs — NEVER from
298
+ * the constructor or a fresh-join applyLedgerEntries, so a joiner is not replayed the whole
299
+ * history as live events (it reads revokedDevices()/beaconOf for current state instead). Uses
300
+ * `fire`: a throwing listener is swallowed and cannot break the fold. Reads controllerOf on the
301
+ * POST-fold registry.
302
+ */ emitControlEvents(enacted) {
303
+ const emitter = emitterOf(this);
304
+ const revoked = [];
305
+ for (const { entry } of enacted){
306
+ if (entry.type !== DEVICE_ENTRY_TYPE || !isDeviceValue(entry.value)) continue;
307
+ const value = entry.value;
308
+ const subject = normalizeDID(entry.subject);
309
+ if (value.op === 'revoke') {
310
+ const controller = controllerOf(this.#registry, subject);
311
+ if (controller != null) revoked.push({
312
+ device: subject,
313
+ controller
314
+ });
315
+ } else if (value.op === 'beacon' && value.logLength != null && value.headDigest != null) {
316
+ emitter.fire('controllerBeaconChanged', {
317
+ controller: subject,
318
+ logLength: value.logLength,
319
+ headDigest: value.headDigest
320
+ });
321
+ }
322
+ }
323
+ if (revoked.length > 0) emitter.fire('deviceRevoked', revoked);
324
+ }
253
325
  /**
254
326
  * Verify signed ledger tokens, append the valid ones in the order given, and
255
327
  * refold the roster. Tokens that fail verification or whose groupID mismatches are
@@ -264,6 +336,7 @@ export function mutexFor(handle) {
264
336
  * folds an invite once). Serialized on the handle's mutex.
265
337
  */ async applyLedgerEntries(tokens) {
266
338
  return mutexFor(this).run(async ()=>{
339
+ const appended = [];
267
340
  for (const token of tokens){
268
341
  const verified = await verifyLedgerEntry(token);
269
342
  if (verified == null || verified.entry.groupID !== this.groupID) continue;
@@ -277,8 +350,12 @@ export function mutexFor(handle) {
277
350
  token,
278
351
  verified
279
352
  });
353
+ appended.push(verified);
280
354
  }
281
- this.#roster = foldLedgerRoster(this.#ledger, this.#anchor, this.groupID);
355
+ const folded = foldLedgerControl(this.#ledger, this.#anchor, this.groupID);
356
+ this.#roster = folded.roster;
357
+ this.#registry = folded.registry;
358
+ return appended;
282
359
  });
283
360
  }
284
361
  /**
@@ -362,6 +439,9 @@ export function mutexFor(handle) {
362
439
  // What this bootstrap ADDS, in log order, minus the reserved `kumiai.*` types the fold
363
440
  // consumes itself — the same rule the commit path surfaces by.
364
441
  const surfaced = log.filter(({ entryID, verified })=>!this.#entryBodies.has(entryID) && !verified.entry.type.startsWith(GROUP_TYPE_PREFIX)).map(({ verified })=>verified);
442
+ // Same dedupe as `surfaced`, narrowed to device entries — feeds emitControlEvents below so a
443
+ // heal fires deviceRevoked for entries this bootstrap actually adds, not ones already held.
444
+ const enactedDevice = log.filter(({ entryID, verified })=>!this.#entryBodies.has(entryID) && verified.entry.type === DEVICE_ENTRY_TYPE).map(({ verified })=>verified);
365
445
  this.#ledger = log;
366
446
  this.#entryBodies = new Map(log.map(({ entryID, token, verified })=>[
367
447
  entryID,
@@ -370,7 +450,9 @@ export function mutexFor(handle) {
370
450
  verified
371
451
  }
372
452
  ]));
373
- this.#roster = foldLedgerRoster(log, this.#anchor, this.groupID);
453
+ const folded = foldLedgerControl(log, this.#anchor, this.groupID);
454
+ this.#roster = folded.roster;
455
+ this.#registry = folded.registry;
374
456
  // SURFACED HERE TOO, not only on the commit path. A heal is how a peer that missed commits
375
457
  // catches up — it rejoins, gathers the whole ledger, and lands here — so a bootstrap that
376
458
  // said nothing left a host consuming `onLedgerEntries` as an event stream permanently
@@ -380,6 +462,7 @@ export function mutexFor(handle) {
380
462
  // Deduped against what this handle already held, so a peer bootstrapping over a partial
381
463
  // ledger is not re-notified of entries it has already seen.
382
464
  if (surfaced.length > 0) this.#onLedgerEntries?.(surfaced);
465
+ this.emitControlEvents(enactedDevice);
383
466
  });
384
467
  }
385
468
  get memberCount() {
@@ -398,9 +481,23 @@ export function mutexFor(handle) {
398
481
  } catch {
399
482
  continue;
400
483
  }
484
+ // `?? parsed.id` is the did:key case, where long form IS the id. It is unreachable
485
+ // for peer:4 for any leaf that entered through an add or a join: makeMLSCredential
486
+ // refuses to build a peer:4 identity without a long form, and validateCredential
487
+ // rejects any peer:4 leaf lacking one before it can enter a ratchet tree. restore
488
+ // trusts the host's own persisted state, so neither gate runs on that path.
489
+ const controller = parsed.controller ? parsed.controller.id : undefined;
490
+ const beacon = controller != null ? beaconOf(this.#registry, controller) : undefined;
401
491
  yield {
402
492
  leafIndex: i / 2,
403
- id: parsed.id
493
+ id: parsed.id,
494
+ longForm: parsed.longForm ?? parsed.id,
495
+ ...controller ? {
496
+ controller
497
+ } : {},
498
+ ...beacon ? {
499
+ controllerBeacon: beacon
500
+ } : {}
404
501
  };
405
502
  }
406
503
  }
@@ -414,6 +511,20 @@ export function mutexFor(handle) {
414
511
  return undefined;
415
512
  }
416
513
  /**
514
+ * The resolvable form of a member's DID — the string to hand a DID resolver or a JWE
515
+ * recipient — or `undefined` when the group has no such member. `undefined` carries that one
516
+ * meaning: every member has a long form.
517
+ *
518
+ * Accepts either form of `id`, normalizing both sides exactly as {@link findMemberLeafIndex}
519
+ * does, so a caller holding a long form read off another leaf need not truncate it first.
520
+ */ findMemberLongForm(id) {
521
+ const targetNorm = normalizeDID(id);
522
+ for (const member of this.#iterateMembers()){
523
+ if (normalizeDID(member.id) === targetNorm) return member.longForm;
524
+ }
525
+ return undefined;
526
+ }
527
+ /**
417
528
  * The group's current members from the ratchet tree, in ascending leaf-index
418
529
  * order. Leaves whose credential identity fails to parse are skipped (like
419
530
  * findMemberLeafIndex). Reflects current #state — call before and after
@@ -565,6 +676,7 @@ export function mutexFor(handle) {
565
676
  }
566
677
  let precomputedReject = false;
567
678
  let candidateRoster = this.#roster;
679
+ let candidateRegistry = this.#registry;
568
680
  let surfaced = [];
569
681
  let acceptedEntries = [];
570
682
  let envelopeIDs = [];
@@ -624,21 +736,39 @@ export function mutexFor(handle) {
624
736
  ]);
625
737
  return input;
626
738
  });
627
- const foldResult = foldEnvelope(this.#roster, ordered, this.groupID);
739
+ const foldResult = foldEnvelope(this.#roster, this.#registry, ordered, this.groupID);
628
740
  if (!foldResult.ok) {
629
741
  precomputedReject = true;
630
742
  } else {
631
743
  candidateRoster = foldResult.roster;
744
+ candidateRegistry = foldResult.registry;
632
745
  surfaced = foldResult.surfaced;
633
746
  acceptedEntries = ordered;
747
+ const proofCtx = {
748
+ bindingOfDID: (d)=>this.bindingOfDID(d),
749
+ controllerOf: (d)=>controllerOf(this.#registry, d)
750
+ };
751
+ for (const { verified } of acceptedEntries){
752
+ if (verified.entry.type !== DEVICE_ENTRY_TYPE) continue;
753
+ const ok = await verifyDeviceEntry(verified, proofCtx);
754
+ if (!ok) {
755
+ precomputedReject = true;
756
+ break;
757
+ }
758
+ }
634
759
  }
635
760
  }
636
761
  }
637
762
  }
763
+ const enactedDeviceEntries = acceptedEntries.filter(({ verified })=>verified.entry.type === DEVICE_ENTRY_TYPE).map(({ verified })=>({
764
+ subject: normalizeDID(verified.entry.subject),
765
+ op: verified.entry.value.op
766
+ }));
638
767
  const context = buildCommitPolicyContext(this, {
639
768
  baseRoster: this.#roster,
640
769
  candidateRoster,
641
770
  entryIDs: envelopeIDs,
771
+ enactedDeviceEntries,
642
772
  ...externalCommitDID !== undefined && {
643
773
  externalCommitDID
644
774
  }
@@ -665,7 +795,9 @@ export function mutexFor(handle) {
665
795
  });
666
796
  }
667
797
  this.#roster = candidateRoster;
798
+ this.#registry = candidateRegistry;
668
799
  if (surfaced.length > 0) this.#onLedgerEntries?.(surfaced);
800
+ this.emitControlEvents(acceptedEntries.filter(({ verified })=>verified.entry.type === DEVICE_ENTRY_TYPE).map(({ verified })=>verified));
669
801
  };
670
802
  return {
671
803
  callback: wrapCommitPolicy(combined, capture),
@@ -725,6 +857,34 @@ export function mutexFor(handle) {
725
857
  return undefined;
726
858
  }
727
859
  /**
860
+ * The device-proof binding at the leaf naming `did`: its bound controller (if any), the embedded
861
+ * controller-log prefix (if bound), and the leaf signature key. Reads the CURRENT ratchet tree —
862
+ * the pre-commit tree in the acceptance pipeline. Undefined when no leaf names the DID.
863
+ */ bindingOfDID(did) {
864
+ const target = normalizeDID(did);
865
+ const tree = this.#state.ratchetTree;
866
+ for (const node of tree){
867
+ if (node == null || node.nodeType !== nodeTypes.leaf) continue;
868
+ const credential = node.leaf.credential;
869
+ if (!('identity' in credential)) continue;
870
+ let parsed;
871
+ try {
872
+ parsed = parseMLSCredentialIdentity(credential.identity);
873
+ } catch {
874
+ continue;
875
+ }
876
+ if (normalizeDID(parsed.id) !== target) continue;
877
+ return {
878
+ leafKey: node.leaf.signaturePublicKey,
879
+ ...parsed.controller != null ? {
880
+ controller: parsed.controller.id,
881
+ prefix: parsed.controller.prefix
882
+ } : {}
883
+ };
884
+ }
885
+ return undefined;
886
+ }
887
+ /**
728
888
  * Read what a Commit says about itself against this handle, WITHOUT advancing state.
729
889
  *
730
890
  * **`null` means "these bytes are not a Commit" and nothing else.** It does not mean "a
@@ -873,9 +1033,20 @@ export function mutexFor(handle) {
873
1033
  baseRoster: args.baseRoster,
874
1034
  candidateRoster: args.candidateRoster,
875
1035
  didOfLeaf: (leafIndex)=>leafToDID.get(leafIndex),
1036
+ // Status-aware, in parity with authority(): only an ACTIVE binding confers its controller's
1037
+ // authority. A revoked device resolves to undefined here, so isAdmin's `controllerOf ?? id`
1038
+ // falls back to the device's own DID — a revoked admin device re-entering as a floating leaf
1039
+ // (which the deny set skips) cannot author membership commits as its former admin profile. The
1040
+ // shared registry controllerOf stays raw (deviceRevoked emission + revoke/label gate need it).
1041
+ controllerOf: (did)=>{
1042
+ const record = handle.registry.devices.get(normalizeDID(did));
1043
+ return record != null && record.status === 'active' ? record.controller : undefined;
1044
+ },
876
1045
  currentExtensions: handle.state.groupContext.extensions,
877
1046
  expectedHeadExtensionData,
878
1047
  commitEnactsEntries: args.entryIDs.length > 0,
1048
+ enactedDeviceEntries: args.enactedDeviceEntries,
1049
+ enactsOnlyDeviceEntries: args.entryIDs.length > 0 && args.enactedDeviceEntries.length === args.entryIDs.length,
879
1050
  ...args.externalCommitDID !== undefined && {
880
1051
  externalCommitDID: args.externalCommitDID
881
1052
  }
@@ -887,10 +1058,9 @@ export function mutexFor(handle) {
887
1058
  credential: group.credential,
888
1059
  context: group.context,
889
1060
  ledger: group.ledger,
890
- cache: group.cache,
891
- resolver: group.resolver,
892
1061
  commitPolicy: group.commitPolicy,
893
1062
  resolveLedgerEntries: group.resolveLedgerEntries,
894
- onLedgerEntries: group.onLedgerEntries
1063
+ onLedgerEntries: group.onLedgerEntries,
1064
+ events: emitterOf(group)
895
1065
  });
896
1066
  }
@@ -1,4 +1,4 @@
1
- import { createInMemoryDIDCache, normalizeDID } from '@kokuin/token';
1
+ import { normalizeDID } from '@kokuin/token';
2
2
  import { decode, encode, generateKeyPackageWithKey, joinGroup as mlsJoinGroup, joinGroupExternal as mlsJoinGroupExternal, mlsMessageDecoder, mlsMessageEncoder, protocolVersions, wireformats } from 'ts-mls';
3
3
  import { sanitizeRatchetTree } from './codec.js';
4
4
  import { buildLeafCapabilities, resolveMlsContext } from './group-context.js';
@@ -9,7 +9,6 @@ import { ledgerEntryDigest, verifyLedgerEntry } from './ledger.js';
9
9
  import { ROLE_ENTRY_TYPE } from './roster.js';
10
10
  export async function processWelcome(params) {
11
11
  const { identity, invite, welcome, keyPackageBundle, ratchetTree, options } = params;
12
- const cache = options?.cache ?? createInMemoryDIDCache();
13
12
  const context = await resolveMlsContext(options);
14
13
  // A Welcome is only this member's when the invite carries a role entry naming
15
14
  // them: an invite minted for someone else is not an invitation to join.
@@ -51,8 +50,6 @@ export async function processWelcome(params) {
51
50
  state,
52
51
  credential,
53
52
  context,
54
- cache,
55
- resolver: options?.resolver,
56
53
  commitPolicy: options?.commitPolicy,
57
54
  resolveLedgerEntries: options?.resolveLedgerEntries,
58
55
  onLedgerEntries: options?.onLedgerEntries
@@ -113,7 +110,6 @@ export async function joinGroupExternal(params) {
113
110
  if (normalizeDID(identity.id) !== normalizeDID(credential.id)) {
114
111
  throw new Error(`joinGroupExternal: identity.id (${identity.id}) must match credential.id (${credential.id}) for resync`);
115
112
  }
116
- const cache = options?.cache ?? createInMemoryDIDCache();
117
113
  const context = await resolveMlsContext(options);
118
114
  const message = decode(mlsMessageDecoder, groupInfoBytes);
119
115
  if (message == null) {
@@ -163,8 +159,6 @@ export async function joinGroupExternal(params) {
163
159
  state: newState,
164
160
  credential,
165
161
  context,
166
- cache,
167
- resolver: options?.resolver,
168
162
  commitPolicy: options?.commitPolicy,
169
163
  resolveLedgerEntries: options?.resolveLedgerEntries,
170
164
  onLedgerEntries: options?.onLedgerEntries
package/lib/group.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  export { type CommitInviteResult, type CommitLedgerEntriesResult, type CreateInviteParams, type CreateInviteResult, commitInvite, commitLedgerEntries, createInvite, InviteRecipientMismatchError, type InviteRecipientMismatchErrorParams, } from './group-commit.js';
2
2
  export { type CreateGroupResult, createGroup, type RestoreGroupParams, restoreGroup, } from './group-create.js';
3
3
  export { createKeyPackageBundle, createLastResortKeyPackageBundle, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, } from './group-credential.js';
4
- export { CommitRejectedError, GroupHandle, type GroupHandleParams, type HeldLedgerEntry, type LedgerLogEntry, } from './group-handle.js';
4
+ export { addDevice, announceControllerBeacon, type DeviceWriteResult, labelDevice, registerDevice, revokeDevice, } from './group-device.js';
5
+ export { CommitRejectedError, GroupHandle, type GroupHandleEvents, type GroupHandleParams, type HeldLedgerEntry, type LedgerLogEntry, } from './group-handle.js';
5
6
  export { type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, type GroupInfoBinding, type InspectGroupInfoResult, inspectGroupInfo, readGroupInfoBinding, readMessageEpoch, } from './group-info.js';
6
7
  export { type RemoveMemberResult, removeMember } from './group-membership.js';
7
8
  export { type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, type ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, } from './group-welcome.js';
package/lib/group.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export { commitInvite, commitLedgerEntries, createInvite, InviteRecipientMismatchError } from './group-commit.js';
2
2
  export { createGroup, restoreGroup } from './group-create.js';
3
3
  export { createKeyPackageBundle, createLastResortKeyPackageBundle, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS } from './group-credential.js';
4
+ export { addDevice, announceControllerBeacon, labelDevice, registerDevice, revokeDevice } from './group-device.js';
4
5
  export { CommitRejectedError, GroupHandle } from './group-handle.js';
5
6
  export { exportGroupInfo, inspectGroupInfo, readGroupInfoBinding, readMessageEpoch } from './group-info.js';
6
7
  export { removeMember } from './group-membership.js';
package/lib/index.d.ts CHANGED
@@ -1,19 +1,22 @@
1
+ export type { EventsSource } from '@sozai/event';
1
2
  export type { Capabilities, GroupContextExtension, IncomingMessageCallback, KeyPackage, Proposal, ProposalWithSender, } from 'ts-mls';
2
3
  export { defaultCapabilities, defaultProposalTypes, makeCustomExtension } from 'ts-mls';
3
4
  export { buildCurrentGroupAnchorExtension, buildGroupAnchorExtension, controlCapabilities, decodeGroupAnchor, encodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, type GroupAnchor, LEDGER_HEAD_EXTENSION_TYPE, readGroupAnchor, readGroupAnchorExtension, } from './anchor.js';
4
- export { createDIDAuthenticationService } from './authentication.js';
5
+ export { createDIDAuthenticationService, MLS_DEVICES_ACT, MLS_DEVICES_RES, MLS_LEAF_ACT, MLS_LEAF_RES, verifyManagementCapability, } from './authentication.js';
5
6
  export { type ClientState, decodeClientState, encodeClientState, sanitizeRatchetTree, } from './codec.js';
6
- export { type GroupMember, type MemberCredential, type MLSCredentialIdentity, parseMLSCredentialIdentity, populateCacheFromCredential, } from './credential.js';
7
+ export { type ControllerBinding, type GroupMember, type MemberCredential, type MLSCredentialIdentity, parseMLSCredentialIdentity, } from './credential.js';
7
8
  export { createNobleCryptoProvider, type NobleCryptoProviderOptions, nobleCryptoProvider, } from './crypto.js';
9
+ export type { LeafBinding } from './device-proof.js';
8
10
  export { CONTROL_ENVELOPE_VERSION, type ControlEnvelope, type DecodeResult, decodeControlEnvelope, encodeControlEnvelope, } from './envelope.js';
9
11
  export { type EnvelopeFoldResult, foldEnvelope } from './envelope-fold.js';
10
12
  export { type FoldDrop, type FoldInput, foldLedger, type LedgerReducer, } from './fold.js';
11
- export { type CommitInviteResult, type CommitLedgerEntriesResult, CommitRejectedError, type CreateGroupResult, type CreateInviteParams, type CreateInviteResult, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, GroupHandle, type GroupHandleParams, type HeldLedgerEntry, type InspectGroupInfoResult, InviteRecipientMismatchError, type InviteRecipientMismatchErrorParams, inspectGroupInfo, type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, type LedgerLogEntry, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, type ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, type RemoveMemberResult, type RestoreGroupParams, readMessageEpoch, removeMember, restoreGroup, } from './group.js';
13
+ export { addDevice, announceControllerBeacon, type CommitInviteResult, type CommitLedgerEntriesResult, CommitRejectedError, type CreateGroupResult, type CreateInviteParams, type CreateInviteResult, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, type DeviceWriteResult, type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, GroupHandle, type GroupHandleEvents, type GroupHandleParams, type HeldLedgerEntry, type InspectGroupInfoResult, InviteRecipientMismatchError, type InviteRecipientMismatchErrorParams, inspectGroupInfo, type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, type LedgerLogEntry, labelDevice, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, type ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, type RemoveMemberResult, type RestoreGroupParams, readMessageEpoch, registerDevice, removeMember, restoreGroup, revokeDevice, } from './group.js';
12
14
  export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, type LedgerHead, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension, } from './head.js';
13
15
  export { decodeKeyPackage, decodePrivateKeyPackage, encodeKeyPackage, encodePrivateKeyPackage, keyPackageRef, } from './key-package-codec.js';
14
16
  export { type LedgerEntry, ledgerEntryDigest, signLedgerEntry, type VerifiedLedgerEntry, verifyLedgerEntry, } from './ledger.js';
15
17
  export { type CommitPolicyContext, defaultCommitPolicy, MissingLedgerEntriesError, } from './policy.js';
16
18
  export { type CreateRecoveryRequestParams, type CreateRecoveryRequestResult, createRecoveryRequest, type OpenSealedGroupInfoParams, type OpenSealedLedgerParams, openSealedGroupInfo, openSealedLedger, RECOVERY_REQUEST_TYPE, type RecoveryRequest, RecoveryRequestError, type RecoveryRequestRejection, SEALED_GROUP_INFO_VERSION, SEALED_LEDGER_VERSION, SealedGroupInfoError, type SealedGroupInfoRejection, SealedLedgerError, type SealedLedgerRejection, type SealedReplyRejection, type SealGroupInfoParams, type SealLedgerParams, sealGroupInfo, sealLedger, type VerifiedRecoveryRequest, } from './recovery.js';
19
+ export { authority, beaconOf, type ControllerBeacon, controllerOf, DEVICE_ENTRY_TYPE, type DeviceOp, type DeviceRecord, type DeviceRegistry, type DeviceValue, denySetOf, foldControl, registrySeed, } from './registry.js';
17
20
  export { adminCount, foldRoster, type GroupPermission, ROLE_ENTRY_TYPE, type RoleValue, type RosterState, roleReducer, } from './roster.js';
18
21
  export type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
19
22
  export { welcomeKeyPackageRefs } from './welcome-refs.js';
package/lib/index.js CHANGED
@@ -1,17 +1,18 @@
1
1
  export { defaultCapabilities, defaultProposalTypes, makeCustomExtension } from 'ts-mls';
2
2
  export { buildCurrentGroupAnchorExtension, buildGroupAnchorExtension, controlCapabilities, decodeGroupAnchor, encodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, LEDGER_HEAD_EXTENSION_TYPE, readGroupAnchor, readGroupAnchorExtension } from './anchor.js';
3
- export { createDIDAuthenticationService } from './authentication.js';
3
+ export { createDIDAuthenticationService, MLS_DEVICES_ACT, MLS_DEVICES_RES, MLS_LEAF_ACT, MLS_LEAF_RES, verifyManagementCapability } from './authentication.js';
4
4
  export { decodeClientState, encodeClientState, sanitizeRatchetTree } from './codec.js';
5
- export { parseMLSCredentialIdentity, populateCacheFromCredential } from './credential.js';
5
+ export { parseMLSCredentialIdentity } from './credential.js';
6
6
  export { createNobleCryptoProvider, nobleCryptoProvider } from './crypto.js';
7
7
  export { CONTROL_ENVELOPE_VERSION, decodeControlEnvelope, encodeControlEnvelope } from './envelope.js';
8
8
  export { foldEnvelope } from './envelope-fold.js';
9
9
  export { foldLedger } from './fold.js';
10
- export { CommitRejectedError, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, exportGroupInfo, GroupHandle, InviteRecipientMismatchError, inspectGroupInfo, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, processWelcome, processWelcomeOnce, readMessageEpoch, removeMember, restoreGroup } from './group.js';
10
+ export { addDevice, announceControllerBeacon, CommitRejectedError, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, exportGroupInfo, GroupHandle, InviteRecipientMismatchError, inspectGroupInfo, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, labelDevice, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, processWelcome, processWelcomeOnce, readMessageEpoch, registerDevice, removeMember, restoreGroup, revokeDevice } from './group.js';
11
11
  export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension } from './head.js';
12
12
  export { decodeKeyPackage, decodePrivateKeyPackage, encodeKeyPackage, encodePrivateKeyPackage, keyPackageRef } from './key-package-codec.js';
13
13
  export { ledgerEntryDigest, signLedgerEntry, verifyLedgerEntry } from './ledger.js';
14
14
  export { defaultCommitPolicy, MissingLedgerEntriesError } from './policy.js';
15
15
  export { createRecoveryRequest, openSealedGroupInfo, openSealedLedger, RECOVERY_REQUEST_TYPE, RecoveryRequestError, SEALED_GROUP_INFO_VERSION, SEALED_LEDGER_VERSION, SealedGroupInfoError, SealedLedgerError, sealGroupInfo, sealLedger } from './recovery.js';
16
+ export { authority, beaconOf, controllerOf, DEVICE_ENTRY_TYPE, denySetOf, foldControl, registrySeed } from './registry.js';
16
17
  export { adminCount, foldRoster, ROLE_ENTRY_TYPE, roleReducer } from './roster.js';
17
18
  export { welcomeKeyPackageRefs } from './welcome-refs.js';
package/lib/policy.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { GroupContextExtension, IncomingMessageAction, ProposalWithSender } from 'ts-mls';
2
+ import type { DeviceOp } from './registry.js';
2
3
  import type { RosterState } from './roster.js';
3
4
  /**
4
5
  * Everything the receiving-side gate needs, resolved by the caller. Pure: no group handle, no
@@ -15,6 +16,11 @@ export type CommitPolicyContext = {
15
16
  * target: a Remove of a leaf still `admin` here carried no demotion and is rejected. */
16
17
  candidateRoster: RosterState;
17
18
  didOfLeaf: (leafIndex: number) => string | undefined;
19
+ /** Resolve a device DID to its controller (profile) via the pre-commit folded registry, or
20
+ * undefined. ACTIVE bindings only — a revoked device resolves to undefined here, so its
21
+ * authority falls back to its own DID (parity with `authority()`; a revoked device confers no
22
+ * controller authority). `isAdmin` reads this to apply authority = controller ?? id. */
23
+ controllerOf: (did: string) => string | undefined;
18
24
  /** The pre-commit GroupContext extension list. A group_context_extensions commit may change
19
25
  * nothing in it but the ledger_head entry. */
20
26
  currentExtensions: Array<GroupContextExtension>;
@@ -24,6 +30,20 @@ export type CommitPolicyContext = {
24
30
  expectedHeadExtensionData: Uint8Array;
25
31
  /** Whether the commit's envelope names any entries. */
26
32
  commitEnactsEntries: boolean;
33
+ /** The kumiai.device entries this commit enacts — subjects normalized, in envelope order; empty for
34
+ * a non-device commit. The device carve-out reads these to accept device-scoped proposals
35
+ * STRUCTURALLY. Load-bearing invariant: this is safe only because the acceptance-pipeline proof gate
36
+ * (verifyDeviceEntry) authorized these entries earlier in the same pipeline, before this policy runs
37
+ * — see group-handle.ts #prepareCommitPipeline, where precomputedReject short-circuits ahead of
38
+ * defaultCommitPolicy. The policy never grants device authority on its own. */
39
+ enactedDeviceEntries: ReadonlyArray<{
40
+ subject: string;
41
+ op: DeviceOp;
42
+ }>;
43
+ /** True iff the commit enacts at least one entry AND every enacted entry is a kumiai.device entry —
44
+ * the device-only precondition for the head-move carve-out. A commit mixing a role entry has this
45
+ * false, so its mandatory head-move falls back to the admin rule. */
46
+ enactsOnlyDeviceEntries: boolean;
27
47
  externalCommitDID?: string;
28
48
  };
29
49
  /** A commit or standalone proposal handed to the gate, matching the ts-mls callback shape. */
package/lib/policy.js CHANGED
@@ -16,6 +16,17 @@ function bytesEqual(a, b) {
16
16
  /**
17
17
  * Fail-closed admin check: no DID, a DID absent from the roster, or any role but `admin`, is
18
18
  * not admin. An undefined leaf (external commit with no committer) is never admin.
19
+ *
20
+ * Authority resolves through the device registry: `authority(did) = controllerOf(did) ?? did`,
21
+ * where `controllerOf` resolves ACTIVE bindings only (a revoked device resolves to its own DID).
22
+ * A device leaf of an admin profile is admin, because the profile — not the device — is what
23
+ * the roster actually grants a role to. This resolution is deliberately applied only here, to
24
+ * the *acting* sender, and NOT to the Remove-target admin check (`evaluateProposal`'s `remove`
25
+ * case) or the external-commit DID match (`evaluateExternalCommit`): those compare an actual
26
+ * device leaf (the leaf being removed, the leaf a resynced external commit proves control of),
27
+ * not the authority that acts. Resolving authority there too would mean removing one device of
28
+ * an admin profile requires demoting the whole profile first — which is not the rule this
29
+ * policy enforces.
19
30
  */ function isAdmin(context, leafIndex) {
20
31
  if (leafIndex === undefined) {
21
32
  return false;
@@ -24,7 +35,9 @@ function bytesEqual(a, b) {
24
35
  if (did === undefined) {
25
36
  return false;
26
37
  }
27
- return context.baseRoster.roles.get(normalizeDID(did)) === 'admin';
38
+ const normalized = normalizeDID(did);
39
+ const authority = context.controllerOf(normalized) ?? normalized;
40
+ return context.baseRoster.roles.get(authority) === 'admin';
28
41
  }
29
42
  /**
30
43
  * The group-context-extensions rule: an admin may replace the extension list only to move the
@@ -91,7 +104,10 @@ function bytesEqual(a, b) {
91
104
  switch(proposal.proposalType){
92
105
  case defaultProposalTypes.add:
93
106
  {
94
- if (!isAdmin(context, effectiveSender)) {
107
+ // A credential that names no DID (non-`basic`, or malformed) is rejected rather than
108
+ // trusted. `didFromCredential` is total, so nothing here can throw past this boundary.
109
+ const addedDID = didFromCredential(proposal.add.keyPackage.leafNode.credential);
110
+ if (addedDID === undefined) {
95
111
  return 'reject';
96
112
  }
97
113
  // Bind the leaf that joins to the roster this commit produces, mirroring the binding
@@ -105,14 +121,14 @@ function bytesEqual(a, b) {
105
121
  // Membership, not provenance: the question is whether the added DID holds a role, never
106
122
  // whether this commit granted it. A re-add — a second device, a rejoin after removal —
107
123
  // enacts no entry and must keep working.
108
- //
109
- // A credential that names no DID (non-`basic`, or malformed) is rejected rather than
110
- // trusted. `didFromCredential` is total, so nothing here can throw past this boundary.
111
- const addedDID = didFromCredential(proposal.add.keyPackage.leafNode.credential);
112
- if (addedDID === undefined) {
113
- return 'reject';
124
+ if (isAdmin(context, effectiveSender) && context.candidateRoster.roles.has(addedDID)) {
125
+ return 'accept';
114
126
  }
115
- return context.candidateRoster.roles.has(addedDID) ? 'accept' : 'reject';
127
+ // Device carve-out: an Add whose added DID is the subject of an enacted device `add` entry is
128
+ // authorized by that entry's proof (already verified upstream), not by a roster role — no
129
+ // admin sender required.
130
+ const addedNorm = normalizeDID(addedDID);
131
+ return context.enactedDeviceEntries.some((e)=>e.op === 'add' && e.subject === addedNorm) ? 'accept' : 'reject';
116
132
  }
117
133
  // Split from `add` above only so they stop sharing an arm that reads `proposal.add`.
118
134
  // Neither carries a leaf, so neither has anything to bind to the roster.
@@ -131,12 +147,17 @@ function bytesEqual(a, b) {
131
147
  if (isAdmin(context, effectiveSender)) {
132
148
  return 'accept';
133
149
  }
134
- return effectiveSender !== undefined && proposal.remove.removed === effectiveSender ? 'accept' : 'reject';
150
+ if (effectiveSender !== undefined && proposal.remove.removed === effectiveSender) {
151
+ return 'accept';
152
+ }
153
+ // Device carve-out: a Remove whose target is the subject of an enacted device `revoke` entry is
154
+ // authorized by that entry's proof. The anti-demotion check above still guards an admin leaf.
155
+ return removedDID !== undefined && context.enactedDeviceEntries.some((e)=>e.op === 'revoke' && e.subject === normalizeDID(removedDID)) ? 'accept' : 'reject';
135
156
  }
136
157
  case defaultProposalTypes.update:
137
158
  return 'accept';
138
159
  case defaultProposalTypes.group_context_extensions:
139
- return isAdmin(context, effectiveSender) ? evaluateGroupContextExtensions(proposal.groupContextExtensions.extensions, context) : 'reject';
160
+ return isAdmin(context, effectiveSender) || context.enactsOnlyDeviceEntries ? evaluateGroupContextExtensions(proposal.groupContextExtensions.extensions, context) : 'reject';
140
161
  default:
141
162
  return 'reject';
142
163
  }