@kumiai/mls 0.2.0 → 0.3.1
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/group-commit.d.ts +100 -0
- package/lib/group-commit.js +252 -0
- package/lib/group-context.d.ts +11 -0
- package/lib/group-context.js +33 -0
- package/lib/group-create.d.ts +19 -0
- package/lib/group-create.js +85 -0
- package/lib/group-credential.d.ts +6 -0
- package/lib/group-credential.js +39 -0
- package/lib/group-handle.d.ts +196 -0
- package/lib/group-handle.js +691 -0
- package/lib/group-info.d.ts +57 -0
- package/lib/group-info.js +85 -0
- package/lib/group-membership.d.ts +25 -0
- package/lib/group-membership.js +36 -0
- package/lib/group-welcome.d.ts +67 -0
- package/lib/group-welcome.js +178 -0
- package/lib/group.d.ts +7 -339
- package/lib/group.js +7 -1194
- package/lib/head.d.ts +35 -38
- package/lib/head.js +43 -48
- package/lib/index.d.ts +3 -2
- package/lib/index.js +3 -2
- package/lib/recovery.d.ts +227 -0
- package/lib/recovery.js +456 -0
- package/lib/sender-data.d.ts +24 -0
- package/lib/sender-data.js +99 -0
- package/package.json +1 -1
|
@@ -0,0 +1,691 @@
|
|
|
1
|
+
import { normalizeDID } from '@kokuin/token';
|
|
2
|
+
import { contentTypes, createApplicationMessage, decode, encode, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, wireformats } from 'ts-mls';
|
|
3
|
+
import { readGroupAnchor } from './anchor.js';
|
|
4
|
+
import { parseMLSCredentialIdentity } from './credential.js';
|
|
5
|
+
import { decodeControlEnvelope } from './envelope.js';
|
|
6
|
+
import { foldEnvelope } from './envelope-fold.js';
|
|
7
|
+
import { readMessageEpoch } from './group-info.js';
|
|
8
|
+
import { assertHeadMatches, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, headsMatch, readLedgerHead, readLedgerHeadExtension } from './head.js';
|
|
9
|
+
import { ledgerEntryDigest, verifyLedgerEntry } from './ledger.js';
|
|
10
|
+
import { createMutex } from './mutex.js';
|
|
11
|
+
import { defaultCommitPolicy, MissingLedgerEntriesError } from './policy.js';
|
|
12
|
+
import { foldRoster } from './roster.js';
|
|
13
|
+
import { readSenderLeafIndex } from './sender-data.js';
|
|
14
|
+
/** One serializer per live handle, so its state-mutating operations run one at a
|
|
15
|
+
* time in issue order. Keyed weakly: the entry is collected with the handle, and
|
|
16
|
+
* the handle carries no reference back to it. */ const MUTEXES = new WeakMap();
|
|
17
|
+
export function mutexFor(handle) {
|
|
18
|
+
let mutex = MUTEXES.get(handle);
|
|
19
|
+
if (mutex === undefined) {
|
|
20
|
+
mutex = createMutex();
|
|
21
|
+
MUTEXES.set(handle, mutex);
|
|
22
|
+
}
|
|
23
|
+
return mutex;
|
|
24
|
+
}
|
|
25
|
+
/** Overwrite retired secret buffers ts-mls hands back as `consumed`, so key
|
|
26
|
+
* material does not linger in the heap after the state that used it is replaced. */ function zeroAll(buffers) {
|
|
27
|
+
for (const buffer of buffers)buffer.fill(0);
|
|
28
|
+
}
|
|
29
|
+
/** Thrown by GroupHandle.processMessage when the commit policy rejects an incoming
|
|
30
|
+
* commit. The handle is left at its pre-commit epoch. */ export class CommitRejectedError extends Error {
|
|
31
|
+
#proposals;
|
|
32
|
+
#senderLeafIndex;
|
|
33
|
+
constructor(proposals, senderLeafIndex){
|
|
34
|
+
super('Commit rejected by group commit policy');
|
|
35
|
+
this.name = 'CommitRejectedError';
|
|
36
|
+
this.#proposals = proposals;
|
|
37
|
+
this.#senderLeafIndex = senderLeafIndex;
|
|
38
|
+
}
|
|
39
|
+
get proposals() {
|
|
40
|
+
return this.#proposals;
|
|
41
|
+
}
|
|
42
|
+
get senderLeafIndex() {
|
|
43
|
+
return this.#senderLeafIndex;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Wrap a consumer commit policy to capture a rejected commit's proposals for
|
|
48
|
+
* CommitRejectedError. ts-mls does not surface them on its result, so record them
|
|
49
|
+
* from the callback's own argument on the 'reject' path. Undefined when no policy.
|
|
50
|
+
*/ function wrapCommitPolicy(callback, capture) {
|
|
51
|
+
if (callback == null) return undefined;
|
|
52
|
+
return (incoming)=>{
|
|
53
|
+
const action = callback(incoming);
|
|
54
|
+
if (action === 'reject' && incoming.kind === 'commit') {
|
|
55
|
+
capture.rejected = {
|
|
56
|
+
proposals: incoming.proposals,
|
|
57
|
+
senderLeafIndex: incoming.senderLeafIndex == null ? undefined : Number(incoming.senderLeafIndex)
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
return action;
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Read a PrivateMessage commit's cleartext `authenticatedData`, available before
|
|
65
|
+
* any epoch secret. Returns undefined for anything that is not a PrivateMessage of
|
|
66
|
+
* contentType commit (those keep the pre-envelope path). Narrows the `unknown`
|
|
67
|
+
* frame structurally, not by cast.
|
|
68
|
+
*/ function readPrivateCommit(decoded) {
|
|
69
|
+
if (decoded == null || typeof decoded !== 'object') return undefined;
|
|
70
|
+
const frame = decoded;
|
|
71
|
+
if (frame.wireformat !== wireformats.mls_private_message) return undefined;
|
|
72
|
+
const pm = frame.privateMessage;
|
|
73
|
+
if (pm == null || pm.contentType !== contentTypes.commit) return undefined;
|
|
74
|
+
const data = pm.authenticatedData;
|
|
75
|
+
return {
|
|
76
|
+
authenticatedData: data instanceof Uint8Array ? data : new Uint8Array()
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Narrow a decoded frame to the PrivateMessage-commit fields sender-data decrypt reads.
|
|
81
|
+
* Returns undefined for anything that is not a PrivateMessage of contentType commit.
|
|
82
|
+
*/ function readPrivateCommitFrame(decoded) {
|
|
83
|
+
if (decoded == null || typeof decoded !== 'object') return undefined;
|
|
84
|
+
const frame = decoded;
|
|
85
|
+
if (frame.wireformat !== wireformats.mls_private_message) return undefined;
|
|
86
|
+
const pm = frame.privateMessage;
|
|
87
|
+
if (pm == null || pm.contentType !== contentTypes.commit) return undefined;
|
|
88
|
+
if (!(pm.groupId instanceof Uint8Array) || typeof pm.epoch !== 'bigint' || !(pm.encryptedSenderData instanceof Uint8Array) || !(pm.ciphertext instanceof Uint8Array)) {
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
groupId: pm.groupId,
|
|
93
|
+
epoch: pm.epoch,
|
|
94
|
+
contentType: pm.contentType,
|
|
95
|
+
encryptedSenderData: pm.encryptedSenderData,
|
|
96
|
+
ciphertext: pm.ciphertext
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Read the DID an external-join commit proves control of. An external join is a
|
|
101
|
+
* PublicMessage from a joining non-member (senderType new_member_commit) carrying a
|
|
102
|
+
* commit; the committer holds no pre-commit leaf, so its DID rides the commit's own
|
|
103
|
+
* UpdatePath leaf credential. Returns undefined for anything else (keeps the
|
|
104
|
+
* pre-envelope path). Returns `{ did: undefined }` when the UpdatePath is absent or
|
|
105
|
+
* the leaf credential does not resolve to a basic-credential DID — cannot be a valid
|
|
106
|
+
* resync, so the caller rejects it. Narrows structurally.
|
|
107
|
+
*/ function readExternalCommit(decoded) {
|
|
108
|
+
if (decoded == null || typeof decoded !== 'object') return undefined;
|
|
109
|
+
const frame = decoded;
|
|
110
|
+
if (frame.wireformat !== wireformats.mls_public_message) return undefined;
|
|
111
|
+
const pm = frame.publicMessage;
|
|
112
|
+
if (pm == null || pm.senderType !== senderTypes.new_member_commit) return undefined;
|
|
113
|
+
const content = pm.content;
|
|
114
|
+
if (content == null || content.contentType !== contentTypes.commit) return undefined;
|
|
115
|
+
const commit = content.commit;
|
|
116
|
+
const path = commit?.path;
|
|
117
|
+
if (path == null) return {
|
|
118
|
+
did: undefined
|
|
119
|
+
};
|
|
120
|
+
const leafNode = path.leafNode;
|
|
121
|
+
const credential = leafNode?.credential;
|
|
122
|
+
if (credential == null || !(credential.identity instanceof Uint8Array)) {
|
|
123
|
+
return {
|
|
124
|
+
did: undefined
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
try {
|
|
128
|
+
return {
|
|
129
|
+
did: parseMLSCredentialIdentity(credential.identity).id
|
|
130
|
+
};
|
|
131
|
+
} catch {
|
|
132
|
+
return {
|
|
133
|
+
did: undefined
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Project a held ledger into the roster. foldRoster drops every non-`group.role`
|
|
139
|
+
* entry by type, so the mixed-type log is fed in whole. Replayed in order, repeats
|
|
140
|
+
* and all: a claim re-enacted at a later position must undo what came between.
|
|
141
|
+
*/ function foldLedgerRoster(ledger, anchor, groupID) {
|
|
142
|
+
const entries = ledger.map(({ verified, entryID })=>({
|
|
143
|
+
verified,
|
|
144
|
+
entryID
|
|
145
|
+
}));
|
|
146
|
+
return foldRoster(entries, anchor, groupID);
|
|
147
|
+
}
|
|
148
|
+
/** Mutable wrapper around MLS group state + Enkaku credential. */ export class GroupHandle {
|
|
149
|
+
#state;
|
|
150
|
+
#credential;
|
|
151
|
+
#context;
|
|
152
|
+
#cache;
|
|
153
|
+
#resolver;
|
|
154
|
+
#commitPolicy;
|
|
155
|
+
#resolveLedgerEntries;
|
|
156
|
+
#onLedgerEntries;
|
|
157
|
+
#anchor;
|
|
158
|
+
/** The ordered log of enactments — the ledger as the head chains it. A content id
|
|
159
|
+
* may appear more than once: re-enacting a claim at a later position undoes what
|
|
160
|
+
* came between, which is how a demotion back to a previously-held role works. */ #ledger;
|
|
161
|
+
/** Entry bodies by content id, for resolving the ids an envelope names. A body is
|
|
162
|
+
* the same wherever it appears in the log, so this store is keyed. */ #entryBodies;
|
|
163
|
+
#roster;
|
|
164
|
+
constructor(params){
|
|
165
|
+
this.#state = params.state;
|
|
166
|
+
this.#credential = params.credential;
|
|
167
|
+
this.#context = params.context;
|
|
168
|
+
this.#cache = params.cache;
|
|
169
|
+
this.#resolver = params.resolver;
|
|
170
|
+
this.#commitPolicy = params.commitPolicy;
|
|
171
|
+
this.#resolveLedgerEntries = params.resolveLedgerEntries;
|
|
172
|
+
this.#onLedgerEntries = params.onLedgerEntries;
|
|
173
|
+
// Seed control state from the genesis anchor in the group's GroupContext. Reading
|
|
174
|
+
// it here makes the constructor the single choke no anchorless handle slips
|
|
175
|
+
// through: an absent anchor fails closed rather than installing a permissive roster.
|
|
176
|
+
const anchor = readGroupAnchor(this);
|
|
177
|
+
if (anchor == null) {
|
|
178
|
+
throw new Error('group has no anchor extension; cannot seed a control roster');
|
|
179
|
+
}
|
|
180
|
+
this.#anchor = anchor;
|
|
181
|
+
this.#ledger = [
|
|
182
|
+
...params.ledger ?? []
|
|
183
|
+
];
|
|
184
|
+
this.#entryBodies = new Map(this.#ledger.map(({ entryID, token, verified })=>[
|
|
185
|
+
entryID,
|
|
186
|
+
{
|
|
187
|
+
token,
|
|
188
|
+
verified
|
|
189
|
+
}
|
|
190
|
+
]));
|
|
191
|
+
this.#roster = foldLedgerRoster(this.#ledger, anchor, this.groupID);
|
|
192
|
+
}
|
|
193
|
+
get groupID() {
|
|
194
|
+
return this.#credential.groupID;
|
|
195
|
+
}
|
|
196
|
+
get epoch() {
|
|
197
|
+
return this.#state.groupContext.epoch;
|
|
198
|
+
}
|
|
199
|
+
get treeHash() {
|
|
200
|
+
return this.#state.groupContext.treeHash;
|
|
201
|
+
}
|
|
202
|
+
get credential() {
|
|
203
|
+
return this.#credential;
|
|
204
|
+
}
|
|
205
|
+
get state() {
|
|
206
|
+
return this.#state;
|
|
207
|
+
}
|
|
208
|
+
get context() {
|
|
209
|
+
return this.#context;
|
|
210
|
+
}
|
|
211
|
+
get cache() {
|
|
212
|
+
return this.#cache;
|
|
213
|
+
}
|
|
214
|
+
get resolver() {
|
|
215
|
+
return this.#resolver;
|
|
216
|
+
}
|
|
217
|
+
/** The commit policy enforced by processMessage, if any. Carried onto
|
|
218
|
+
* handles derived from this one (commitInvite/removeMember). */ get commitPolicy() {
|
|
219
|
+
return this.#commitPolicy;
|
|
220
|
+
}
|
|
221
|
+
/** The ledger-entry resolver, carried onto handles derived from this one. */ get resolveLedgerEntries() {
|
|
222
|
+
return this.#resolveLedgerEntries;
|
|
223
|
+
}
|
|
224
|
+
/** The accepted-commit entry sink, carried onto handles derived from this one. */ get onLedgerEntries() {
|
|
225
|
+
return this.#onLedgerEntries;
|
|
226
|
+
}
|
|
227
|
+
/** The genesis anchor seeded into this handle at construction. */ get anchor() {
|
|
228
|
+
return this.#anchor;
|
|
229
|
+
}
|
|
230
|
+
/** The control-ledger log this handle holds, in enactment order, repeats and
|
|
231
|
+
* all. Carried onto handles derived from this one (commitInvite/removeMember). */ get ledger() {
|
|
232
|
+
return this.#ledger;
|
|
233
|
+
}
|
|
234
|
+
/** The ordered signed tokens this handle holds, repeats included — the ledger's
|
|
235
|
+
* canonical persistent/wire form, and the list the authenticated head folds over.
|
|
236
|
+
* Feeds createInvite, restoreGroup, and host persistence. The verified entries are
|
|
237
|
+
* a derived cache with no export form: the only way in is applyLedgerEntries,
|
|
238
|
+
* which re-verifies. */ get ledgerTokens() {
|
|
239
|
+
return this.#ledger.map(({ token })=>token);
|
|
240
|
+
}
|
|
241
|
+
/** The control roster folded from the anchor and every applied ledger entry. */ get roster() {
|
|
242
|
+
return this.#roster;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Verify signed ledger tokens, append the valid ones in the order given, and
|
|
246
|
+
* refold the roster. Tokens that fail verification or whose groupID mismatches are
|
|
247
|
+
* dropped (defensive — the strict admin-issuer enforcement is the commit pre-pass).
|
|
248
|
+
* Every token is re-verified on the way in: no entry enters a ledger unverified,
|
|
249
|
+
* whatever the import path.
|
|
250
|
+
*
|
|
251
|
+
* A token the log already holds is appended again, not skipped: the log records
|
|
252
|
+
* what each commit enacted, not a set of claims, and a repeat is the only way to
|
|
253
|
+
* express a demotion back to a previously-held role. Nothing replays a commit into
|
|
254
|
+
* it (MLS applies each once, restoreGroup replays a token list once, processWelcome
|
|
255
|
+
* folds an invite once). Serialized on the handle's mutex.
|
|
256
|
+
*/ async applyLedgerEntries(tokens) {
|
|
257
|
+
return mutexFor(this).run(async ()=>{
|
|
258
|
+
for (const token of tokens){
|
|
259
|
+
const verified = await verifyLedgerEntry(token);
|
|
260
|
+
if (verified == null || verified.entry.groupID !== this.groupID) continue;
|
|
261
|
+
const entryID = ledgerEntryDigest(token);
|
|
262
|
+
this.#ledger.push({
|
|
263
|
+
entryID,
|
|
264
|
+
token,
|
|
265
|
+
verified
|
|
266
|
+
});
|
|
267
|
+
this.#entryBodies.set(entryID, {
|
|
268
|
+
token,
|
|
269
|
+
verified
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
this.#roster = foldLedgerRoster(this.#ledger, this.#anchor, this.groupID);
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Whether the ledger this handle holds is the whole ledger its GroupContext
|
|
277
|
+
* attests to: the head folded from the ids it holds, in order, against the
|
|
278
|
+
* authenticated `ledger_head`.
|
|
279
|
+
*
|
|
280
|
+
* Purely local — reads this handle's ledger and GroupContext, consults no peer.
|
|
281
|
+
* False means incomplete (e.g. an external-commit rejoin arrives with an *empty*
|
|
282
|
+
* ledger against a live, non-genesis head), and {@link bootstrapLedger} must run
|
|
283
|
+
* before the handle can be trusted to fold a roster or judge a commit.
|
|
284
|
+
*
|
|
285
|
+
* A group with no entries reads true, non-vacuously: the empty fold is the genesis
|
|
286
|
+
* head (a real 32-byte digest bound to this group), which matches only a head that
|
|
287
|
+
* has never moved — exactly a genuinely empty ledger.
|
|
288
|
+
*/ async isLedgerComplete() {
|
|
289
|
+
return mutexFor(this).run(async ()=>{
|
|
290
|
+
const authenticated = readLedgerHead(this);
|
|
291
|
+
if (authenticated == null) {
|
|
292
|
+
// No head extension attests to no ledger, so nothing can be shown complete.
|
|
293
|
+
// Report incomplete and let bootstrap fail loudly.
|
|
294
|
+
return false;
|
|
295
|
+
}
|
|
296
|
+
return headsMatch(authenticated.head, computeHead(this.groupID, this.#ledger.map(({ entryID })=>entryID)));
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* The whole ordered ledger this handle holds, as signed tokens — what a responder
|
|
301
|
+
* serves to a bootstrapping peer. Order is load-bearing: the head is a chain
|
|
302
|
+
* digest, so a permuted list folds to a different head and is rejected.
|
|
303
|
+
*/ async getLedger() {
|
|
304
|
+
return mutexFor(this).run(async ()=>this.ledgerTokens);
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Install a gathered ledger, verified against the authenticated head before a
|
|
308
|
+
* single entry is folded.
|
|
309
|
+
*
|
|
310
|
+
* The gathered list is the group's WHOLE ledger from genesis, not a delta: a list
|
|
311
|
+
* that reproduces the head this GroupContext carries *is* the entire ledger, in
|
|
312
|
+
* order, and replaces whatever this handle held.
|
|
313
|
+
*
|
|
314
|
+
* Check before fold, structurally: the head is recomputed over the incoming
|
|
315
|
+
* `tokens` while the handle's ledger, entry bodies, and roster are untouched, and
|
|
316
|
+
* the fold's results are installed in one assignment at the end. A rejected ledger
|
|
317
|
+
* writes nothing — no half-applied window, no rollback.
|
|
318
|
+
*
|
|
319
|
+
* Signatures alone do not cover this: a lying responder can hand back genuinely
|
|
320
|
+
* signed, correctly scoped tokens with one demotion omitted or two transposed —
|
|
321
|
+
* every signature verifies, yet the folded roster contains an admin the group
|
|
322
|
+
* demoted. Omission and reordering are exactly what the head chain protects and
|
|
323
|
+
* signatures do not. The bound: **a lying responder can withhold, never rewrite.**
|
|
324
|
+
*
|
|
325
|
+
* Throws {@link LedgerIncompleteError} on a head mismatch; the caller drops that
|
|
326
|
+
* responder and tries the next.
|
|
327
|
+
*/ async bootstrapLedger(tokens) {
|
|
328
|
+
return mutexFor(this).run(async ()=>{
|
|
329
|
+
const authenticated = readLedgerHead(this);
|
|
330
|
+
if (authenticated == null) {
|
|
331
|
+
throw new Error('bootstrapLedger: the group has no ledger head extension');
|
|
332
|
+
}
|
|
333
|
+
// The gate. Nothing below touches the handle until the last three statements,
|
|
334
|
+
// and nothing above reads the tokens except for their content ids.
|
|
335
|
+
const entryIDs = tokens.map(ledgerEntryDigest);
|
|
336
|
+
assertHeadMatches(authenticated.head, computeHead(this.groupID, entryIDs));
|
|
337
|
+
const log = [];
|
|
338
|
+
for(let index = 0; index < tokens.length; index++){
|
|
339
|
+
const token = tokens[index];
|
|
340
|
+
const verified = await verifyLedgerEntry(token);
|
|
341
|
+
if (verified == null || verified.entry.groupID !== this.groupID) {
|
|
342
|
+
// Unreachable past the gate — the chain digests the token bytes, so an
|
|
343
|
+
// unverifiable or cross-group token cannot sit at a position the head
|
|
344
|
+
// covers. Fails closed anyway.
|
|
345
|
+
throw new Error('bootstrapLedger: the gathered ledger holds an unverifiable or cross-group entry');
|
|
346
|
+
}
|
|
347
|
+
log.push({
|
|
348
|
+
entryID: entryIDs[index],
|
|
349
|
+
token,
|
|
350
|
+
verified
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
this.#ledger = log;
|
|
354
|
+
this.#entryBodies = new Map(log.map(({ entryID, token, verified })=>[
|
|
355
|
+
entryID,
|
|
356
|
+
{
|
|
357
|
+
token,
|
|
358
|
+
verified
|
|
359
|
+
}
|
|
360
|
+
]));
|
|
361
|
+
this.#roster = foldLedgerRoster(log, this.#anchor, this.groupID);
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
get memberCount() {
|
|
365
|
+
return this.#state.ratchetTree.filter((node)=>node != null && node.nodeType === nodeTypes.leaf).length;
|
|
366
|
+
}
|
|
367
|
+
*#iterateMembers() {
|
|
368
|
+
const tree = this.#state.ratchetTree;
|
|
369
|
+
for(let i = 0; i < tree.length; i++){
|
|
370
|
+
const node = tree[i];
|
|
371
|
+
if (node != null && node.nodeType === nodeTypes.leaf) {
|
|
372
|
+
const credential = node.leaf.credential;
|
|
373
|
+
if ('identity' in credential) {
|
|
374
|
+
let parsed;
|
|
375
|
+
try {
|
|
376
|
+
parsed = parseMLSCredentialIdentity(credential.identity);
|
|
377
|
+
} catch {
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
yield {
|
|
381
|
+
leafIndex: i / 2,
|
|
382
|
+
id: parsed.id
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
findMemberLeafIndex(id) {
|
|
389
|
+
const targetNorm = normalizeDID(id);
|
|
390
|
+
for (const member of this.#iterateMembers()){
|
|
391
|
+
if (normalizeDID(member.id) === targetNorm) return member.leafIndex;
|
|
392
|
+
}
|
|
393
|
+
return undefined;
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* The group's current members from the ratchet tree, in ascending leaf-index
|
|
397
|
+
* order. Leaves whose credential identity fails to parse are skipped (like
|
|
398
|
+
* findMemberLeafIndex). Reflects current #state — call before and after
|
|
399
|
+
* processMessage to diff a commit's membership change.
|
|
400
|
+
*/ listMembers() {
|
|
401
|
+
return [
|
|
402
|
+
...this.#iterateMembers()
|
|
403
|
+
];
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Encrypt an application message for the group at this handle's current epoch,
|
|
407
|
+
* returning framed wire bytes. A handle a commit has already superseded (see
|
|
408
|
+
* {@link commitInvite}, {@link removeMember}, {@link commitLedgerEntries}) must not
|
|
409
|
+
* be reused to send — it silently emits at the now-stale epoch. Adopt the commit's
|
|
410
|
+
* `newGroup` and encrypt on that.
|
|
411
|
+
*/ async encrypt(plaintext) {
|
|
412
|
+
return mutexFor(this).run(async ()=>{
|
|
413
|
+
const { newState, message, consumed } = await createApplicationMessage({
|
|
414
|
+
context: this.#context,
|
|
415
|
+
state: this.#state,
|
|
416
|
+
message: plaintext
|
|
417
|
+
});
|
|
418
|
+
this.#state = newState;
|
|
419
|
+
zeroAll(consumed);
|
|
420
|
+
return encode(mlsMessageEncoder, message);
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* The async pre-pass feeding the synchronous ts-mls commit callback, run before
|
|
425
|
+
* mlsProcessMessage. For anything that is not a PrivateMessage commit it just
|
|
426
|
+
* resolves the caller policy, wraps it for rejected-proposal capture, and applies
|
|
427
|
+
* nothing on accept.
|
|
428
|
+
*
|
|
429
|
+
* For a PrivateMessage commit it decodes the control envelope, resolves and
|
|
430
|
+
* verifies the entry bodies it names, folds a candidate roster off the pre-commit
|
|
431
|
+
* state, and precomputes the pure inputs the sync callback reads. That callback is
|
|
432
|
+
* a pure lookup: decode/fold failure is a hard reject; else a caller policy wins,
|
|
433
|
+
* and with none the anchored default policy runs. Missing entry bodies with no
|
|
434
|
+
* resolver throw MissingLedgerEntriesError HERE — before mlsProcessMessage — so the
|
|
435
|
+
* handle stays at its pre-commit epoch.
|
|
436
|
+
*/ async #prepareCommitPipeline(decoded, opts) {
|
|
437
|
+
const callerPolicy = opts?.commitPolicy ?? this.#commitPolicy;
|
|
438
|
+
const capture = {};
|
|
439
|
+
const commit = readPrivateCommit(decoded);
|
|
440
|
+
let externalCommitDID;
|
|
441
|
+
let isCommitMessage = commit != null;
|
|
442
|
+
if (commit == null) {
|
|
443
|
+
const external = readExternalCommit(decoded);
|
|
444
|
+
if (external != null) {
|
|
445
|
+
externalCommitDID = external.did;
|
|
446
|
+
isCommitMessage = true;
|
|
447
|
+
}
|
|
448
|
+
// else: a standalone by-reference Proposal (or an application message / a
|
|
449
|
+
// frame ts-mls will not call back on). Fall through with the roster unchanged
|
|
450
|
+
// so `combined` judges a kind:'proposal' incoming under the same
|
|
451
|
+
// defaultCommitPolicy rows applied to a commit's proposals; a non-admin's
|
|
452
|
+
// authority-bearing proposal is rejected on receipt and never stored.
|
|
453
|
+
// Application messages never reach the callback, so this is inert for them.
|
|
454
|
+
}
|
|
455
|
+
let precomputedReject = false;
|
|
456
|
+
let candidateRoster = this.#roster;
|
|
457
|
+
let surfaced = [];
|
|
458
|
+
let acceptedEntries = [];
|
|
459
|
+
let envelopeIDs = [];
|
|
460
|
+
if (isCommitMessage) {
|
|
461
|
+
if (commit == null) {
|
|
462
|
+
// An external-join commit carries no control envelope: resolves nothing,
|
|
463
|
+
// folds nothing, never moves the head; candidate roster is unchanged. Its
|
|
464
|
+
// only precomputed reject is an unresolvable committer DID (no UpdatePath /
|
|
465
|
+
// bad credential), which cannot be a valid resync.
|
|
466
|
+
precomputedReject = externalCommitDID === undefined;
|
|
467
|
+
} else {
|
|
468
|
+
const env = decodeControlEnvelope(commit.authenticatedData);
|
|
469
|
+
if (!env.ok) {
|
|
470
|
+
precomputedReject = true;
|
|
471
|
+
} else {
|
|
472
|
+
const ids = env.envelope.entries ?? [];
|
|
473
|
+
envelopeIDs = ids;
|
|
474
|
+
const resolved = new Map();
|
|
475
|
+
const missing = [];
|
|
476
|
+
for (const id of ids){
|
|
477
|
+
const held = this.#entryBodies.get(id);
|
|
478
|
+
if (held != null) {
|
|
479
|
+
resolved.set(id, {
|
|
480
|
+
...held,
|
|
481
|
+
entryID: id
|
|
482
|
+
});
|
|
483
|
+
} else {
|
|
484
|
+
missing.push(id);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
if (missing.length > 0) {
|
|
488
|
+
if (this.#resolveLedgerEntries == null) {
|
|
489
|
+
throw new MissingLedgerEntriesError(missing);
|
|
490
|
+
}
|
|
491
|
+
const tokens = await this.#resolveLedgerEntries(missing);
|
|
492
|
+
for (const token of tokens){
|
|
493
|
+
const id = ledgerEntryDigest(token);
|
|
494
|
+
// Content-addressing binds the untrusted body to the requested id.
|
|
495
|
+
if (resolved.has(id) || !missing.includes(id)) continue;
|
|
496
|
+
const verified = await verifyLedgerEntry(token);
|
|
497
|
+
if (verified == null) continue;
|
|
498
|
+
resolved.set(id, {
|
|
499
|
+
token,
|
|
500
|
+
verified,
|
|
501
|
+
entryID: id
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
const stillMissing = missing.filter((id)=>!resolved.has(id));
|
|
505
|
+
if (stillMissing.length > 0) {
|
|
506
|
+
throw new MissingLedgerEntriesError(stillMissing);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
const ordered = ids.map((id)=>{
|
|
510
|
+
const input = resolved.get(id);
|
|
511
|
+
if (input == null) throw new MissingLedgerEntriesError([
|
|
512
|
+
id
|
|
513
|
+
]);
|
|
514
|
+
return input;
|
|
515
|
+
});
|
|
516
|
+
const foldResult = foldEnvelope(this.#roster, ordered, this.groupID);
|
|
517
|
+
if (!foldResult.ok) {
|
|
518
|
+
precomputedReject = true;
|
|
519
|
+
} else {
|
|
520
|
+
candidateRoster = foldResult.roster;
|
|
521
|
+
surfaced = foldResult.surfaced;
|
|
522
|
+
acceptedEntries = ordered;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
const context = buildCommitPolicyContext(this, {
|
|
528
|
+
baseRoster: this.#roster,
|
|
529
|
+
candidateRoster,
|
|
530
|
+
entryIDs: envelopeIDs,
|
|
531
|
+
...externalCommitDID !== undefined && {
|
|
532
|
+
externalCommitDID
|
|
533
|
+
}
|
|
534
|
+
});
|
|
535
|
+
const combined = (incoming)=>{
|
|
536
|
+
// A decode/fold failure is a hard reject even under a caller policy: the
|
|
537
|
+
// ledger the commit depends on is unresolvable or malformed.
|
|
538
|
+
if (precomputedReject) return 'reject';
|
|
539
|
+
if (callerPolicy != null) return callerPolicy(incoming);
|
|
540
|
+
return defaultCommitPolicy(incoming, context);
|
|
541
|
+
};
|
|
542
|
+
const applyOnAccept = ()=>{
|
|
543
|
+
// Appended, never deduped: the log records what this commit enacted, at the
|
|
544
|
+
// position the head chained it.
|
|
545
|
+
for (const { token, verified, entryID } of acceptedEntries){
|
|
546
|
+
this.#ledger.push({
|
|
547
|
+
entryID,
|
|
548
|
+
token,
|
|
549
|
+
verified
|
|
550
|
+
});
|
|
551
|
+
this.#entryBodies.set(entryID, {
|
|
552
|
+
token,
|
|
553
|
+
verified
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
this.#roster = candidateRoster;
|
|
557
|
+
if (surfaced.length > 0) this.#onLedgerEntries?.(surfaced);
|
|
558
|
+
};
|
|
559
|
+
return {
|
|
560
|
+
callback: wrapCommitPolicy(combined, capture),
|
|
561
|
+
capture,
|
|
562
|
+
applyOnAccept
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
/** The DID at a ratchet-tree leaf index, or undefined if that leaf is empty/unparsable. */ #didOfLeaf(leafIndex) {
|
|
566
|
+
for (const member of this.#iterateMembers()){
|
|
567
|
+
if (member.leafIndex === leafIndex) return member.id;
|
|
568
|
+
}
|
|
569
|
+
return undefined;
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Read a Commit's MLS-authenticated committer against this handle, WITHOUT advancing
|
|
573
|
+
* state. `null` for bytes that are not a Commit.
|
|
574
|
+
*
|
|
575
|
+
* A member commit (PrivateMessage) has its committer encrypted under the epoch's
|
|
576
|
+
* sender-data secret: decrypt it to the sender leaf index and resolve that against this
|
|
577
|
+
* handle's ratchet tree — the same leaf->DID the commit policy sees as
|
|
578
|
+
* `didOfLeaf(senderLeafIndex)`. An external commit's committer rides its UpdatePath leaf
|
|
579
|
+
* instead (see {@link readExternalCommit}) — no tree lookup, no sender-data decrypt.
|
|
580
|
+
* `null` for anything that is neither.
|
|
581
|
+
*
|
|
582
|
+
* Runs on the handle mutex so the epoch secret, tree, and epoch are one snapshot against a
|
|
583
|
+
* concurrent processMessage. Non-mutating: sender-data decrypt is epoch-level and consumes
|
|
584
|
+
* no per-message key. Async only because the KDF and AEAD are.
|
|
585
|
+
*/ async readCommitHeader(commit) {
|
|
586
|
+
return mutexFor(this).run(async ()=>{
|
|
587
|
+
let decoded;
|
|
588
|
+
try {
|
|
589
|
+
decoded = decode(mlsMessageDecoder, commit);
|
|
590
|
+
} catch {
|
|
591
|
+
// ts-mls `decode` throws CodecError on malformed/truncated frames; the contract is
|
|
592
|
+
// "null for bytes that are not a Commit", and the lane treats null as poison (advance
|
|
593
|
+
// the cursor, never retry). An unguarded throw would instead wedge the commit lane on
|
|
594
|
+
// this frame forever. Mirrors readMessageEpoch, which guards this same decode.
|
|
595
|
+
return null;
|
|
596
|
+
}
|
|
597
|
+
if (decoded == null) return null;
|
|
598
|
+
const epoch = readMessageEpoch(commit);
|
|
599
|
+
if (epoch == null) return null;
|
|
600
|
+
// External-join commit: the committer holds no pre-commit leaf, so its DID rides the
|
|
601
|
+
// commit's own UpdatePath leaf. No tree lookup, no sender-data decrypt.
|
|
602
|
+
const external = readExternalCommit(decoded);
|
|
603
|
+
if (external != null) {
|
|
604
|
+
return external.did == null ? null : {
|
|
605
|
+
epoch,
|
|
606
|
+
committerDID: external.did
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
const pm = readPrivateCommitFrame(decoded);
|
|
610
|
+
if (pm == null) return null // non-commit frame
|
|
611
|
+
;
|
|
612
|
+
const leafIndex = await readSenderLeafIndex(this.#context, this.#state.keySchedule.senderDataSecret, pm);
|
|
613
|
+
if (leafIndex == null) return null;
|
|
614
|
+
const committerDID = this.#didOfLeaf(leafIndex);
|
|
615
|
+
return committerDID == null ? null : {
|
|
616
|
+
epoch,
|
|
617
|
+
committerDID
|
|
618
|
+
};
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Process a received MLS message (Commit, Proposal, or application). Accepts
|
|
623
|
+
* wire-form bytes (preferred, e.g. from commitInvite/removeMember) or a pre-decoded
|
|
624
|
+
* ts-mls object (legacy). Param widens to `unknown` because `Uint8Array | unknown`
|
|
625
|
+
* collapses to `unknown`; the runtime `instanceof` selects the decode path.
|
|
626
|
+
*/ async processMessage(message, opts) {
|
|
627
|
+
let decoded = message;
|
|
628
|
+
if (message instanceof Uint8Array) {
|
|
629
|
+
const parsed = decode(mlsMessageDecoder, message);
|
|
630
|
+
if (parsed == null) {
|
|
631
|
+
throw new Error('processMessage: failed to decode MLSMessage');
|
|
632
|
+
}
|
|
633
|
+
decoded = parsed;
|
|
634
|
+
}
|
|
635
|
+
return mutexFor(this).run(async ()=>{
|
|
636
|
+
const { callback, capture, applyOnAccept } = await this.#prepareCommitPipeline(decoded, opts);
|
|
637
|
+
const result = await mlsProcessMessage({
|
|
638
|
+
context: this.#context,
|
|
639
|
+
state: this.#state,
|
|
640
|
+
message: decoded,
|
|
641
|
+
...callback != null && {
|
|
642
|
+
callback
|
|
643
|
+
}
|
|
644
|
+
});
|
|
645
|
+
this.#state = result.newState;
|
|
646
|
+
zeroAll(result.consumed);
|
|
647
|
+
if (result.kind === 'newState' && result.actionTaken === 'reject') {
|
|
648
|
+
throw new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex);
|
|
649
|
+
}
|
|
650
|
+
if (result.kind === 'applicationMessage') {
|
|
651
|
+
return result.message;
|
|
652
|
+
}
|
|
653
|
+
applyOnAccept();
|
|
654
|
+
return null;
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
/** Build the CommitPolicyContext both the receive gate and the send-side pending
|
|
659
|
+
* filter judge against, so the two always agree. `entryIDs` are the ledger entry
|
|
660
|
+
* ids this commit enacts (drives the expected head); `candidateRoster` is the
|
|
661
|
+
* post-fold roster receivers install. */ export function buildCommitPolicyContext(handle, args) {
|
|
662
|
+
const leafToDID = new Map();
|
|
663
|
+
for (const member of handle.listMembers())leafToDID.set(member.leafIndex, member.id);
|
|
664
|
+
const headExt = readLedgerHeadExtension(handle);
|
|
665
|
+
const currentHead = headExt != null && headExt.extensionData instanceof Uint8Array ? decodeLedgerHead(headExt.extensionData) : null;
|
|
666
|
+
const expectedHeadExtensionData = currentHead == null ? new Uint8Array() : encodeLedgerHead(extendHead(currentHead.head, args.entryIDs));
|
|
667
|
+
return {
|
|
668
|
+
baseRoster: args.baseRoster,
|
|
669
|
+
candidateRoster: args.candidateRoster,
|
|
670
|
+
didOfLeaf: (leafIndex)=>leafToDID.get(leafIndex),
|
|
671
|
+
currentExtensions: handle.state.groupContext.extensions,
|
|
672
|
+
expectedHeadExtensionData,
|
|
673
|
+
commitEnactsEntries: args.entryIDs.length > 0,
|
|
674
|
+
...args.externalCommitDID !== undefined && {
|
|
675
|
+
externalCommitDID: args.externalCommitDID
|
|
676
|
+
}
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
/** Build the handle a commit hands back: the post-commit state, everything else inherited. */ export function deriveGroup(group, state) {
|
|
680
|
+
return new GroupHandle({
|
|
681
|
+
state,
|
|
682
|
+
credential: group.credential,
|
|
683
|
+
context: group.context,
|
|
684
|
+
ledger: group.ledger,
|
|
685
|
+
cache: group.cache,
|
|
686
|
+
resolver: group.resolver,
|
|
687
|
+
commitPolicy: group.commitPolicy,
|
|
688
|
+
resolveLedgerEntries: group.resolveLedgerEntries,
|
|
689
|
+
onLedgerEntries: group.onLedgerEntries
|
|
690
|
+
});
|
|
691
|
+
}
|