@kumiai/mls 0.1.0 → 0.2.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.
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
+ }
package/lib/group.d.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  import { type DIDCache, type DIDResolver, type OwnIdentity, type SigningIdentity } from '@kokuin/token';
2
2
  import { type ClientState, type Credential, type IncomingMessageCallback, type KeyPackage, type MlsContext, type ProposalWithSender } from 'ts-mls';
3
- import { type GroupPermission } from './capability.js';
3
+ import { type GroupAnchor } from './anchor.js';
4
4
  import { type GroupMember, type MemberCredential } from './credential.js';
5
+ import { type VerifiedLedgerEntry } from './ledger.js';
6
+ import { type GroupPermission, type RosterState } from './roster.js';
5
7
  import type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
6
8
  export declare function makeMLSCredential(identity: OwnIdentity): Credential;
7
9
  /**
8
- * Thrown by GroupHandle.processMessage/decrypt when the active commit policy
9
- * rejects an incoming commit. The handle is left at its pre-commit epoch.
10
+ * Thrown by GroupHandle.processMessage when the active commit policy rejects
11
+ * an incoming commit. The handle is left at its pre-commit epoch.
10
12
  */
11
13
  export declare class CommitRejectedError extends Error {
12
14
  #private;
@@ -14,16 +16,37 @@ export declare class CommitRejectedError extends Error {
14
16
  get proposals(): Array<ProposalWithSender>;
15
17
  get senderLeafIndex(): number | undefined;
16
18
  }
19
+ /**
20
+ * A control-ledger entry as a handle holds it: the signed token — the canonical
21
+ * persistent and wire form, the only thing that can be handed to another party —
22
+ * paired with its verified form. The verified form is a one-way derivation (the
23
+ * token cannot be reconstructed from it), so keeping only it would leave a handle
24
+ * unable to forward the ledger it holds.
25
+ */
26
+ export type HeldLedgerEntry = {
27
+ token: string;
28
+ verified: VerifiedLedgerEntry;
29
+ };
30
+ /** A held entry paired with its content id — one position in the ledger log. */
31
+ export type LedgerLogEntry = HeldLedgerEntry & {
32
+ entryID: string;
33
+ };
17
34
  export type GroupHandleParams = {
18
35
  state: ClientState;
19
36
  credential: MemberCredential;
20
37
  context: MlsContext;
21
- /** Stringified root capability (for delegation) */
22
- rootCapability: string;
38
+ /** The control-ledger log this handle starts from, in enactment order. A handle
39
+ * derived from another (commitInvite/removeMember) inherits the parent's, so the
40
+ * roster it folds does not revert to the anchor alone. */
41
+ ledger?: ReadonlyArray<LedgerLogEntry>;
23
42
  cache: DIDCache;
24
43
  resolver?: DIDResolver;
25
- /** Default commit policy applied by processMessage/decrypt. */
44
+ /** Default commit policy applied by processMessage. */
26
45
  commitPolicy?: IncomingMessageCallback;
46
+ /** Fetch control-ledger entry bodies the local ledger lacks (commit pre-pass). */
47
+ resolveLedgerEntries?: (ids: Array<string>) => Promise<Array<string>>;
48
+ /** Surface an accepted commit's notarized non-`group.role` entries to the consumer. */
49
+ onLedgerEntries?: (entries: Array<VerifiedLedgerEntry>) => void;
27
50
  };
28
51
  /**
29
52
  * Mutable wrapper around MLS group state + Enkaku credential.
@@ -36,13 +59,45 @@ export declare class GroupHandle {
36
59
  get treeHash(): Uint8Array;
37
60
  get credential(): MemberCredential;
38
61
  get state(): ClientState;
39
- get rootCapability(): string;
40
62
  get context(): MlsContext;
41
63
  get cache(): DIDCache;
42
64
  get resolver(): DIDResolver | undefined;
43
- /** The commit policy enforced by processMessage/decrypt, if any. Carried
44
- * onto handles derived from this one (commitInvite/removeMember). */
65
+ /** The commit policy enforced by processMessage, if any. Carried onto
66
+ * handles derived from this one (commitInvite/removeMember). */
45
67
  get commitPolicy(): IncomingMessageCallback | undefined;
68
+ /** The ledger-entry resolver, carried onto handles derived from this one. */
69
+ get resolveLedgerEntries(): ((ids: Array<string>) => Promise<Array<string>>) | undefined;
70
+ /** The accepted-commit entry sink, carried onto handles derived from this one. */
71
+ get onLedgerEntries(): ((entries: Array<VerifiedLedgerEntry>) => void) | undefined;
72
+ /** The genesis anchor seeded into this handle at construction. */
73
+ get anchor(): GroupAnchor;
74
+ /** The control-ledger log this handle holds, in enactment order, repeats and
75
+ * all. Carried onto handles derived from this one (commitInvite/removeMember). */
76
+ get ledger(): ReadonlyArray<LedgerLogEntry>;
77
+ /** The ordered signed tokens this handle holds, including repeats — the ledger's
78
+ * canonical persistent and wire form, and the list the authenticated head folds
79
+ * over. Feeds createInvite, restoreGroup, and host persistence. The verified
80
+ * entries are a derived cache with no export form: the only way into a ledger is
81
+ * applyLedgerEntries, which re-verifies. */
82
+ get ledgerTokens(): Array<string>;
83
+ /** The control roster folded from the anchor and every applied ledger entry. */
84
+ get roster(): RosterState;
85
+ /**
86
+ * Verify signed ledger tokens, append the valid ones to the log in the order
87
+ * given, and refold the roster. Tokens that fail verification or whose groupID
88
+ * does not match the group are dropped (defensive — this is the low-level apply
89
+ * primitive; the commit pre-pass does the strict admin-issuer enforcement).
90
+ * Every token is re-verified on the way in: no entry enters a ledger unverified,
91
+ * whatever the import path.
92
+ *
93
+ * A token the log already holds is appended again rather than skipped. The log
94
+ * is an ordered record of what each commit enacted, not a set of claims, and a
95
+ * repeat is the only way to express a demotion back to a previously-held role.
96
+ * Nothing replays a commit into it: MLS applies each commit exactly once,
97
+ * restoreGroup replays a token list once, and processWelcome folds an invite once.
98
+ * Runs serialized on the handle's mutex, like the other state-mutating operations.
99
+ */
100
+ applyLedgerEntries(tokens: Array<string>): Promise<void>;
46
101
  get memberCount(): number;
47
102
  findMemberLeafIndex(id: string): number | undefined;
48
103
  /**
@@ -53,25 +108,14 @@ export declare class GroupHandle {
53
108
  */
54
109
  listMembers(): Array<GroupMember>;
55
110
  /**
56
- * Encrypt an application message for the group.
111
+ * Encrypt an application message for the group, returning framed wire bytes.
112
+ * Encrypts at this handle's current epoch. A handle a commit has already
113
+ * superseded (see {@link commitInvite}, {@link removeMember},
114
+ * {@link commitLedgerEntries}) must not be reused to send — doing so silently
115
+ * emits an application message at the now-stale epoch; adopt the commit's
116
+ * `newGroup` and call `encrypt` on that instead.
57
117
  */
58
- encrypt(plaintext: Uint8Array): Promise<{
59
- message: unknown;
60
- consumed: Array<Uint8Array>;
61
- }>;
62
- /**
63
- * Decrypt an application message from the group.
64
- *
65
- * Accepts either wire-form bytes (framed MLSMessage `Uint8Array`) or a
66
- * pre-decoded ts-mls message object. The param type widens to `unknown`
67
- * because `Uint8Array | unknown` collapses to `unknown` in TypeScript; the
68
- * runtime `instanceof` check selects the decode path. Note: `encrypt`
69
- * currently emits objects, so the bytes path is for symmetry with
70
- * processMessage and future wire-form application messages.
71
- */
72
- decrypt(message: Uint8Array | unknown, opts?: {
73
- commitPolicy?: IncomingMessageCallback;
74
- }): Promise<Uint8Array>;
118
+ encrypt(plaintext: Uint8Array): Promise<Uint8Array>;
75
119
  /**
76
120
  * Process a received MLS message (Commit, Proposal, or application).
77
121
  *
@@ -96,7 +140,8 @@ export declare function createGroup(identity: OwnIdentity, groupID: string, opti
96
140
  export type RestoreGroupParams = {
97
141
  state: ClientState;
98
142
  credential: MemberCredential;
99
- rootCapability: string;
143
+ /** Signed ledger tokens the host persisted, replayed to rebuild the roster. */
144
+ ledgerEntries?: Array<string>;
100
145
  options?: GroupOptions;
101
146
  };
102
147
  export declare function restoreGroup(params: RestoreGroupParams): Promise<GroupHandle>;
@@ -112,8 +157,39 @@ export type CreateInviteResult = {
112
157
  /**
113
158
  * Create an invite for a new member.
114
159
  * Does NOT add them to the group — call commitInvite with their key package to do that.
160
+ *
161
+ * Only an admin may invite: a role entry from a non-admin issuer is dropped by every
162
+ * receiver's fold, so refusing here turns a silent downstream commit rejection into a
163
+ * local error.
115
164
  */
116
165
  export declare function createInvite(params: CreateInviteParams): Promise<CreateInviteResult>;
166
+ export type CommitLedgerEntriesResult = {
167
+ /** Framed MLSMessage bytes. Broadcast to existing members via the DS. */
168
+ commitMessage: Uint8Array;
169
+ newGroup: GroupHandle;
170
+ /** Post-commit epoch the group is now at (== newGroup.epoch). */
171
+ epoch: bigint;
172
+ };
173
+ /**
174
+ * The admin write path for the control ledger: a commit that carries no membership
175
+ * proposal, only the entries it enacts and the head move that covers them. This is how
176
+ * an admin promotes, demotes, or writes any other entry type — an entry that never
177
+ * rides a commit is invisible to the head, and a joiner recomputing the head would
178
+ * read the group's history as doctored.
179
+ *
180
+ * Enacts exactly `tokens`, at the end of the log — including one whose content the log
181
+ * already carries, which is how an admin is demoted back to a role they previously held.
182
+ * Rejects an empty `tokens` list: a commit that enacts nothing has no reason to be
183
+ * authored here.
184
+ *
185
+ * Reads `group`'s state and returns a NEW derived handle (`newGroup`); it never
186
+ * advances `group` itself. The caller must adopt `newGroup` — never reuse `group` —
187
+ * before issuing the next commit: two commits issued from the same source handle
188
+ * both frame at that handle's epoch and diverge. The per-handle mutex only
189
+ * serializes concurrent calls against one handle; it does not make it safe to
190
+ * produce a second commit from a handle a prior commit has already superseded.
191
+ */
192
+ export declare function commitLedgerEntries(group: GroupHandle, tokens: Array<string>): Promise<CommitLedgerEntriesResult>;
117
193
  export type CommitInviteResult = {
118
194
  /** Framed MLSMessage bytes. Broadcast to existing members via the DS. */
119
195
  commitMessage: Uint8Array;
@@ -129,8 +205,26 @@ export type CommitInviteResult = {
129
205
  /**
130
206
  * Commit an invite by adding the invitee's key package to the group.
131
207
  * Produces an MLS Commit + Welcome.
208
+ *
209
+ * The invite's ledger entries are enacted by this commit: their content ids ride in
210
+ * the commit's control envelope and the commit advances the ledger head by exactly
211
+ * those ids, so every receiver folds the invitee's role entry into its roster as it
212
+ * applies the Add. The envelope carries ids, not bodies — a receiver that holds
213
+ * neither the entry nor a `resolveLedgerEntries` resolver throws
214
+ * MissingLedgerEntriesError on this commit.
215
+ *
216
+ * The invite itself carries the group's whole history — a joiner has nothing to fold
217
+ * it onto — but only the entries it adds beyond that history ride the commit; see
218
+ * {@link entriesAddedByInvite} and {@link commitWithEntries}.
219
+ *
220
+ * Reads `group`'s state and returns a NEW derived handle (`newGroup`); it never
221
+ * advances `group` itself. The caller must adopt `newGroup` — never reuse `group` —
222
+ * before issuing the next commit: two commits issued from the same source handle
223
+ * both frame at that handle's epoch and diverge. The per-handle mutex only
224
+ * serializes concurrent calls against one handle; it does not make it safe to
225
+ * produce a second commit from a handle a prior commit has already superseded.
132
226
  */
133
- export declare function commitInvite(group: GroupHandle, keyPackage: KeyPackage): Promise<CommitInviteResult>;
227
+ export declare function commitInvite(group: GroupHandle, keyPackage: KeyPackage, invite: Invite): Promise<CommitInviteResult>;
134
228
  export type ProcessWelcomeResult = {
135
229
  group: GroupHandle;
136
230
  credential: MemberCredential;
@@ -162,8 +256,20 @@ export type RemoveMemberResult = {
162
256
  };
163
257
  /**
164
258
  * Remove a member from the group. Advances the epoch and rotates keys.
259
+ *
260
+ * Removal must demote: a receiver rejects a Remove whose target is still `admin` in
261
+ * the roster the commit's entries fold to. So removing an admin means riding the
262
+ * demotion entry on the same commit — pass it as `ledgerEntries`. The entry is signed
263
+ * by the caller, who holds the identity; this only carries it.
264
+ *
265
+ * Reads `group`'s state and returns a NEW derived handle (`newGroup`); it never
266
+ * advances `group` itself. The caller must adopt `newGroup` — never reuse `group` —
267
+ * before issuing the next commit: two commits issued from the same source handle
268
+ * both frame at that handle's epoch and diverge. The per-handle mutex only
269
+ * serializes concurrent calls against one handle; it does not make it safe to
270
+ * produce a second commit from a handle a prior commit has already superseded.
165
271
  */
166
- export declare function removeMember(group: GroupHandle, leafIndex: number): Promise<RemoveMemberResult>;
272
+ export declare function removeMember(group: GroupHandle, leafIndex: number, ledgerEntries?: Array<string>): Promise<RemoveMemberResult>;
167
273
  /**
168
274
  * Read the MLS epoch from a framed handshake/application message's cleartext
169
275
  * header, without decrypting. Advisory only — the header epoch is unauthenticated;