@kumiai/mls 0.6.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,15 +155,15 @@ 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;
@@ -168,6 +179,7 @@ export function mutexFor(handle) {
168
179
  /** Entry bodies by content id, for resolving the ids an envelope names. A body is
169
180
  * the same wherever it appears in the log, so this store is keyed. */ #entryBodies;
170
181
  #roster;
182
+ #registry;
171
183
  constructor(params){
172
184
  this.#state = params.state;
173
185
  this.#credential = params.credential;
@@ -193,7 +205,15 @@ export function mutexFor(handle) {
193
205
  verified
194
206
  }
195
207
  ]));
196
- 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());
197
217
  }
198
218
  get groupID() {
199
219
  return this.#credential.groupID;
@@ -240,6 +260,68 @@ export function mutexFor(handle) {
240
260
  /** The control roster folded from the anchor and every applied ledger entry. */ get roster() {
241
261
  return this.#roster;
242
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
+ }
243
325
  /**
244
326
  * Verify signed ledger tokens, append the valid ones in the order given, and
245
327
  * refold the roster. Tokens that fail verification or whose groupID mismatches are
@@ -254,6 +336,7 @@ export function mutexFor(handle) {
254
336
  * folds an invite once). Serialized on the handle's mutex.
255
337
  */ async applyLedgerEntries(tokens) {
256
338
  return mutexFor(this).run(async ()=>{
339
+ const appended = [];
257
340
  for (const token of tokens){
258
341
  const verified = await verifyLedgerEntry(token);
259
342
  if (verified == null || verified.entry.groupID !== this.groupID) continue;
@@ -267,8 +350,12 @@ export function mutexFor(handle) {
267
350
  token,
268
351
  verified
269
352
  });
353
+ appended.push(verified);
270
354
  }
271
- 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;
272
359
  });
273
360
  }
274
361
  /**
@@ -352,6 +439,9 @@ export function mutexFor(handle) {
352
439
  // What this bootstrap ADDS, in log order, minus the reserved `kumiai.*` types the fold
353
440
  // consumes itself — the same rule the commit path surfaces by.
354
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);
355
445
  this.#ledger = log;
356
446
  this.#entryBodies = new Map(log.map(({ entryID, token, verified })=>[
357
447
  entryID,
@@ -360,7 +450,9 @@ export function mutexFor(handle) {
360
450
  verified
361
451
  }
362
452
  ]));
363
- 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;
364
456
  // SURFACED HERE TOO, not only on the commit path. A heal is how a peer that missed commits
365
457
  // catches up — it rejoins, gathers the whole ledger, and lands here — so a bootstrap that
366
458
  // said nothing left a host consuming `onLedgerEntries` as an event stream permanently
@@ -370,6 +462,7 @@ export function mutexFor(handle) {
370
462
  // Deduped against what this handle already held, so a peer bootstrapping over a partial
371
463
  // ledger is not re-notified of entries it has already seen.
372
464
  if (surfaced.length > 0) this.#onLedgerEntries?.(surfaced);
465
+ this.emitControlEvents(enactedDevice);
373
466
  });
374
467
  }
375
468
  get memberCount() {
@@ -393,10 +486,18 @@ export function mutexFor(handle) {
393
486
  // refuses to build a peer:4 identity without a long form, and validateCredential
394
487
  // rejects any peer:4 leaf lacking one before it can enter a ratchet tree. restore
395
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;
396
491
  yield {
397
492
  leafIndex: i / 2,
398
493
  id: parsed.id,
399
- longForm: parsed.longForm ?? parsed.id
494
+ longForm: parsed.longForm ?? parsed.id,
495
+ ...controller ? {
496
+ controller
497
+ } : {},
498
+ ...beacon ? {
499
+ controllerBeacon: beacon
500
+ } : {}
400
501
  };
401
502
  }
402
503
  }
@@ -575,6 +676,7 @@ export function mutexFor(handle) {
575
676
  }
576
677
  let precomputedReject = false;
577
678
  let candidateRoster = this.#roster;
679
+ let candidateRegistry = this.#registry;
578
680
  let surfaced = [];
579
681
  let acceptedEntries = [];
580
682
  let envelopeIDs = [];
@@ -634,21 +736,39 @@ export function mutexFor(handle) {
634
736
  ]);
635
737
  return input;
636
738
  });
637
- const foldResult = foldEnvelope(this.#roster, ordered, this.groupID);
739
+ const foldResult = foldEnvelope(this.#roster, this.#registry, ordered, this.groupID);
638
740
  if (!foldResult.ok) {
639
741
  precomputedReject = true;
640
742
  } else {
641
743
  candidateRoster = foldResult.roster;
744
+ candidateRegistry = foldResult.registry;
642
745
  surfaced = foldResult.surfaced;
643
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
+ }
644
759
  }
645
760
  }
646
761
  }
647
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
+ }));
648
767
  const context = buildCommitPolicyContext(this, {
649
768
  baseRoster: this.#roster,
650
769
  candidateRoster,
651
770
  entryIDs: envelopeIDs,
771
+ enactedDeviceEntries,
652
772
  ...externalCommitDID !== undefined && {
653
773
  externalCommitDID
654
774
  }
@@ -675,7 +795,9 @@ export function mutexFor(handle) {
675
795
  });
676
796
  }
677
797
  this.#roster = candidateRoster;
798
+ this.#registry = candidateRegistry;
678
799
  if (surfaced.length > 0) this.#onLedgerEntries?.(surfaced);
800
+ this.emitControlEvents(acceptedEntries.filter(({ verified })=>verified.entry.type === DEVICE_ENTRY_TYPE).map(({ verified })=>verified));
679
801
  };
680
802
  return {
681
803
  callback: wrapCommitPolicy(combined, capture),
@@ -735,6 +857,34 @@ export function mutexFor(handle) {
735
857
  return undefined;
736
858
  }
737
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
+ /**
738
888
  * Read what a Commit says about itself against this handle, WITHOUT advancing state.
739
889
  *
740
890
  * **`null` means "these bytes are not a Commit" and nothing else.** It does not mean "a
@@ -883,9 +1033,20 @@ export function mutexFor(handle) {
883
1033
  baseRoster: args.baseRoster,
884
1034
  candidateRoster: args.candidateRoster,
885
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
+ },
886
1045
  currentExtensions: handle.state.groupContext.extensions,
887
1046
  expectedHeadExtensionData,
888
1047
  commitEnactsEntries: args.entryIDs.length > 0,
1048
+ enactedDeviceEntries: args.enactedDeviceEntries,
1049
+ enactsOnlyDeviceEntries: args.entryIDs.length > 0 && args.enactedDeviceEntries.length === args.entryIDs.length,
889
1050
  ...args.externalCommitDID !== undefined && {
890
1051
  externalCommitDID: args.externalCommitDID
891
1052
  }
@@ -899,6 +1060,7 @@ export function mutexFor(handle) {
899
1060
  ledger: group.ledger,
900
1061
  commitPolicy: group.commitPolicy,
901
1062
  resolveLedgerEntries: group.resolveLedgerEntries,
902
- onLedgerEntries: group.onLedgerEntries
1063
+ onLedgerEntries: group.onLedgerEntries,
1064
+ events: emitterOf(group)
903
1065
  });
904
1066
  }
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, } 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
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
  }
@@ -0,0 +1,89 @@
1
+ import type { GroupAnchor } from './anchor.js';
2
+ import type { FoldDrop, FoldInput } from './fold.js';
3
+ import type { VerifiedLedgerEntry } from './ledger.js';
4
+ import { type RosterState } from './roster.js';
5
+ /** The reserved control type carrying a device-registry mutation. One branch, one namespace slot. */
6
+ export declare const DEVICE_ENTRY_TYPE = "kumiai.device";
7
+ /** The device lifecycle operations plus the advisory controller-log beacon. */
8
+ export type DeviceOp = 'register' | 'add' | 'revoke' | 'label' | 'beacon';
9
+ /**
10
+ * A `kumiai.device` entry's `value`. `controller` names the profile a register/add binds to;
11
+ * `label` renames; `capability` carries the management-capability proof a manage op is verified
12
+ * against IN THE ACCEPTANCE PIPELINE — the pure fold never reads it (recorded-once trust).
13
+ */
14
+ export type DeviceValue = {
15
+ op: DeviceOp;
16
+ controller?: string;
17
+ label?: string;
18
+ capability?: string;
19
+ /** Beacon only: the length of the controller's FULL log at announcement time. */
20
+ logLength?: number;
21
+ /** Beacon only: the head digest of the controller's FULL log at announcement time. */
22
+ headDigest?: string;
23
+ };
24
+ /** A folded device binding. `controller` is the profile DID; `status` gates the deny set. */
25
+ export type DeviceRecord = {
26
+ controller: string;
27
+ status: 'active' | 'revoked';
28
+ label?: string;
29
+ };
30
+ /** An advisory pointer to a controller's FULL log head. Never a validation input. */
31
+ export type ControllerBeacon = {
32
+ logLength: number;
33
+ headDigest: string;
34
+ };
35
+ /**
36
+ * The group-folded device registry: `device DID -> record`, keyed by normalized DID. A pure
37
+ * function of the accepted `kumiai.device` entries, folded beside {@link RosterState}. Two views
38
+ * 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.
40
+ */
41
+ export type DeviceRegistry = {
42
+ devices: ReadonlyMap<string, DeviceRecord>;
43
+ controllers: ReadonlyMap<string, ControllerBeacon>;
44
+ };
45
+ export declare function registrySeed(): DeviceRegistry;
46
+ /** Structural guard: a value carrying a known `op` (and, for register/add, a string controller). */
47
+ export declare function isDeviceValue(value: unknown): value is DeviceValue;
48
+ /**
49
+ * The registry fold step. Pure, order-dependent, authorization-free — a device entry's authority
50
+ * 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.
53
+ */
54
+ export declare function registryApply(verified: VerifiedLedgerEntry<DeviceValue>, state: DeviceRegistry): DeviceRegistry;
55
+ /** The profile a device is bound to in the folded registry, or undefined — the authority input. */
56
+ export declare function controllerOf(registry: DeviceRegistry, deviceDID: string): string | undefined;
57
+ /** The advisory beacon a controller last announced, or undefined. Never a validation input. */
58
+ export declare function beaconOf(registry: DeviceRegistry, controllerDID: string): ControllerBeacon | undefined;
59
+ /**
60
+ * The deny set Slice 1's seam consumes: the device DIDs at `status: 'revoked'` NOW. Matched, never
61
+ * enumerated by consumers (`has`), holding device DIDs only, per the kokuin deny-set rule.
62
+ */
63
+ export declare function denySetOf(registry: DeviceRegistry): ReadonlySet<string>;
64
+ /**
65
+ * The universal rule: an ACTIVE binding resolves the issuer to its controller; anything else
66
+ * resolves to the issuer itself. A revoked binding confers no authority — terminal revocation only
67
+ * ever subtracts — so a revoked device re-entering as a floating leaf, or a role entry it signed
68
+ * before revocation but enacted after, must not resolve to its former controller. (Note the split:
69
+ * {@link controllerOf} is the RAW lookup, deliberately status-blind, since the deviceRevoked event
70
+ * emission and the revoke/label gate read the surviving binding of a just-revoked device.)
71
+ */
72
+ export declare function authority(registry: DeviceRegistry, issuer: string): string;
73
+ /**
74
+ * Fold the whole control ledger into BOTH projections in one ordered pass, so a role entry's
75
+ * authority resolves against the registry-so-far (device entries strictly earlier), never a
76
+ * later binding. This is the determinism-preserving replacement for driving two independent
77
+ * per-type folds: {@link foldLedger}'s own doc warns that a reducer whose authority reads another
78
+ * entry type cannot be driven by a per-type applier — the roster reducer now reads the registry,
79
+ * so both advance together here.
80
+ *
81
+ * A `kumiai.device` entry updates the registry (trusted — proofs are the pipeline's gate). A
82
+ * `kumiai.role` entry is authorized by `roster.roles.get(authority(registry, issuer)) === 'admin'`
83
+ * and must not empty the admin set. Every other type, a groupID mismatch, or a malformed value is
84
+ * dropped (never thrown), routed through `onDrop` exactly as {@link foldRoster}.
85
+ */
86
+ export declare function foldControl(entries: Array<FoldInput>, anchor: GroupAnchor, groupID: string, onDrop?: (drop: FoldDrop) => void): {
87
+ roster: RosterState;
88
+ registry: DeviceRegistry;
89
+ };