@kumiai/mls 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +21 -9
  2. package/lib/anchor.d.ts +87 -0
  3. package/lib/anchor.js +124 -0
  4. package/lib/credential.d.ts +3 -12
  5. package/lib/credential.js +0 -13
  6. package/lib/envelope-fold.d.ts +35 -0
  7. package/lib/envelope-fold.js +86 -0
  8. package/lib/envelope.d.ts +53 -0
  9. package/lib/envelope.js +87 -0
  10. package/lib/fold.d.ts +68 -0
  11. package/lib/fold.js +53 -0
  12. package/lib/group-commit.d.ts +100 -0
  13. package/lib/group-commit.js +252 -0
  14. package/lib/group-context.d.ts +11 -0
  15. package/lib/group-context.js +33 -0
  16. package/lib/group-create.d.ts +19 -0
  17. package/lib/group-create.js +85 -0
  18. package/lib/group-credential.d.ts +6 -0
  19. package/lib/group-credential.js +39 -0
  20. package/lib/group-handle.d.ts +177 -0
  21. package/lib/group-handle.js +613 -0
  22. package/lib/group-info.d.ts +57 -0
  23. package/lib/group-info.js +85 -0
  24. package/lib/group-membership.d.ts +25 -0
  25. package/lib/group-membership.js +36 -0
  26. package/lib/group-welcome.d.ts +67 -0
  27. package/lib/group-welcome.js +178 -0
  28. package/lib/group.d.ts +7 -233
  29. package/lib/group.js +7 -653
  30. package/lib/head.d.ts +79 -0
  31. package/lib/head.js +150 -0
  32. package/lib/index.d.ts +11 -3
  33. package/lib/index.js +11 -3
  34. package/lib/ledger.d.ts +49 -0
  35. package/lib/ledger.js +67 -0
  36. package/lib/mutex.d.ts +14 -0
  37. package/lib/mutex.js +20 -0
  38. package/lib/policy.d.ts +71 -0
  39. package/lib/policy.js +191 -0
  40. package/lib/recovery.d.ts +227 -0
  41. package/lib/recovery.js +456 -0
  42. package/lib/roster.d.ts +45 -0
  43. package/lib/roster.js +72 -0
  44. package/lib/types.d.ts +31 -11
  45. package/package.json +2 -3
  46. package/lib/capability.d.ts +0 -47
  47. package/lib/capability.js +0 -79
package/lib/fold.js ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Replay the ledger into a single reducer's projection.
3
+ *
4
+ * Signatures are verified at ingest, not here — this fold evaluates AUTHORITY:
5
+ * whether each issuer was allowed to make its claim given the state accumulated
6
+ * from strictly-earlier entries. Evaluating against state-so-far (never the
7
+ * final state) is what makes rotation sound: a key authorized when it made a
8
+ * claim can be revoked later without retroactively invalidating that claim.
9
+ *
10
+ * Folds `entries` in exactly the order given — it imposes no order of its own.
11
+ * The caller supplies the total order (kumiai derives it from the authenticated
12
+ * epoch chain), so ordering lives with the caller, not the fold. Full replay
13
+ * only: it takes the whole entry set and folds it. There is no incremental
14
+ * apply, per-type watermark, or dependency entry point by design — a reducer
15
+ * whose authority reads another entry type cannot be driven safely by a
16
+ * per-type incremental applier, so the only fold entry point replays everything.
17
+ *
18
+ * The fold itself does not filter by `groupID`: the caller passes only entries
19
+ * for the group being folded, so a `groupID` mismatch is dropped by the caller
20
+ * before the fold, or by a reducer's own `type` / `verifyAuthority` check. No
21
+ * group logic lives here.
22
+ *
23
+ * Pure — no clock, no randomness, no I/O — and the input array is never mutated
24
+ * (nothing here writes to it, and there is no copy-to-sort). A claim of an
25
+ * unrelated type or one whose authority fails is dropped (never thrown) so a
26
+ * single bad entry can never abort the projection. Drops are silent unless an
27
+ * `onDrop` observer is supplied — the fold runs on every authority check, where
28
+ * authority-failed drops are expected, so the caller decides whether to surface
29
+ * them rather than the fold emitting to the console.
30
+ */ export function foldLedger(entries, anchor, reducer, onDrop) {
31
+ let state = reducer.seed(anchor);
32
+ for (const { verified, entryID } of entries){
33
+ const { entry } = verified;
34
+ if (entry.type !== reducer.type) {
35
+ onDrop?.({
36
+ entryID,
37
+ type: entry.type,
38
+ reason: `unrelated type '${entry.type}' for reducer '${reducer.type}'`
39
+ });
40
+ continue;
41
+ }
42
+ if (!reducer.verifyAuthority(verified, state)) {
43
+ onDrop?.({
44
+ entryID,
45
+ type: entry.type,
46
+ reason: `issuer '${verified.issuer}' not authorized`
47
+ });
48
+ continue;
49
+ }
50
+ state = reducer.apply(verified, state);
51
+ }
52
+ return state;
53
+ }
@@ -0,0 +1,100 @@
1
+ import { type SigningIdentity } from '@kokuin/token';
2
+ import { createCommit, type DefaultProposal, type KeyPackage } from 'ts-mls';
3
+ import { type GroupHandle } from './group-handle.js';
4
+ import { type GroupPermission } from './roster.js';
5
+ import type { Invite } from './types.js';
6
+ export type CreateInviteParams = {
7
+ group: GroupHandle;
8
+ identity: SigningIdentity;
9
+ recipientDID: string;
10
+ permission: GroupPermission;
11
+ };
12
+ export type CreateInviteResult = {
13
+ invite: Invite;
14
+ };
15
+ /**
16
+ * Create an invite for a new member. Does NOT add them — call commitInvite with
17
+ * their key package for that.
18
+ *
19
+ * Only an admin may invite: a role entry from a non-admin issuer is dropped by every
20
+ * receiver's fold, so refusing here turns a silent downstream rejection into a local
21
+ * error.
22
+ */
23
+ export declare function createInvite(params: CreateInviteParams): Promise<CreateInviteResult>;
24
+ /**
25
+ * The one place a commit carrying control-ledger entries is built: `commitInvite`,
26
+ * `removeMember`, and `commitLedgerEntries` all route through it, so envelope and
27
+ * head never drift apart.
28
+ *
29
+ * `enacted` is exactly what this commit enacts, and only the caller can decide it:
30
+ * entries are enacted by *position*, so one whose content the log already carries is
31
+ * a legitimate re-enactment (e.g. a demotion back to a previously-held role) and must
32
+ * not be filtered by content.
33
+ *
34
+ * The envelope names only what this commit enacts, never the whole history: replaying
35
+ * history would re-judge every past entry against the present roster, and a grant by
36
+ * a since-demoted admin would read as a non-admin's — freezing every group that ever
37
+ * rotated admins.
38
+ *
39
+ * When `enacted` is non-empty the commit also carries a group-context-extensions
40
+ * proposal advancing the head by exactly those ids, in envelope order. An empty list
41
+ * moves no head and carries no envelope.
42
+ */
43
+ export declare function commitWithEntries(group: GroupHandle, extraProposals: Array<DefaultProposal>, enacted: Array<string>, ratchetTreeExtension?: boolean): Promise<Awaited<ReturnType<typeof createCommit>>>;
44
+ export type CommitLedgerEntriesResult = {
45
+ /** Framed MLSMessage bytes. Broadcast to existing members via the DS. */
46
+ commitMessage: Uint8Array;
47
+ newGroup: GroupHandle;
48
+ /** Post-commit epoch the group is now at (== newGroup.epoch). */
49
+ epoch: bigint;
50
+ };
51
+ /**
52
+ * The admin write path for the control ledger: a commit carrying no membership
53
+ * proposal, only the entries it enacts and the head move covering them. An entry that
54
+ * never rides a commit is invisible to the head, and a joiner recomputing the head
55
+ * would read the history as doctored.
56
+ *
57
+ * Enacts exactly `tokens` at the end of the log — including one whose content the log
58
+ * already carries (how an admin is demoted back to a previously-held role). Rejects an
59
+ * empty `tokens` list.
60
+ *
61
+ * Reads `group` and returns a NEW derived handle (`newGroup`); it never advances
62
+ * `group`. The caller MUST adopt `newGroup` — never reuse `group` — before the next
63
+ * commit: two commits from the same source handle both frame at its epoch and diverge.
64
+ * The mutex only serializes concurrent calls against one handle; it does not make a
65
+ * second commit from a superseded handle safe.
66
+ */
67
+ export declare function commitLedgerEntries(group: GroupHandle, tokens: Array<string>): Promise<CommitLedgerEntriesResult>;
68
+ export type CommitInviteResult = {
69
+ /** Framed MLSMessage bytes. Broadcast to existing members via the DS. */
70
+ commitMessage: Uint8Array;
71
+ /** Framed MLSMessage(Welcome) bytes. Delivered to the new member. */
72
+ welcomeMessage: Uint8Array;
73
+ newGroup: GroupHandle;
74
+ /** Post-commit epoch (== newGroup.epoch). NOT the commit's wire-header epoch: a
75
+ * commit is framed at the sender's pre-commit epoch (== epoch - 1n), which is what
76
+ * receivers compare against their own handle.epoch for ordering (see
77
+ * readMessageEpoch). */
78
+ epoch: bigint;
79
+ };
80
+ /**
81
+ * Commit an invite by adding the invitee's key package. Produces an MLS Commit +
82
+ * Welcome.
83
+ *
84
+ * The invite's ledger entries are enacted here: their content ids ride the commit's
85
+ * control envelope and advance the head by exactly those ids, so every receiver folds
86
+ * the invitee's role entry as it applies the Add. The envelope carries ids, not
87
+ * bodies — a receiver holding neither the entry nor a `resolveLedgerEntries` resolver
88
+ * throws MissingLedgerEntriesError.
89
+ *
90
+ * The invite carries the group's whole history (a joiner has nothing to fold it onto),
91
+ * but only the entries beyond that history ride the commit — see
92
+ * {@link entriesAddedByInvite} and {@link commitWithEntries}.
93
+ *
94
+ * Reads `group` and returns a NEW derived handle (`newGroup`); it never advances
95
+ * `group`. The caller MUST adopt `newGroup` — never reuse `group` — before the next
96
+ * commit: two commits from the same source handle both frame at its epoch and diverge.
97
+ * The mutex only serializes concurrent calls against one handle; it does not make a
98
+ * second commit from a superseded handle safe.
99
+ */
100
+ export declare function commitInvite(group: GroupHandle, keyPackage: KeyPackage, invite: Invite): Promise<CommitInviteResult>;
@@ -0,0 +1,252 @@
1
+ import { normalizeDID } from '@kokuin/token';
2
+ import { createCommit, defaultProposalTypes, encode, mlsMessageEncoder } from 'ts-mls';
3
+ import { LEDGER_HEAD_EXTENSION_TYPE } from './anchor.js';
4
+ import { encodeControlEnvelope } from './envelope.js';
5
+ import { foldEnvelope } from './envelope-fold.js';
6
+ import { buildCommitPolicyContext, deriveGroup, mutexFor } from './group-handle.js';
7
+ import { buildLedgerHeadExtension, extendHead, readLedgerHead } from './head.js';
8
+ import { ledgerEntryDigest, signLedgerEntry, verifyLedgerEntry } from './ledger.js';
9
+ import { defaultCommitPolicy } from './policy.js';
10
+ import { ROLE_ENTRY_TYPE } from './roster.js';
11
+ /**
12
+ * Create an invite for a new member. Does NOT add them — call commitInvite with
13
+ * their key package for that.
14
+ *
15
+ * Only an admin may invite: a role entry from a non-admin issuer is dropped by every
16
+ * receiver's fold, so refusing here turns a silent downstream rejection into a local
17
+ * error.
18
+ */ export async function createInvite(params) {
19
+ const { group, identity, recipientDID, permission } = params;
20
+ if (group.roster.roles.get(normalizeDID(identity.id)) !== 'admin') {
21
+ throw new Error('createInvite: the inviter must be an admin in the group roster');
22
+ }
23
+ // The role entry naming the invitee. Its issuer is the inviter (authenticated by
24
+ // the token signature) and its value is the permission granted.
25
+ const roleToken = await signLedgerEntry(identity, {
26
+ type: ROLE_ENTRY_TYPE,
27
+ groupID: group.groupID,
28
+ subject: recipientDID,
29
+ value: permission
30
+ });
31
+ const invite = {
32
+ groupID: group.groupID,
33
+ inviterID: identity.id,
34
+ // The whole log, new role entry last: a joiner handed only its own entry would
35
+ // never learn of earlier role changes and would reject every commit by an admin
36
+ // promoted since — a permanent fork nothing re-sends. The new entry must fold
37
+ // after the history it depends on, hence last. Re-granting a role the log already
38
+ // carries appends it again (a legal re-enactment). The joiner still folds from the
39
+ // anchor, so padding this list cannot promote anyone.
40
+ ledgerEntries: [
41
+ ...group.ledgerTokens,
42
+ roleToken
43
+ ]
44
+ };
45
+ return {
46
+ invite
47
+ };
48
+ }
49
+ /**
50
+ * The GroupContext extension list a commit installs when it enacts `entryIDs`: the
51
+ * current list with only the ledger-head extension replaced by the head extended by
52
+ * those ids, in envelope order. Every other extension — the anchor above all — is the
53
+ * verbatim object from the current GroupContext, never a re-encode: the receiving
54
+ * policy byte-compares the anchor.
55
+ */ function extensionsWithHead(group, entryIDs) {
56
+ const current = readLedgerHead(group);
57
+ if (current == null) {
58
+ throw new Error('group has no ledger head extension; it cannot enact ledger entries');
59
+ }
60
+ const next = buildLedgerHeadExtension(extendHead(current.head, entryIDs));
61
+ return group.state.groupContext.extensions.map((ext)=>ext.extensionType === LEDGER_HEAD_EXTENSION_TYPE ? next : ext);
62
+ }
63
+ /**
64
+ * The one place a commit carrying control-ledger entries is built: `commitInvite`,
65
+ * `removeMember`, and `commitLedgerEntries` all route through it, so envelope and
66
+ * head never drift apart.
67
+ *
68
+ * `enacted` is exactly what this commit enacts, and only the caller can decide it:
69
+ * entries are enacted by *position*, so one whose content the log already carries is
70
+ * a legitimate re-enactment (e.g. a demotion back to a previously-held role) and must
71
+ * not be filtered by content.
72
+ *
73
+ * The envelope names only what this commit enacts, never the whole history: replaying
74
+ * history would re-judge every past entry against the present roster, and a grant by
75
+ * a since-demoted admin would read as a non-admin's — freezing every group that ever
76
+ * rotated admins.
77
+ *
78
+ * When `enacted` is non-empty the commit also carries a group-context-extensions
79
+ * proposal advancing the head by exactly those ids, in envelope order. An empty list
80
+ * moves no head and carries no envelope.
81
+ */ export async function commitWithEntries(group, extraProposals, enacted, ratchetTreeExtension = false) {
82
+ // Same reason createInvite guards the inviter: a non-admin's commit is rejected by
83
+ // every receiver, so fail here rather than emitting a commit nobody will apply.
84
+ if (group.roster.roles.get(normalizeDID(group.credential.id)) !== 'admin') {
85
+ throw new Error('the committer must be an admin in the group roster');
86
+ }
87
+ // Fold the entries exactly as every receiver will; refuse to author a commit the
88
+ // group would reject. Without this the write path fails *open*: the committer
89
+ // advances its own log and head while every receiver rejects the commit, forking
90
+ // itself off. Being an admin is not enough — an entry's own issuer must hold
91
+ // authority at the position it lands, so a token signed by a since-demoted admin is
92
+ // dead paper no matter who commits it.
93
+ const inputs = [];
94
+ for (const token of enacted){
95
+ const verified = await verifyLedgerEntry(token);
96
+ if (verified == null) {
97
+ throw new Error('cannot enact a ledger entry whose signature does not verify');
98
+ }
99
+ inputs.push({
100
+ verified,
101
+ entryID: ledgerEntryDigest(token)
102
+ });
103
+ }
104
+ const fold = foldEnvelope(group.roster, inputs, group.groupID);
105
+ if (!fold.ok) {
106
+ throw new Error(`cannot enact ledger entry ${fold.entryID}: ${fold.reason}`);
107
+ }
108
+ const entryIDs = enacted.map(ledgerEntryDigest);
109
+ // Filter the pending-proposal set the committer would otherwise absorb: ts-mls folds
110
+ // every unappliedProposal into the commit, so a non-admin's pending proposal would
111
+ // ride it and every peer would reject the whole thing — one member could stall the
112
+ // group. Judge each against the same defaultCommitPolicy and context receivers build,
113
+ // dropping any the group would reject.
114
+ const filterContext = buildCommitPolicyContext(group, {
115
+ baseRoster: group.roster,
116
+ candidateRoster: fold.roster,
117
+ entryIDs
118
+ });
119
+ const keptPending = {};
120
+ for (const [ref, pws] of Object.entries(group.state.unappliedProposals)){
121
+ if (defaultCommitPolicy({
122
+ kind: 'proposal',
123
+ proposal: pws
124
+ }, filterContext) !== 'reject') {
125
+ keptPending[ref] = pws;
126
+ }
127
+ }
128
+ const commitState = {
129
+ ...group.state,
130
+ unappliedProposals: keptPending
131
+ };
132
+ const proposals = [
133
+ ...extraProposals
134
+ ];
135
+ if (entryIDs.length > 0) {
136
+ proposals.push({
137
+ proposalType: defaultProposalTypes.group_context_extensions,
138
+ groupContextExtensions: {
139
+ extensions: extensionsWithHead(group, entryIDs)
140
+ }
141
+ });
142
+ }
143
+ return await createCommit({
144
+ context: group.context,
145
+ state: commitState,
146
+ extraProposals: proposals,
147
+ ...ratchetTreeExtension && {
148
+ ratchetTreeExtension: true
149
+ },
150
+ ...entryIDs.length > 0 && {
151
+ authenticatedData: encodeControlEnvelope({
152
+ v: 1,
153
+ entries: entryIDs
154
+ })
155
+ }
156
+ });
157
+ }
158
+ /**
159
+ * The entries an invite adds beyond the committer's own log: everything past the
160
+ * log's length. Positional, never by content — a re-granted role is a token the log
161
+ * already carries earlier, and content-narrowing would drop the very entry the invite
162
+ * exists to enact.
163
+ *
164
+ * Positional narrowing is sound only when the invite's list *begins with* the
165
+ * committer's log, so that is asserted, not assumed: an invite against a different
166
+ * history would mis-slice and move the head by ids that do not follow the group's own,
167
+ * corrupting the chain for every receiver.
168
+ */ function entriesAddedByInvite(group, invite) {
169
+ const held = group.ledgerTokens;
170
+ if (invite.ledgerEntries.length < held.length || held.some((token, index)=>invite.ledgerEntries[index] !== token)) {
171
+ throw new Error("commitInvite: the invite's ledger does not extend this group's own");
172
+ }
173
+ return invite.ledgerEntries.slice(held.length);
174
+ }
175
+ /**
176
+ * The admin write path for the control ledger: a commit carrying no membership
177
+ * proposal, only the entries it enacts and the head move covering them. An entry that
178
+ * never rides a commit is invisible to the head, and a joiner recomputing the head
179
+ * would read the history as doctored.
180
+ *
181
+ * Enacts exactly `tokens` at the end of the log — including one whose content the log
182
+ * already carries (how an admin is demoted back to a previously-held role). Rejects an
183
+ * empty `tokens` list.
184
+ *
185
+ * Reads `group` and returns a NEW derived handle (`newGroup`); it never advances
186
+ * `group`. The caller MUST adopt `newGroup` — never reuse `group` — before the next
187
+ * commit: two commits from the same source handle both frame at its epoch and diverge.
188
+ * The mutex only serializes concurrent calls against one handle; it does not make a
189
+ * second commit from a superseded handle safe.
190
+ */ export async function commitLedgerEntries(group, tokens) {
191
+ return mutexFor(group).run(async ()=>{
192
+ if (tokens.length === 0) {
193
+ throw new Error('commitLedgerEntries: no ledger entries to commit');
194
+ }
195
+ const result = await commitWithEntries(group, [], tokens);
196
+ const newGroup = deriveGroup(group, result.newState);
197
+ await newGroup.applyLedgerEntries(tokens);
198
+ return {
199
+ commitMessage: encode(mlsMessageEncoder, result.commit),
200
+ newGroup,
201
+ epoch: newGroup.epoch
202
+ };
203
+ });
204
+ }
205
+ /**
206
+ * Commit an invite by adding the invitee's key package. Produces an MLS Commit +
207
+ * Welcome.
208
+ *
209
+ * The invite's ledger entries are enacted here: their content ids ride the commit's
210
+ * control envelope and advance the head by exactly those ids, so every receiver folds
211
+ * the invitee's role entry as it applies the Add. The envelope carries ids, not
212
+ * bodies — a receiver holding neither the entry nor a `resolveLedgerEntries` resolver
213
+ * throws MissingLedgerEntriesError.
214
+ *
215
+ * The invite carries the group's whole history (a joiner has nothing to fold it onto),
216
+ * but only the entries beyond that history ride the commit — see
217
+ * {@link entriesAddedByInvite} and {@link commitWithEntries}.
218
+ *
219
+ * Reads `group` and returns a NEW derived handle (`newGroup`); it never advances
220
+ * `group`. The caller MUST adopt `newGroup` — never reuse `group` — before the next
221
+ * commit: two commits from the same source handle both frame at its epoch and diverge.
222
+ * The mutex only serializes concurrent calls against one handle; it does not make a
223
+ * second commit from a superseded handle safe.
224
+ */ export async function commitInvite(group, keyPackage, invite) {
225
+ return mutexFor(group).run(async ()=>{
226
+ if (invite.groupID !== group.groupID) {
227
+ throw new Error(`commitInvite: invite is for group ${invite.groupID}, not ${group.groupID}`);
228
+ }
229
+ const enacted = entriesAddedByInvite(group, invite);
230
+ const addProposal = {
231
+ proposalType: defaultProposalTypes.add,
232
+ add: {
233
+ keyPackage
234
+ }
235
+ };
236
+ const result = await commitWithEntries(group, [
237
+ addProposal
238
+ ], enacted, true);
239
+ const newGroup = deriveGroup(group, result.newState);
240
+ if (result.welcome == null) {
241
+ throw new Error('commitInvite: expected a Welcome message for the add proposal');
242
+ }
243
+ // The entries this commit enacts are now part of the group's ledger.
244
+ await newGroup.applyLedgerEntries(enacted);
245
+ return {
246
+ commitMessage: encode(mlsMessageEncoder, result.commit),
247
+ welcomeMessage: encode(mlsMessageEncoder, result.welcome),
248
+ newGroup,
249
+ epoch: newGroup.epoch
250
+ };
251
+ });
252
+ }
@@ -0,0 +1,11 @@
1
+ import { type Capabilities, type GroupContextExtension, type MlsContext } from 'ts-mls';
2
+ import type { GroupOptions } from './types.js';
3
+ export declare function resolveMlsContext(options?: GroupOptions): Promise<MlsContext>;
4
+ /**
5
+ * Build the leaf-node capabilities for a member joining or creating a group. RFC
6
+ * 9420 requires a leaf to advertise every non-default GroupContext extension type
7
+ * the group uses; derive that set from the group's extensions so it cannot desync.
8
+ * A leaf advertising only defaults is rejected by ts-mls ("client does not support
9
+ * every extension in the GroupContext"). An explicit `override` wins verbatim.
10
+ */
11
+ export declare function buildLeafCapabilities(extensions: ReadonlyArray<GroupContextExtension>, override?: Capabilities): Capabilities;
@@ -0,0 +1,33 @@
1
+ import { defaultCapabilities, getCiphersuiteImpl } from 'ts-mls';
2
+ import { createDIDAuthenticationService } from './authentication.js';
3
+ import { nobleCryptoProvider } from './crypto.js';
4
+ const DEFAULT_CIPHERSUITE = 'MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519';
5
+ export async function resolveMlsContext(options) {
6
+ const name = options?.ciphersuiteName ?? DEFAULT_CIPHERSUITE;
7
+ const cipherSuite = await getCiphersuiteImpl(name, options?.cryptoProvider ?? nobleCryptoProvider);
8
+ const authService = createDIDAuthenticationService();
9
+ return {
10
+ cipherSuite,
11
+ authService
12
+ };
13
+ }
14
+ /**
15
+ * Build the leaf-node capabilities for a member joining or creating a group. RFC
16
+ * 9420 requires a leaf to advertise every non-default GroupContext extension type
17
+ * the group uses; derive that set from the group's extensions so it cannot desync.
18
+ * A leaf advertising only defaults is rejected by ts-mls ("client does not support
19
+ * every extension in the GroupContext"). An explicit `override` wins verbatim.
20
+ */ export function buildLeafCapabilities(extensions, override) {
21
+ if (override != null) return override;
22
+ const base = defaultCapabilities();
23
+ const types = new Set([
24
+ ...base.extensions,
25
+ ...extensions.map((e)=>e.extensionType)
26
+ ]);
27
+ return {
28
+ ...base,
29
+ extensions: [
30
+ ...types
31
+ ]
32
+ };
33
+ }
@@ -0,0 +1,19 @@
1
+ import { type OwnIdentity } from '@kokuin/token';
2
+ import { type ClientState } from 'ts-mls';
3
+ import type { MemberCredential } from './credential.js';
4
+ import { GroupHandle } from './group-handle.js';
5
+ import type { GroupOptions } from './types.js';
6
+ export type CreateGroupResult = {
7
+ group: GroupHandle;
8
+ credential: MemberCredential;
9
+ };
10
+ /** Create a new MLS group. The identity becomes the sole member and admin. */
11
+ export declare function createGroup(identity: OwnIdentity, groupID: string, options?: GroupOptions): Promise<CreateGroupResult>;
12
+ export type RestoreGroupParams = {
13
+ state: ClientState;
14
+ credential: MemberCredential;
15
+ /** Signed ledger tokens the host persisted, replayed to rebuild the roster. */
16
+ ledgerEntries?: Array<string>;
17
+ options?: GroupOptions;
18
+ };
19
+ export declare function restoreGroup(params: RestoreGroupParams): Promise<GroupHandle>;
@@ -0,0 +1,85 @@
1
+ import { createInMemoryDIDCache, normalizeDID } from '@kokuin/token';
2
+ import { generateKeyPackageWithKey, createGroup as mlsCreateGroup } from 'ts-mls';
3
+ import { buildCurrentGroupAnchorExtension, decodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, LEDGER_HEAD_EXTENSION_TYPE } from './anchor.js';
4
+ import { buildLeafCapabilities, resolveMlsContext } from './group-context.js';
5
+ import { makeMLSCredential } from './group-credential.js';
6
+ import { GroupHandle } from './group-handle.js';
7
+ import { buildLedgerHeadExtension, genesisHead } from './head.js';
8
+ /** Create a new MLS group. The identity becomes the sole member and admin. */ export async function createGroup(identity, groupID, options) {
9
+ const cache = options?.cache ?? createInMemoryDIDCache();
10
+ const context = await resolveMlsContext(options);
11
+ // Every group is anchored at creation: creator is the epoch-0 admin, ledger head
12
+ // starts at genesis. A caller-supplied anchor is left untouched (the caller owns
13
+ // its contents); its `creatorDID` coupling to the creating identity is validated
14
+ // below. A decode failure here is left to the fail-closed decode in the constructor.
15
+ const extensions = [
16
+ ...options?.extensions ?? []
17
+ ];
18
+ const suppliedAnchorExtension = extensions.find((ext)=>ext.extensionType === GROUP_ANCHOR_EXTENSION_TYPE);
19
+ if (suppliedAnchorExtension != null) {
20
+ const suppliedAnchorData = suppliedAnchorExtension.extensionData;
21
+ const suppliedAnchor = suppliedAnchorData instanceof Uint8Array ? decodeGroupAnchor(suppliedAnchorData) : null;
22
+ if (suppliedAnchor != null && normalizeDID(suppliedAnchor.creatorDID) !== normalizeDID(identity.id)) {
23
+ throw new Error(`createGroup: the anchor's creatorDID (${suppliedAnchor.creatorDID}) must be the creating identity (${identity.id})`);
24
+ }
25
+ }
26
+ if (!extensions.some((ext)=>ext.extensionType === GROUP_ANCHOR_EXTENSION_TYPE)) {
27
+ extensions.push(buildCurrentGroupAnchorExtension(identity.id));
28
+ }
29
+ if (!extensions.some((ext)=>ext.extensionType === LEDGER_HEAD_EXTENSION_TYPE)) {
30
+ extensions.push(buildLedgerHeadExtension(genesisHead(groupID)));
31
+ }
32
+ const statePromise = generateKeyPackageWithKey({
33
+ credential: makeMLSCredential(identity),
34
+ signatureKeyPair: {
35
+ signKey: identity.privateKey,
36
+ publicKey: identity.publicKey
37
+ },
38
+ cipherSuite: context.cipherSuite,
39
+ capabilities: buildLeafCapabilities(extensions, options?.capabilities)
40
+ }).then((keyPackage)=>{
41
+ return mlsCreateGroup({
42
+ context,
43
+ groupId: new TextEncoder().encode(groupID),
44
+ keyPackage: keyPackage.publicPackage,
45
+ privateKeyPackage: keyPackage.privatePackage,
46
+ extensions
47
+ });
48
+ });
49
+ const state = await statePromise;
50
+ const credential = {
51
+ id: identity.id,
52
+ groupID
53
+ };
54
+ const group = new GroupHandle({
55
+ state,
56
+ credential,
57
+ context,
58
+ cache,
59
+ resolver: options?.resolver,
60
+ commitPolicy: options?.commitPolicy,
61
+ resolveLedgerEntries: options?.resolveLedgerEntries,
62
+ onLedgerEntries: options?.onLedgerEntries
63
+ });
64
+ return {
65
+ group,
66
+ credential
67
+ };
68
+ }
69
+ export async function restoreGroup(params) {
70
+ const cache = params.options?.cache ?? createInMemoryDIDCache();
71
+ // Construction reseeds `{creator: 'admin'}` from the anchor in the restored state;
72
+ // an anchorless state throws (the same fail-closed guard).
73
+ const group = new GroupHandle({
74
+ state: params.state,
75
+ credential: params.credential,
76
+ context: await resolveMlsContext(params.options),
77
+ cache,
78
+ resolver: params.options?.resolver,
79
+ commitPolicy: params.options?.commitPolicy,
80
+ resolveLedgerEntries: params.options?.resolveLedgerEntries,
81
+ onLedgerEntries: params.options?.onLedgerEntries
82
+ });
83
+ await group.applyLedgerEntries(params.ledgerEntries ?? []);
84
+ return group;
85
+ }
@@ -0,0 +1,6 @@
1
+ import { type OwnIdentity } from '@kokuin/token';
2
+ import { type Credential } from 'ts-mls';
3
+ import type { GroupOptions, KeyPackageBundle } from './types.js';
4
+ export declare function makeMLSCredential(identity: OwnIdentity): Credential;
5
+ /** Generate a key package for joining groups. */
6
+ export declare function createKeyPackageBundle(identity: OwnIdentity, options?: GroupOptions): Promise<KeyPackageBundle>;
@@ -0,0 +1,39 @@
1
+ import { isPeer4 } from '@kokuin/token';
2
+ import { defaultCredentialTypes, generateKeyPackageWithKey } from 'ts-mls';
3
+ import { controlCapabilities } from './anchor.js';
4
+ import { resolveMlsContext } from './group-context.js';
5
+ export function makeMLSCredential(identity) {
6
+ const id = identity.id;
7
+ const isPeer = isPeer4(id);
8
+ if (isPeer && !('longForm' in identity && typeof identity.longForm === 'string')) {
9
+ throw new Error('peer:4 identity is missing longForm; only identities from createIdentity can be used as MLS members');
10
+ }
11
+ const payload = {
12
+ id
13
+ };
14
+ if (isPeer) {
15
+ payload.longForm = identity.longForm;
16
+ }
17
+ return {
18
+ credentialType: defaultCredentialTypes.basic,
19
+ identity: new TextEncoder().encode(JSON.stringify(payload))
20
+ };
21
+ }
22
+ /** Generate a key package for joining groups. */ export async function createKeyPackageBundle(identity, options) {
23
+ const { cipherSuite } = await resolveMlsContext(options);
24
+ const result = await generateKeyPackageWithKey({
25
+ credential: makeMLSCredential(identity),
26
+ signatureKeyPair: {
27
+ signKey: identity.privateKey,
28
+ publicKey: identity.publicKey
29
+ },
30
+ cipherSuite,
31
+ // An invitee leaf must advertise the control extension types or ts-mls
32
+ // refuses to add it to an anchored group. An explicit override still wins.
33
+ capabilities: options?.capabilities ?? controlCapabilities()
34
+ });
35
+ return {
36
+ ...result,
37
+ ownerDID: identity.id
38
+ };
39
+ }