@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,5 +1,11 @@
1
1
  import { type Capabilities, type GroupContextExtension, type MlsContext } from 'ts-mls';
2
2
  import type { GroupOptions } from './types.js';
3
+ /** Late-bound provider of a context's device deny set, pointed at the live handle after construction. */
4
+ export type DeviceDenyHolder = {
5
+ provider: () => ReadonlySet<string>;
6
+ };
7
+ /** The deny holder for a context built by {@link resolveMlsContext}, or undefined for others. */
8
+ export declare function deviceDenyHolderFor(context: MlsContext): DeviceDenyHolder | undefined;
3
9
  export declare function resolveMlsContext(options?: GroupOptions): Promise<MlsContext>;
4
10
  /**
5
11
  * Build the leaf-node capabilities for a member joining or creating a group. RFC
@@ -2,14 +2,28 @@ import { defaultCapabilities, getCiphersuiteImpl } from 'ts-mls';
2
2
  import { createDIDAuthenticationService } from './authentication.js';
3
3
  import { nobleCryptoProvider } from './crypto.js';
4
4
  const DEFAULT_CIPHERSUITE = 'MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519';
5
+ const EMPTY_DENY = new Set();
6
+ const DENY_HOLDERS = new WeakMap();
7
+ /** The deny holder for a context built by {@link resolveMlsContext}, or undefined for others. */ export function deviceDenyHolderFor(context) {
8
+ return DENY_HOLDERS.get(context);
9
+ }
5
10
  export async function resolveMlsContext(options) {
6
11
  const name = options?.ciphersuiteName ?? DEFAULT_CIPHERSUITE;
7
12
  const cipherSuite = await getCiphersuiteImpl(name, options?.cryptoProvider ?? nobleCryptoProvider);
8
- const authService = createDIDAuthenticationService();
9
- return {
13
+ // The deny set cannot be known here — the handle that folds it does not exist yet. Bind a mutable
14
+ // holder the auth service reads; the GroupHandle constructor points it at its own currentDenySet().
15
+ const holder = {
16
+ provider: ()=>EMPTY_DENY
17
+ };
18
+ const authService = createDIDAuthenticationService({
19
+ deviceDenySet: ()=>holder.provider()
20
+ });
21
+ const context = {
10
22
  cipherSuite,
11
23
  authService
12
24
  };
25
+ DENY_HOLDERS.set(context, holder);
26
+ return context;
13
27
  }
14
28
  /**
15
29
  * Build the leaf-node capabilities for a member joining or creating a group. RFC
@@ -0,0 +1,67 @@
1
+ import { type SigningIdentity } from '@kokuin/token';
2
+ import { type KeyPackage } from 'ts-mls';
3
+ import { type GroupHandle } from './group-handle.js';
4
+ export type DeviceWriteResult = {
5
+ /** Framed MLSMessage bytes. The caller (kubun) broadcasts to existing members via its DS. */
6
+ commitMessage: Uint8Array;
7
+ newGroup: GroupHandle;
8
+ /** Post-commit epoch (== newGroup.epoch). */
9
+ epoch: bigint;
10
+ };
11
+ /**
12
+ * Record a `device -> controller` binding: self-attested (leaf) when `device` is the caller's own,
13
+ * or management-capability-authorized (`capability`) when recording a co-device already in the
14
+ * group. Proof gating runs in `commitWithEntries` (authoring side) and every receiver's pipeline —
15
+ * no admin role is required. Returns the commit bytes to broadcast.
16
+ */
17
+ export declare function registerDevice(group: GroupHandle, identity: SigningIdentity, params: {
18
+ device: string;
19
+ controller: string;
20
+ capability?: string;
21
+ }): Promise<DeviceWriteResult>;
22
+ /**
23
+ * Rename a device already bound in the registry. A manage op — authorized by the profile's
24
+ * management capability (the issuer is a device of `controllerOf(device)`); no admin role required.
25
+ */
26
+ export declare function labelDevice(group: GroupHandle, identity: SigningIdentity, params: {
27
+ device: string;
28
+ label: string;
29
+ capability: string;
30
+ }): Promise<DeviceWriteResult>;
31
+ /**
32
+ * Bring a co-device into the group WITHOUT a group admin: an MLS Add of the new device's key
33
+ * package plus a `kumiai.device` `add` entry, both authorized by the profile's management
34
+ * capability. Binds the added leaf to `device`/`controller` (the key package must present `device`).
35
+ * Returns the Commit + Welcome bytes.
36
+ */
37
+ export declare function addDevice(group: GroupHandle, identity: SigningIdentity, params: {
38
+ keyPackage: KeyPackage;
39
+ device: string;
40
+ controller: string;
41
+ capability: string;
42
+ }): Promise<DeviceWriteResult & {
43
+ welcomeMessage: Uint8Array;
44
+ }>;
45
+ /**
46
+ * Revoke a device: ONE commit, TWO effects, matching the two surfaces the kokuin security doc
47
+ * sanctions. (1) a `kumiai.device` `revoke` entry — folds the subject to `revoked`, so the derived
48
+ * deny set gains it (closing Slice 1's external-rejoin path, which the deny set governs). (2) if the
49
+ * subject currently holds a leaf, an MLS Remove of it in the SAME commit (the deny set alone leaves a
50
+ * stale leaf; the Remove alone lets it rejoin on its still-valid bound-leaf capability). Both are
51
+ * required. Authorized by the profile's management capability; no admin role.
52
+ */
53
+ export declare function revokeDevice(group: GroupHandle, identity: SigningIdentity, params: {
54
+ device: string;
55
+ capability: string;
56
+ }): Promise<DeviceWriteResult>;
57
+ /**
58
+ * Announce the controller's FULL log head into the group as folded, cross-peer-consistent state.
59
+ * Advisory only — it gates nothing. Authored by any bound device of `controller` (self-scoped, no
60
+ * management capability). Publish only-on-change and only when the log meaningfully advances: each
61
+ * call is a permanent ledger entry (replayed at every welcome, no compaction).
62
+ */
63
+ export declare function announceControllerBeacon(group: GroupHandle, identity: SigningIdentity, params: {
64
+ controller: string;
65
+ logLength: number;
66
+ headDigest: string;
67
+ }): Promise<DeviceWriteResult>;
@@ -0,0 +1,206 @@
1
+ import { normalizeDID } from '@kokuin/token';
2
+ import { defaultCredentialTypes, defaultProposalTypes, encode, isDefaultCredential, mlsMessageEncoder } from 'ts-mls';
3
+ import { parseMLSCredentialIdentity } from './credential.js';
4
+ import { commitWithEntries } from './group-commit.js';
5
+ import { deriveGroup, mutexFor } from './group-handle.js';
6
+ import { signLedgerEntry } from './ledger.js';
7
+ import { DEVICE_ENTRY_TYPE } from './registry.js';
8
+ /**
9
+ * Record a `device -> controller` binding: self-attested (leaf) when `device` is the caller's own,
10
+ * or management-capability-authorized (`capability`) when recording a co-device already in the
11
+ * group. Proof gating runs in `commitWithEntries` (authoring side) and every receiver's pipeline —
12
+ * no admin role is required. Returns the commit bytes to broadcast.
13
+ */ export async function registerDevice(group, identity, params) {
14
+ return mutexFor(group).run(async ()=>{
15
+ const token = await signLedgerEntry(identity, {
16
+ type: DEVICE_ENTRY_TYPE,
17
+ groupID: group.groupID,
18
+ subject: params.device,
19
+ value: {
20
+ op: 'register',
21
+ controller: params.controller,
22
+ ...params.capability != null ? {
23
+ capability: params.capability
24
+ } : {}
25
+ }
26
+ });
27
+ const result = await commitWithEntries(group, [], [
28
+ token
29
+ ], {
30
+ requireAdmin: false
31
+ });
32
+ const newGroup = deriveGroup(group, result.newState);
33
+ await newGroup.applyLedgerEntries([
34
+ token
35
+ ]);
36
+ return {
37
+ commitMessage: encode(mlsMessageEncoder, result.commit),
38
+ newGroup,
39
+ epoch: newGroup.epoch
40
+ };
41
+ });
42
+ }
43
+ /**
44
+ * Rename a device already bound in the registry. A manage op — authorized by the profile's
45
+ * management capability (the issuer is a device of `controllerOf(device)`); no admin role required.
46
+ */ export async function labelDevice(group, identity, params) {
47
+ return mutexFor(group).run(async ()=>{
48
+ const token = await signLedgerEntry(identity, {
49
+ type: DEVICE_ENTRY_TYPE,
50
+ groupID: group.groupID,
51
+ subject: params.device,
52
+ value: {
53
+ op: 'label',
54
+ label: params.label,
55
+ capability: params.capability
56
+ }
57
+ });
58
+ const result = await commitWithEntries(group, [], [
59
+ token
60
+ ], {
61
+ requireAdmin: false
62
+ });
63
+ const newGroup = deriveGroup(group, result.newState);
64
+ await newGroup.applyLedgerEntries([
65
+ token
66
+ ]);
67
+ return {
68
+ commitMessage: encode(mlsMessageEncoder, result.commit),
69
+ newGroup,
70
+ epoch: newGroup.epoch
71
+ };
72
+ });
73
+ }
74
+ /**
75
+ * Bring a co-device into the group WITHOUT a group admin: an MLS Add of the new device's key
76
+ * package plus a `kumiai.device` `add` entry, both authorized by the profile's management
77
+ * capability. Binds the added leaf to `device`/`controller` (the key package must present `device`).
78
+ * Returns the Commit + Welcome bytes.
79
+ */ export async function addDevice(group, identity, params) {
80
+ return mutexFor(group).run(async ()=>{
81
+ // Bind the added leaf to the entry's subject — the key package must present `device`.
82
+ const credential = params.keyPackage.leafNode.credential;
83
+ if (!isDefaultCredential(credential) || credential.credentialType !== defaultCredentialTypes.basic) {
84
+ throw new Error('addDevice: the key package carries a non-basic credential, which names no device DID');
85
+ }
86
+ const presentedDID = normalizeDID(parseMLSCredentialIdentity(credential.identity).id);
87
+ if (presentedDID !== normalizeDID(params.device)) {
88
+ throw new Error(`addDevice: the key package presents ${presentedDID}, not the device ${normalizeDID(params.device)}`);
89
+ }
90
+ const token = await signLedgerEntry(identity, {
91
+ type: DEVICE_ENTRY_TYPE,
92
+ groupID: group.groupID,
93
+ subject: params.device,
94
+ value: {
95
+ op: 'add',
96
+ controller: params.controller,
97
+ capability: params.capability
98
+ }
99
+ });
100
+ const addProposal = {
101
+ proposalType: defaultProposalTypes.add,
102
+ add: {
103
+ keyPackage: params.keyPackage
104
+ }
105
+ };
106
+ const result = await commitWithEntries(group, [
107
+ addProposal
108
+ ], [
109
+ token
110
+ ], {
111
+ ratchetTreeExtension: true,
112
+ requireAdmin: false
113
+ });
114
+ if (result.welcome == null) {
115
+ throw new Error('addDevice: expected a Welcome message for the add proposal');
116
+ }
117
+ const newGroup = deriveGroup(group, result.newState);
118
+ await newGroup.applyLedgerEntries([
119
+ token
120
+ ]);
121
+ return {
122
+ commitMessage: encode(mlsMessageEncoder, result.commit),
123
+ welcomeMessage: encode(mlsMessageEncoder, result.welcome),
124
+ newGroup,
125
+ epoch: newGroup.epoch
126
+ };
127
+ });
128
+ }
129
+ /**
130
+ * Revoke a device: ONE commit, TWO effects, matching the two surfaces the kokuin security doc
131
+ * sanctions. (1) a `kumiai.device` `revoke` entry — folds the subject to `revoked`, so the derived
132
+ * deny set gains it (closing Slice 1's external-rejoin path, which the deny set governs). (2) if the
133
+ * subject currently holds a leaf, an MLS Remove of it in the SAME commit (the deny set alone leaves a
134
+ * stale leaf; the Remove alone lets it rejoin on its still-valid bound-leaf capability). Both are
135
+ * required. Authorized by the profile's management capability; no admin role.
136
+ */ export async function revokeDevice(group, identity, params) {
137
+ return mutexFor(group).run(async ()=>{
138
+ const token = await signLedgerEntry(identity, {
139
+ type: DEVICE_ENTRY_TYPE,
140
+ groupID: group.groupID,
141
+ subject: params.device,
142
+ value: {
143
+ op: 'revoke',
144
+ capability: params.capability
145
+ }
146
+ });
147
+ const leafIndex = group.findMemberLeafIndex(params.device);
148
+ const proposals = leafIndex === undefined ? [] : [
149
+ {
150
+ proposalType: defaultProposalTypes.remove,
151
+ remove: {
152
+ removed: leafIndex
153
+ }
154
+ }
155
+ ];
156
+ const result = await commitWithEntries(group, proposals, [
157
+ token
158
+ ], {
159
+ requireAdmin: false
160
+ });
161
+ const newGroup = deriveGroup(group, result.newState);
162
+ const enacted = await newGroup.applyLedgerEntries([
163
+ token
164
+ ]);
165
+ newGroup.emitControlEvents(enacted);
166
+ return {
167
+ commitMessage: encode(mlsMessageEncoder, result.commit),
168
+ newGroup,
169
+ epoch: newGroup.epoch
170
+ };
171
+ });
172
+ }
173
+ /**
174
+ * Announce the controller's FULL log head into the group as folded, cross-peer-consistent state.
175
+ * Advisory only — it gates nothing. Authored by any bound device of `controller` (self-scoped, no
176
+ * management capability). Publish only-on-change and only when the log meaningfully advances: each
177
+ * call is a permanent ledger entry (replayed at every welcome, no compaction).
178
+ */ export async function announceControllerBeacon(group, identity, params) {
179
+ return mutexFor(group).run(async ()=>{
180
+ const token = await signLedgerEntry(identity, {
181
+ type: DEVICE_ENTRY_TYPE,
182
+ groupID: group.groupID,
183
+ subject: params.controller,
184
+ value: {
185
+ op: 'beacon',
186
+ logLength: params.logLength,
187
+ headDigest: params.headDigest
188
+ }
189
+ });
190
+ const result = await commitWithEntries(group, [], [
191
+ token
192
+ ], {
193
+ requireAdmin: false
194
+ });
195
+ const newGroup = deriveGroup(group, result.newState);
196
+ const enacted = await newGroup.applyLedgerEntries([
197
+ token
198
+ ]);
199
+ newGroup.emitControlEvents(enacted);
200
+ return {
201
+ commitMessage: encode(mlsMessageEncoder, result.commit),
202
+ newGroup,
203
+ epoch: newGroup.epoch
204
+ };
205
+ });
206
+ }
@@ -1,11 +1,29 @@
1
+ import { EventEmitter, type EventsSource } from '@sozai/event';
1
2
  import { type ClientState, type IncomingMessageCallback, type MlsContext, type ProposalWithSender } from 'ts-mls';
2
3
  import { type GroupAnchor } from './anchor.js';
3
4
  import { type GroupMember, type MemberCredential } from './credential.js';
5
+ import { type LeafBinding } from './device-proof.js';
4
6
  import { type VerifiedLedgerEntry } from './ledger.js';
5
7
  import { type Mutex } from './mutex.js';
6
8
  import { type CommitPolicyContext } from './policy.js';
7
- import { type RosterState } from './roster.js';
9
+ import { type DeviceOp, type DeviceRegistry } from './registry.js';
10
+ import type { RosterState } from './roster.js';
8
11
  export declare function mutexFor(handle: GroupHandle): Mutex;
12
+ /** Events a GroupHandle emits. Advisory notifications derived from the folded ledger; never
13
+ * a protocol input. Delivered via `fire` (a throwing listener never breaks a fold). */
14
+ export type GroupHandleEvents = {
15
+ deviceRevoked: Array<{
16
+ device: string;
17
+ controller: string;
18
+ }>;
19
+ controllerBeaconChanged: {
20
+ controller: string;
21
+ logLength: number;
22
+ headDigest: string;
23
+ };
24
+ };
25
+ /** The full emitter for a handle — module-internal, for deriveGroup to share it onward. */
26
+ export declare function emitterOf(group: GroupHandle): EventEmitter<GroupHandleEvents>;
9
27
  /** Thrown by GroupHandle.processMessage when the commit policy rejects an incoming
10
28
  * commit. The handle is left at its pre-commit epoch. */
11
29
  export declare class CommitRejectedError extends Error {
@@ -42,6 +60,8 @@ export type GroupHandleParams = {
42
60
  resolveLedgerEntries?: (ids: Array<string>) => Promise<Array<string>>;
43
61
  /** Surface an accepted commit's notarized non-`kumiai.role` entries to the consumer. */
44
62
  onLedgerEntries?: (entries: Array<VerifiedLedgerEntry>) => void;
63
+ /** Shared event emitter; a derived handle inherits its parent's so subscriptions persist. */
64
+ events?: EventEmitter<GroupHandleEvents>;
45
65
  };
46
66
  /** Mutable wrapper around MLS group state + Enkaku credential. */
47
67
  export declare class GroupHandle {
@@ -73,6 +93,35 @@ export declare class GroupHandle {
73
93
  get ledgerTokens(): Array<string>;
74
94
  /** The control roster folded from the anchor and every applied ledger entry. */
75
95
  get roster(): RosterState;
96
+ /** The device registry folded from the anchor and every applied ledger entry. */
97
+ get registry(): DeviceRegistry;
98
+ /**
99
+ * The device deny set the auth service consumes: the DIDs revoked in the CURRENTLY folded
100
+ * registry (pre-commit). Matched, never enumerated by consumers. A revoke takes deny-effect from
101
+ * the next epoch, so a commit never denies the leaves it is itself validating.
102
+ */
103
+ currentDenySet(): ReadonlySet<string>;
104
+ /** Listen-only view of this group's events. Consumers subscribe; they cannot emit. */
105
+ get events(): EventsSource<GroupHandleEvents>;
106
+ /**
107
+ * The device bindings currently at `status: 'revoked'` — an enumerable notification/tracking
108
+ * surface for consumers deciding where else to revoke. Distinct from currentDenySet(), the
109
+ * opaque matched-never-enumerated validation deny set; this is never a gating input.
110
+ */
111
+ revokedDevices(): ReadonlyArray<{
112
+ device: string;
113
+ controller: string;
114
+ label?: string;
115
+ }>;
116
+ /**
117
+ * @internal Fire notification events for the device entries just enacted in one operation.
118
+ * Called from the commit path, from bootstrapLedger, and from the local write APIs — NEVER from
119
+ * the constructor or a fresh-join applyLedgerEntries, so a joiner is not replayed the whole
120
+ * history as live events (it reads revokedDevices()/beaconOf for current state instead). Uses
121
+ * `fire`: a throwing listener is swallowed and cannot break the fold. Reads controllerOf on the
122
+ * POST-fold registry.
123
+ */
124
+ emitControlEvents(enacted: ReadonlyArray<VerifiedLedgerEntry>): void;
76
125
  /**
77
126
  * Verify signed ledger tokens, append the valid ones in the order given, and
78
127
  * refold the roster. Tokens that fail verification or whose groupID mismatches are
@@ -86,7 +135,7 @@ export declare class GroupHandle {
86
135
  * it (MLS applies each once, restoreGroup replays a token list once, processWelcome
87
136
  * folds an invite once). Serialized on the handle's mutex.
88
137
  */
89
- applyLedgerEntries(tokens: Array<string>): Promise<void>;
138
+ applyLedgerEntries(tokens: Array<string>): Promise<Array<VerifiedLedgerEntry>>;
90
139
  /**
91
140
  * Whether the ledger this handle holds is the whole ledger its GroupContext
92
141
  * attests to: the head folded from the ids it holds, in order, against the
@@ -223,6 +272,12 @@ export declare class GroupHandle {
223
272
  payload: Uint8Array;
224
273
  senderDID?: string;
225
274
  }>;
275
+ /**
276
+ * The device-proof binding at the leaf naming `did`: its bound controller (if any), the embedded
277
+ * controller-log prefix (if bound), and the leaf signature key. Reads the CURRENT ratchet tree —
278
+ * the pre-commit tree in the acceptance pipeline. Undefined when no leaf names the DID.
279
+ */
280
+ bindingOfDID(did: string): LeafBinding | undefined;
226
281
  /**
227
282
  * Read what a Commit says about itself against this handle, WITHOUT advancing state.
228
283
  *
@@ -281,6 +336,10 @@ export declare function buildCommitPolicyContext(handle: GroupHandle, args: {
281
336
  baseRoster: RosterState;
282
337
  candidateRoster: RosterState;
283
338
  entryIDs: Array<string>;
339
+ enactedDeviceEntries: Array<{
340
+ subject: string;
341
+ op: DeviceOp;
342
+ }>;
284
343
  externalCommitDID?: string;
285
344
  }): CommitPolicyContext;
286
345
  /** Build the handle a commit hands back: the post-commit state, everything else inherited. */