@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/README.md +21 -9
- package/lib/anchor.d.ts +87 -0
- package/lib/anchor.js +124 -0
- package/lib/credential.d.ts +3 -12
- package/lib/credential.js +0 -13
- package/lib/envelope-fold.d.ts +35 -0
- package/lib/envelope-fold.js +86 -0
- package/lib/envelope.d.ts +53 -0
- package/lib/envelope.js +87 -0
- package/lib/fold.d.ts +68 -0
- package/lib/fold.js +53 -0
- package/lib/group.d.ts +136 -30
- package/lib/group.js +726 -185
- package/lib/head.d.ts +82 -0
- package/lib/head.js +155 -0
- package/lib/index.d.ts +10 -3
- package/lib/index.js +10 -3
- package/lib/ledger.d.ts +49 -0
- package/lib/ledger.js +67 -0
- package/lib/mutex.d.ts +14 -0
- package/lib/mutex.js +20 -0
- package/lib/policy.d.ts +71 -0
- package/lib/policy.js +191 -0
- package/lib/roster.d.ts +45 -0
- package/lib/roster.js +72 -0
- package/lib/types.d.ts +31 -11
- package/package.json +2 -3
- package/lib/capability.d.ts +0 -47
- package/lib/capability.js +0 -79
package/lib/group.js
CHANGED
|
@@ -1,11 +1,33 @@
|
|
|
1
|
-
import { createInMemoryDIDCache, isPeer4, normalizeDID
|
|
2
|
-
import { createApplicationMessage, createCommit, createGroupInfoWithExternalPubAndRatchetTree, decode, defaultCapabilities, defaultCredentialTypes, defaultProposalTypes, encode, generateKeyPackageWithKey, getCiphersuiteImpl, createGroup as mlsCreateGroup, joinGroup as mlsJoinGroup, joinGroupExternal as mlsJoinGroupExternal, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, protocolVersions, wireformats } from 'ts-mls';
|
|
1
|
+
import { createInMemoryDIDCache, isPeer4, normalizeDID } from '@kokuin/token';
|
|
2
|
+
import { contentTypes, createApplicationMessage, createCommit, createGroupInfoWithExternalPubAndRatchetTree, decode, defaultCapabilities, defaultCredentialTypes, defaultProposalTypes, encode, generateKeyPackageWithKey, getCiphersuiteImpl, createGroup as mlsCreateGroup, joinGroup as mlsJoinGroup, joinGroupExternal as mlsJoinGroupExternal, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, protocolVersions, senderTypes, wireformats } from 'ts-mls';
|
|
3
|
+
import { buildCurrentGroupAnchorExtension, controlCapabilities, decodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE, LEDGER_HEAD_EXTENSION_TYPE, readGroupAnchor } from './anchor.js';
|
|
3
4
|
import { createDIDAuthenticationService } from './authentication.js';
|
|
4
|
-
import { createGroupCapability, delegateGroupMembership } from './capability.js';
|
|
5
5
|
import { sanitizeRatchetTree } from './codec.js';
|
|
6
6
|
import { parseMLSCredentialIdentity } from './credential.js';
|
|
7
7
|
import { nobleCryptoProvider } from './crypto.js';
|
|
8
|
+
import { decodeControlEnvelope, encodeControlEnvelope } from './envelope.js';
|
|
9
|
+
import { foldEnvelope } from './envelope-fold.js';
|
|
10
|
+
import { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, readLedgerHead, readLedgerHeadExtension } from './head.js';
|
|
11
|
+
import { ledgerEntryDigest, signLedgerEntry, verifyLedgerEntry } from './ledger.js';
|
|
12
|
+
import { createMutex } from './mutex.js';
|
|
13
|
+
import { defaultCommitPolicy, MissingLedgerEntriesError } from './policy.js';
|
|
14
|
+
import { foldRoster, ROLE_ENTRY_TYPE } from './roster.js';
|
|
8
15
|
const DEFAULT_CIPHERSUITE = 'MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519';
|
|
16
|
+
/** One serializer per live handle, so its state-mutating operations run one at a
|
|
17
|
+
* time in issue order. Keyed weakly: the entry is collected with the handle, and
|
|
18
|
+
* the handle carries no reference back to it. */ const MUTEXES = new WeakMap();
|
|
19
|
+
function mutexFor(handle) {
|
|
20
|
+
let mutex = MUTEXES.get(handle);
|
|
21
|
+
if (mutex === undefined) {
|
|
22
|
+
mutex = createMutex();
|
|
23
|
+
MUTEXES.set(handle, mutex);
|
|
24
|
+
}
|
|
25
|
+
return mutex;
|
|
26
|
+
}
|
|
27
|
+
/** Overwrite retired secret buffers ts-mls hands back as `consumed`, so key
|
|
28
|
+
* material does not linger in the heap after the state that used it is replaced. */ function zeroAll(buffers) {
|
|
29
|
+
for (const buffer of buffers)buffer.fill(0);
|
|
30
|
+
}
|
|
9
31
|
async function resolveMlsContext(options) {
|
|
10
32
|
const name = options?.ciphersuiteName ?? DEFAULT_CIPHERSUITE;
|
|
11
33
|
const cipherSuite = await getCiphersuiteImpl(name, options?.cryptoProvider ?? nobleCryptoProvider);
|
|
@@ -33,8 +55,8 @@ export function makeMLSCredential(identity) {
|
|
|
33
55
|
};
|
|
34
56
|
}
|
|
35
57
|
/**
|
|
36
|
-
* Thrown by GroupHandle.processMessage
|
|
37
|
-
*
|
|
58
|
+
* Thrown by GroupHandle.processMessage when the active commit policy rejects
|
|
59
|
+
* an incoming commit. The handle is left at its pre-commit epoch.
|
|
38
60
|
*/ export class CommitRejectedError extends Error {
|
|
39
61
|
#proposals;
|
|
40
62
|
#senderLeafIndex;
|
|
@@ -70,24 +92,124 @@ export function makeMLSCredential(identity) {
|
|
|
70
92
|
return action;
|
|
71
93
|
};
|
|
72
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* Read the cleartext commit fields a PrivateMessage commit exposes before any
|
|
97
|
+
* epoch secret is available: its `authenticatedData` carrier. Returns undefined
|
|
98
|
+
* for anything that is not a PrivateMessage of contentType commit (application
|
|
99
|
+
* message, proposal, PublicMessage, or a pre-decoded non-frame) — those keep the
|
|
100
|
+
* pre-envelope code path. The decoded frame is widened to `unknown` on both
|
|
101
|
+
* public entry points, so this narrows structurally rather than by cast.
|
|
102
|
+
*/ function readPrivateCommit(decoded) {
|
|
103
|
+
if (decoded == null || typeof decoded !== 'object') return undefined;
|
|
104
|
+
const frame = decoded;
|
|
105
|
+
if (frame.wireformat !== wireformats.mls_private_message) return undefined;
|
|
106
|
+
const pm = frame.privateMessage;
|
|
107
|
+
if (pm == null || pm.contentType !== contentTypes.commit) return undefined;
|
|
108
|
+
const data = pm.authenticatedData;
|
|
109
|
+
return {
|
|
110
|
+
authenticatedData: data instanceof Uint8Array ? data : new Uint8Array()
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Read the DID an external-join commit proves control of. An external join is a
|
|
115
|
+
* PublicMessage whose sender is a joining non-member (senderType
|
|
116
|
+
* new_member_commit) carrying a commit; the committer holds no pre-commit leaf,
|
|
117
|
+
* so its DID rides the commit's own UpdatePath leaf credential. Returns undefined
|
|
118
|
+
* for anything that is not such a commit — those keep the pre-envelope path.
|
|
119
|
+
* Returns `{ did: undefined }` for an external commit whose UpdatePath is absent
|
|
120
|
+
* or whose leaf credential does not resolve to a basic-credential DID: it cannot
|
|
121
|
+
* be a valid resync, so the caller rejects it. Narrows the `unknown` frame
|
|
122
|
+
* structurally, mirroring readPrivateCommit / readMessageEpoch.
|
|
123
|
+
*/ function readExternalCommit(decoded) {
|
|
124
|
+
if (decoded == null || typeof decoded !== 'object') return undefined;
|
|
125
|
+
const frame = decoded;
|
|
126
|
+
if (frame.wireformat !== wireformats.mls_public_message) return undefined;
|
|
127
|
+
const pm = frame.publicMessage;
|
|
128
|
+
if (pm == null || pm.senderType !== senderTypes.new_member_commit) return undefined;
|
|
129
|
+
const content = pm.content;
|
|
130
|
+
if (content == null || content.contentType !== contentTypes.commit) return undefined;
|
|
131
|
+
const commit = content.commit;
|
|
132
|
+
const path = commit?.path;
|
|
133
|
+
if (path == null) return {
|
|
134
|
+
did: undefined
|
|
135
|
+
};
|
|
136
|
+
const leafNode = path.leafNode;
|
|
137
|
+
const credential = leafNode?.credential;
|
|
138
|
+
if (credential == null || !(credential.identity instanceof Uint8Array)) {
|
|
139
|
+
return {
|
|
140
|
+
did: undefined
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
return {
|
|
145
|
+
did: parseMLSCredentialIdentity(credential.identity).id
|
|
146
|
+
};
|
|
147
|
+
} catch {
|
|
148
|
+
return {
|
|
149
|
+
did: undefined
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Project a held ledger into the roster. foldRoster is the role projection: it
|
|
155
|
+
* drops every non-`group.role` entry by type, so the mixed-type ledger is fed in
|
|
156
|
+
* as role inputs and the fold filters. The log is replayed in order, repeats and
|
|
157
|
+
* all: a claim re-enacted at a later position must undo what came between.
|
|
158
|
+
*/ function foldLedgerRoster(ledger, anchor, groupID) {
|
|
159
|
+
const entries = ledger.map(({ verified, entryID })=>({
|
|
160
|
+
verified,
|
|
161
|
+
entryID
|
|
162
|
+
}));
|
|
163
|
+
return foldRoster(entries, anchor, groupID);
|
|
164
|
+
}
|
|
73
165
|
/**
|
|
74
166
|
* Mutable wrapper around MLS group state + Enkaku credential.
|
|
75
167
|
*/ export class GroupHandle {
|
|
76
168
|
#state;
|
|
77
169
|
#credential;
|
|
78
170
|
#context;
|
|
79
|
-
#rootCapability;
|
|
80
171
|
#cache;
|
|
81
172
|
#resolver;
|
|
82
173
|
#commitPolicy;
|
|
174
|
+
#resolveLedgerEntries;
|
|
175
|
+
#onLedgerEntries;
|
|
176
|
+
#anchor;
|
|
177
|
+
/** The ordered log of enactments — the ledger as the head chains it. The same
|
|
178
|
+
* content id may appear more than once: a claim re-enacted at a later position
|
|
179
|
+
* undoes what came between, which is how a demotion back to a previously-held
|
|
180
|
+
* role expresses itself at all. */ #ledger;
|
|
181
|
+
/** Entry bodies by content id, for resolving the ids an envelope names. A body
|
|
182
|
+
* is the same body wherever it appears in the log, so this store is keyed. */ #entryBodies;
|
|
183
|
+
#roster;
|
|
83
184
|
constructor(params){
|
|
84
185
|
this.#state = params.state;
|
|
85
186
|
this.#credential = params.credential;
|
|
86
187
|
this.#context = params.context;
|
|
87
|
-
this.#rootCapability = params.rootCapability;
|
|
88
188
|
this.#cache = params.cache;
|
|
89
189
|
this.#resolver = params.resolver;
|
|
90
190
|
this.#commitPolicy = params.commitPolicy;
|
|
191
|
+
this.#resolveLedgerEntries = params.resolveLedgerEntries;
|
|
192
|
+
this.#onLedgerEntries = params.onLedgerEntries;
|
|
193
|
+
// Seed the control state from the genesis anchor baked into the group's own
|
|
194
|
+
// GroupContext. The anchor survives every epoch, so reading it here makes the
|
|
195
|
+
// constructor the single choke that no anchorless handle can slip through: an
|
|
196
|
+
// absent anchor fails closed rather than installing a permissive roster.
|
|
197
|
+
const anchor = readGroupAnchor(this);
|
|
198
|
+
if (anchor == null) {
|
|
199
|
+
throw new Error('group has no anchor extension; cannot seed a control roster');
|
|
200
|
+
}
|
|
201
|
+
this.#anchor = anchor;
|
|
202
|
+
this.#ledger = [
|
|
203
|
+
...params.ledger ?? []
|
|
204
|
+
];
|
|
205
|
+
this.#entryBodies = new Map(this.#ledger.map(({ entryID, token, verified })=>[
|
|
206
|
+
entryID,
|
|
207
|
+
{
|
|
208
|
+
token,
|
|
209
|
+
verified
|
|
210
|
+
}
|
|
211
|
+
]));
|
|
212
|
+
this.#roster = foldLedgerRoster(this.#ledger, anchor, this.groupID);
|
|
91
213
|
}
|
|
92
214
|
get groupID() {
|
|
93
215
|
return this.#credential.groupID;
|
|
@@ -104,9 +226,6 @@ export function makeMLSCredential(identity) {
|
|
|
104
226
|
get state() {
|
|
105
227
|
return this.#state;
|
|
106
228
|
}
|
|
107
|
-
get rootCapability() {
|
|
108
|
-
return this.#rootCapability;
|
|
109
|
-
}
|
|
110
229
|
get context() {
|
|
111
230
|
return this.#context;
|
|
112
231
|
}
|
|
@@ -116,10 +235,66 @@ export function makeMLSCredential(identity) {
|
|
|
116
235
|
get resolver() {
|
|
117
236
|
return this.#resolver;
|
|
118
237
|
}
|
|
119
|
-
/** The commit policy enforced by processMessage
|
|
120
|
-
*
|
|
238
|
+
/** The commit policy enforced by processMessage, if any. Carried onto
|
|
239
|
+
* handles derived from this one (commitInvite/removeMember). */ get commitPolicy() {
|
|
121
240
|
return this.#commitPolicy;
|
|
122
241
|
}
|
|
242
|
+
/** The ledger-entry resolver, carried onto handles derived from this one. */ get resolveLedgerEntries() {
|
|
243
|
+
return this.#resolveLedgerEntries;
|
|
244
|
+
}
|
|
245
|
+
/** The accepted-commit entry sink, carried onto handles derived from this one. */ get onLedgerEntries() {
|
|
246
|
+
return this.#onLedgerEntries;
|
|
247
|
+
}
|
|
248
|
+
/** The genesis anchor seeded into this handle at construction. */ get anchor() {
|
|
249
|
+
return this.#anchor;
|
|
250
|
+
}
|
|
251
|
+
/** The control-ledger log this handle holds, in enactment order, repeats and
|
|
252
|
+
* all. Carried onto handles derived from this one (commitInvite/removeMember). */ get ledger() {
|
|
253
|
+
return this.#ledger;
|
|
254
|
+
}
|
|
255
|
+
/** The ordered signed tokens this handle holds, including repeats — the ledger's
|
|
256
|
+
* canonical persistent and wire form, and the list the authenticated head folds
|
|
257
|
+
* over. Feeds createInvite, restoreGroup, and host persistence. The verified
|
|
258
|
+
* entries are a derived cache with no export form: the only way into a ledger is
|
|
259
|
+
* applyLedgerEntries, which re-verifies. */ get ledgerTokens() {
|
|
260
|
+
return this.#ledger.map(({ token })=>token);
|
|
261
|
+
}
|
|
262
|
+
/** The control roster folded from the anchor and every applied ledger entry. */ get roster() {
|
|
263
|
+
return this.#roster;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Verify signed ledger tokens, append the valid ones to the log in the order
|
|
267
|
+
* given, and refold the roster. Tokens that fail verification or whose groupID
|
|
268
|
+
* does not match the group are dropped (defensive — this is the low-level apply
|
|
269
|
+
* primitive; the commit pre-pass does the strict admin-issuer enforcement).
|
|
270
|
+
* Every token is re-verified on the way in: no entry enters a ledger unverified,
|
|
271
|
+
* whatever the import path.
|
|
272
|
+
*
|
|
273
|
+
* A token the log already holds is appended again rather than skipped. The log
|
|
274
|
+
* is an ordered record of what each commit enacted, not a set of claims, and a
|
|
275
|
+
* repeat is the only way to express a demotion back to a previously-held role.
|
|
276
|
+
* Nothing replays a commit into it: MLS applies each commit exactly once,
|
|
277
|
+
* restoreGroup replays a token list once, and processWelcome folds an invite once.
|
|
278
|
+
* Runs serialized on the handle's mutex, like the other state-mutating operations.
|
|
279
|
+
*/ async applyLedgerEntries(tokens) {
|
|
280
|
+
return mutexFor(this).run(async ()=>{
|
|
281
|
+
for (const token of tokens){
|
|
282
|
+
const verified = await verifyLedgerEntry(token);
|
|
283
|
+
if (verified == null || verified.entry.groupID !== this.groupID) continue;
|
|
284
|
+
const entryID = ledgerEntryDigest(token);
|
|
285
|
+
this.#ledger.push({
|
|
286
|
+
entryID,
|
|
287
|
+
token,
|
|
288
|
+
verified
|
|
289
|
+
});
|
|
290
|
+
this.#entryBodies.set(entryID, {
|
|
291
|
+
token,
|
|
292
|
+
verified
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
this.#roster = foldLedgerRoster(this.#ledger, this.#anchor, this.groupID);
|
|
296
|
+
});
|
|
297
|
+
}
|
|
123
298
|
get memberCount() {
|
|
124
299
|
return this.#state.ratchetTree.filter((node)=>node != null && node.nodeType === nodeTypes.leaf).length;
|
|
125
300
|
}
|
|
@@ -162,58 +337,170 @@ export function makeMLSCredential(identity) {
|
|
|
162
337
|
];
|
|
163
338
|
}
|
|
164
339
|
/**
|
|
165
|
-
* Encrypt an application message for the group.
|
|
340
|
+
* Encrypt an application message for the group, returning framed wire bytes.
|
|
341
|
+
* Encrypts at this handle's current epoch. A handle a commit has already
|
|
342
|
+
* superseded (see {@link commitInvite}, {@link removeMember},
|
|
343
|
+
* {@link commitLedgerEntries}) must not be reused to send — doing so silently
|
|
344
|
+
* emits an application message at the now-stale epoch; adopt the commit's
|
|
345
|
+
* `newGroup` and call `encrypt` on that instead.
|
|
166
346
|
*/ async encrypt(plaintext) {
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
347
|
+
return mutexFor(this).run(async ()=>{
|
|
348
|
+
const { newState, message, consumed } = await createApplicationMessage({
|
|
349
|
+
context: this.#context,
|
|
350
|
+
state: this.#state,
|
|
351
|
+
message: plaintext
|
|
352
|
+
});
|
|
353
|
+
this.#state = newState;
|
|
354
|
+
zeroAll(consumed);
|
|
355
|
+
return encode(mlsMessageEncoder, message);
|
|
171
356
|
});
|
|
172
|
-
this.#state = newState;
|
|
173
|
-
return {
|
|
174
|
-
message,
|
|
175
|
-
consumed
|
|
176
|
-
};
|
|
177
357
|
}
|
|
178
358
|
/**
|
|
179
|
-
*
|
|
359
|
+
* The async pre-pass feeding the synchronous ts-mls commit callback.
|
|
360
|
+
* processMessage runs this before mlsProcessMessage, since it may receive a
|
|
361
|
+
* commit. For anything that is not a PrivateMessage commit (application
|
|
362
|
+
* message, proposal, PublicMessage, pre-decoded non-frame) it does
|
|
363
|
+
* exactly what the code did before this step — resolve the caller policy, wrap
|
|
364
|
+
* it for the rejected-proposal capture, and apply nothing on accept.
|
|
180
365
|
*
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
-
*
|
|
184
|
-
*
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
if (parsed == null) {
|
|
192
|
-
throw new Error('decrypt: failed to decode MLSMessage');
|
|
193
|
-
}
|
|
194
|
-
decoded = parsed;
|
|
195
|
-
}
|
|
196
|
-
const callback = opts?.commitPolicy ?? this.#commitPolicy;
|
|
366
|
+
* For a PrivateMessage commit it decodes the control envelope, resolves and
|
|
367
|
+
* verifies the entry bodies the envelope names, folds a candidate roster off
|
|
368
|
+
* the pre-commit state, and precomputes the pure inputs the sync callback
|
|
369
|
+
* reads. The returned callback is a pure lookup over that precomputed state:
|
|
370
|
+
* a decode/fold failure is a hard reject; otherwise a caller policy wins the
|
|
371
|
+
* permission decision, and with no caller policy the anchored default policy
|
|
372
|
+
* runs. Missing entry bodies with no resolver throw MissingLedgerEntriesError
|
|
373
|
+
* here — before mlsProcessMessage — so the handle stays at its pre-commit epoch.
|
|
374
|
+
*/ async #prepareCommitPipeline(decoded, opts) {
|
|
375
|
+
const callerPolicy = opts?.commitPolicy ?? this.#commitPolicy;
|
|
197
376
|
const capture = {};
|
|
198
|
-
const
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
377
|
+
const commit = readPrivateCommit(decoded);
|
|
378
|
+
let externalCommitDID;
|
|
379
|
+
let isCommitMessage = commit != null;
|
|
380
|
+
if (commit == null) {
|
|
381
|
+
const external = readExternalCommit(decoded);
|
|
382
|
+
if (external != null) {
|
|
383
|
+
externalCommitDID = external.did;
|
|
384
|
+
isCommitMessage = true;
|
|
205
385
|
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
386
|
+
// else: a standalone by-reference Proposal (or an application message / a
|
|
387
|
+
// frame ts-mls will not call back on). Fall through with the roster
|
|
388
|
+
// unchanged so `combined` judges a kind:'proposal' incoming under the same
|
|
389
|
+
// defaultCommitPolicy rows a receiver applies to a commit's proposals; a
|
|
390
|
+
// non-admin's authority-bearing proposal is rejected on receipt and never
|
|
391
|
+
// stored. Application messages never reach the callback, so this is inert
|
|
392
|
+
// for them.
|
|
210
393
|
}
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
394
|
+
let precomputedReject = false;
|
|
395
|
+
let candidateRoster = this.#roster;
|
|
396
|
+
let surfaced = [];
|
|
397
|
+
let acceptedEntries = [];
|
|
398
|
+
let envelopeIDs = [];
|
|
399
|
+
if (isCommitMessage) {
|
|
400
|
+
if (commit == null) {
|
|
401
|
+
// An external-join commit carries no control envelope: it resolves nothing,
|
|
402
|
+
// folds nothing, enacts no ledger entries, and never moves the head. The
|
|
403
|
+
// candidate roster is the current roster unchanged. Its only precomputed
|
|
404
|
+
// reject is an unresolvable committer DID (no UpdatePath / bad credential),
|
|
405
|
+
// which cannot be a valid resync.
|
|
406
|
+
precomputedReject = externalCommitDID === undefined;
|
|
407
|
+
} else {
|
|
408
|
+
const env = decodeControlEnvelope(commit.authenticatedData);
|
|
409
|
+
if (!env.ok) {
|
|
410
|
+
precomputedReject = true;
|
|
411
|
+
} else {
|
|
412
|
+
const ids = env.envelope.entries ?? [];
|
|
413
|
+
envelopeIDs = ids;
|
|
414
|
+
const resolved = new Map();
|
|
415
|
+
const missing = [];
|
|
416
|
+
for (const id of ids){
|
|
417
|
+
const held = this.#entryBodies.get(id);
|
|
418
|
+
if (held != null) {
|
|
419
|
+
resolved.set(id, {
|
|
420
|
+
...held,
|
|
421
|
+
entryID: id
|
|
422
|
+
});
|
|
423
|
+
} else {
|
|
424
|
+
missing.push(id);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
if (missing.length > 0) {
|
|
428
|
+
if (this.#resolveLedgerEntries == null) {
|
|
429
|
+
throw new MissingLedgerEntriesError(missing);
|
|
430
|
+
}
|
|
431
|
+
const tokens = await this.#resolveLedgerEntries(missing);
|
|
432
|
+
for (const token of tokens){
|
|
433
|
+
const id = ledgerEntryDigest(token);
|
|
434
|
+
// Content-addressing binds the untrusted body to the requested id.
|
|
435
|
+
if (resolved.has(id) || !missing.includes(id)) continue;
|
|
436
|
+
const verified = await verifyLedgerEntry(token);
|
|
437
|
+
if (verified == null) continue;
|
|
438
|
+
resolved.set(id, {
|
|
439
|
+
token,
|
|
440
|
+
verified,
|
|
441
|
+
entryID: id
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
const stillMissing = missing.filter((id)=>!resolved.has(id));
|
|
445
|
+
if (stillMissing.length > 0) {
|
|
446
|
+
throw new MissingLedgerEntriesError(stillMissing);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
const ordered = ids.map((id)=>{
|
|
450
|
+
const input = resolved.get(id);
|
|
451
|
+
if (input == null) throw new MissingLedgerEntriesError([
|
|
452
|
+
id
|
|
453
|
+
]);
|
|
454
|
+
return input;
|
|
455
|
+
});
|
|
456
|
+
const foldResult = foldEnvelope(this.#roster, ordered, this.groupID);
|
|
457
|
+
if (!foldResult.ok) {
|
|
458
|
+
precomputedReject = true;
|
|
459
|
+
} else {
|
|
460
|
+
candidateRoster = foldResult.roster;
|
|
461
|
+
surfaced = foldResult.surfaced;
|
|
462
|
+
acceptedEntries = ordered;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}
|
|
215
466
|
}
|
|
216
|
-
|
|
467
|
+
const context = buildCommitPolicyContext(this, {
|
|
468
|
+
baseRoster: this.#roster,
|
|
469
|
+
candidateRoster,
|
|
470
|
+
entryIDs: envelopeIDs,
|
|
471
|
+
...externalCommitDID !== undefined && {
|
|
472
|
+
externalCommitDID
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
const combined = (incoming)=>{
|
|
476
|
+
// A decode/fold failure is a hard reject even under a caller policy: the
|
|
477
|
+
// ledger the commit depends on is unresolvable or malformed.
|
|
478
|
+
if (precomputedReject) return 'reject';
|
|
479
|
+
if (callerPolicy != null) return callerPolicy(incoming);
|
|
480
|
+
return defaultCommitPolicy(incoming, context);
|
|
481
|
+
};
|
|
482
|
+
const applyOnAccept = ()=>{
|
|
483
|
+
// Appended, never deduped: the log records what this commit enacted, at the
|
|
484
|
+
// position the head chained it.
|
|
485
|
+
for (const { token, verified, entryID } of acceptedEntries){
|
|
486
|
+
this.#ledger.push({
|
|
487
|
+
entryID,
|
|
488
|
+
token,
|
|
489
|
+
verified
|
|
490
|
+
});
|
|
491
|
+
this.#entryBodies.set(entryID, {
|
|
492
|
+
token,
|
|
493
|
+
verified
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
this.#roster = candidateRoster;
|
|
497
|
+
if (surfaced.length > 0) this.#onLedgerEntries?.(surfaced);
|
|
498
|
+
};
|
|
499
|
+
return {
|
|
500
|
+
callback: wrapCommitPolicy(combined, capture),
|
|
501
|
+
capture,
|
|
502
|
+
applyOnAccept
|
|
503
|
+
};
|
|
217
504
|
}
|
|
218
505
|
/**
|
|
219
506
|
* Process a received MLS message (Commit, Proposal, or application).
|
|
@@ -232,26 +519,27 @@ export function makeMLSCredential(identity) {
|
|
|
232
519
|
}
|
|
233
520
|
decoded = parsed;
|
|
234
521
|
}
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
522
|
+
return mutexFor(this).run(async ()=>{
|
|
523
|
+
const { callback, capture, applyOnAccept } = await this.#prepareCommitPipeline(decoded, opts);
|
|
524
|
+
const result = await mlsProcessMessage({
|
|
525
|
+
context: this.#context,
|
|
526
|
+
state: this.#state,
|
|
527
|
+
message: decoded,
|
|
528
|
+
...callback != null && {
|
|
529
|
+
callback
|
|
530
|
+
}
|
|
531
|
+
});
|
|
532
|
+
this.#state = result.newState;
|
|
533
|
+
zeroAll(result.consumed);
|
|
534
|
+
if (result.kind === 'newState' && result.actionTaken === 'reject') {
|
|
535
|
+
throw new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex);
|
|
244
536
|
}
|
|
537
|
+
if (result.kind === 'applicationMessage') {
|
|
538
|
+
return result.message;
|
|
539
|
+
}
|
|
540
|
+
applyOnAccept();
|
|
541
|
+
return null;
|
|
245
542
|
});
|
|
246
|
-
// On reject, ts-mls returns the pre-commit state, so the handle stays put.
|
|
247
|
-
this.#state = result.newState;
|
|
248
|
-
if (result.kind === 'newState' && result.actionTaken === 'reject') {
|
|
249
|
-
throw new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex);
|
|
250
|
-
}
|
|
251
|
-
if (result.kind === 'applicationMessage') {
|
|
252
|
-
return result.message;
|
|
253
|
-
}
|
|
254
|
-
return null;
|
|
255
543
|
}
|
|
256
544
|
}
|
|
257
545
|
// ---------------------------------------------------------------------------
|
|
@@ -286,7 +574,29 @@ export function makeMLSCredential(identity) {
|
|
|
286
574
|
*/ export async function createGroup(identity, groupID, options) {
|
|
287
575
|
const cache = options?.cache ?? createInMemoryDIDCache();
|
|
288
576
|
const context = await resolveMlsContext(options);
|
|
289
|
-
|
|
577
|
+
// Every group is anchored at creation: the creator is the epoch-0 admin, and
|
|
578
|
+
// the ledger head starts at genesis. A caller-supplied anchor (e.g. one
|
|
579
|
+
// carrying an `app` payload) is left untouched — the caller owns its contents.
|
|
580
|
+
// Its `creatorDID` coupling to the creating identity is validated below; a
|
|
581
|
+
// decode failure here is not this guard's concern and is left to the
|
|
582
|
+
// downstream fail-closed decode in the GroupHandle constructor.
|
|
583
|
+
const extensions = [
|
|
584
|
+
...options?.extensions ?? []
|
|
585
|
+
];
|
|
586
|
+
const suppliedAnchorExtension = extensions.find((ext)=>ext.extensionType === GROUP_ANCHOR_EXTENSION_TYPE);
|
|
587
|
+
if (suppliedAnchorExtension != null) {
|
|
588
|
+
const suppliedAnchorData = suppliedAnchorExtension.extensionData;
|
|
589
|
+
const suppliedAnchor = suppliedAnchorData instanceof Uint8Array ? decodeGroupAnchor(suppliedAnchorData) : null;
|
|
590
|
+
if (suppliedAnchor != null && normalizeDID(suppliedAnchor.creatorDID) !== normalizeDID(identity.id)) {
|
|
591
|
+
throw new Error(`createGroup: the anchor's creatorDID (${suppliedAnchor.creatorDID}) must be the creating identity (${identity.id})`);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
if (!extensions.some((ext)=>ext.extensionType === GROUP_ANCHOR_EXTENSION_TYPE)) {
|
|
595
|
+
extensions.push(buildCurrentGroupAnchorExtension(identity.id));
|
|
596
|
+
}
|
|
597
|
+
if (!extensions.some((ext)=>ext.extensionType === LEDGER_HEAD_EXTENSION_TYPE)) {
|
|
598
|
+
extensions.push(buildLedgerHeadExtension(genesisHead(groupID)));
|
|
599
|
+
}
|
|
290
600
|
const statePromise = generateKeyPackageWithKey({
|
|
291
601
|
credential: makeMLSCredential(identity),
|
|
292
602
|
signatureKeyPair: {
|
|
@@ -304,28 +614,20 @@ export function makeMLSCredential(identity) {
|
|
|
304
614
|
extensions
|
|
305
615
|
});
|
|
306
616
|
});
|
|
307
|
-
const
|
|
308
|
-
statePromise,
|
|
309
|
-
createGroupCapability(identity, groupID)
|
|
310
|
-
]);
|
|
311
|
-
const rootCapability = stringifyToken(rootCap);
|
|
617
|
+
const state = await statePromise;
|
|
312
618
|
const credential = {
|
|
313
619
|
id: identity.id,
|
|
314
|
-
capabilityChain: [
|
|
315
|
-
rootCapability
|
|
316
|
-
],
|
|
317
|
-
capability: rootCap,
|
|
318
|
-
permission: 'admin',
|
|
319
620
|
groupID
|
|
320
621
|
};
|
|
321
622
|
const group = new GroupHandle({
|
|
322
623
|
state,
|
|
323
624
|
credential,
|
|
324
625
|
context,
|
|
325
|
-
rootCapability,
|
|
326
626
|
cache,
|
|
327
627
|
resolver: options?.resolver,
|
|
328
|
-
commitPolicy: options?.commitPolicy
|
|
628
|
+
commitPolicy: options?.commitPolicy,
|
|
629
|
+
resolveLedgerEntries: options?.resolveLedgerEntries,
|
|
630
|
+
onLedgerEntries: options?.onLedgerEntries
|
|
329
631
|
});
|
|
330
632
|
return {
|
|
331
633
|
group,
|
|
@@ -334,79 +636,303 @@ export function makeMLSCredential(identity) {
|
|
|
334
636
|
}
|
|
335
637
|
export async function restoreGroup(params) {
|
|
336
638
|
const cache = params.options?.cache ?? createInMemoryDIDCache();
|
|
337
|
-
|
|
639
|
+
// Construction reseeds `{creator: 'admin'}` from the anchor in the restored
|
|
640
|
+
// state — an anchorless state throws here, the same fail-closed guard.
|
|
641
|
+
const group = new GroupHandle({
|
|
338
642
|
state: params.state,
|
|
339
643
|
credential: params.credential,
|
|
340
644
|
context: await resolveMlsContext(params.options),
|
|
341
|
-
rootCapability: params.rootCapability,
|
|
342
645
|
cache,
|
|
343
646
|
resolver: params.options?.resolver,
|
|
344
|
-
commitPolicy: params.options?.commitPolicy
|
|
647
|
+
commitPolicy: params.options?.commitPolicy,
|
|
648
|
+
resolveLedgerEntries: params.options?.resolveLedgerEntries,
|
|
649
|
+
onLedgerEntries: params.options?.onLedgerEntries
|
|
345
650
|
});
|
|
651
|
+
await group.applyLedgerEntries(params.ledgerEntries ?? []);
|
|
652
|
+
return group;
|
|
346
653
|
}
|
|
347
654
|
/**
|
|
348
655
|
* Create an invite for a new member.
|
|
349
656
|
* Does NOT add them to the group — call commitInvite with their key package to do that.
|
|
657
|
+
*
|
|
658
|
+
* Only an admin may invite: a role entry from a non-admin issuer is dropped by every
|
|
659
|
+
* receiver's fold, so refusing here turns a silent downstream commit rejection into a
|
|
660
|
+
* local error.
|
|
350
661
|
*/ export async function createInvite(params) {
|
|
351
662
|
const { group, identity, recipientDID, permission } = params;
|
|
352
|
-
|
|
353
|
-
|
|
663
|
+
if (group.roster.roles.get(normalizeDID(identity.id)) !== 'admin') {
|
|
664
|
+
throw new Error('createInvite: the inviter must be an admin in the group roster');
|
|
665
|
+
}
|
|
666
|
+
// The role entry naming the invitee. Its issuer is the inviter (authenticated by
|
|
667
|
+
// the token signature) and its value is the permission granted.
|
|
668
|
+
const roleToken = await signLedgerEntry(identity, {
|
|
669
|
+
type: ROLE_ENTRY_TYPE,
|
|
354
670
|
groupID: group.groupID,
|
|
355
|
-
recipientDID,
|
|
356
|
-
permission
|
|
357
|
-
parentCapability: group.rootCapability
|
|
671
|
+
subject: recipientDID,
|
|
672
|
+
value: permission
|
|
358
673
|
});
|
|
359
|
-
const memberCapStr = stringifyToken(memberCap);
|
|
360
674
|
const invite = {
|
|
361
675
|
groupID: group.groupID,
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
676
|
+
inviterID: identity.id,
|
|
677
|
+
// The whole log, the new role entry last: a joiner handed only its own entry
|
|
678
|
+
// would never learn of a role change made before its invite, and would reject
|
|
679
|
+
// every commit by an admin promoted in the meantime — a permanent fork nothing
|
|
680
|
+
// in the protocol re-sends. The new entry must fold after the history it depends
|
|
681
|
+
// on, hence last. Re-granting a role the log already carries appends that entry a
|
|
682
|
+
// second time, which is a legal re-enactment, not a duplicate to elide. The joiner
|
|
683
|
+
// still folds from the anchor, so the inviter cannot promote anyone by padding
|
|
684
|
+
// this list.
|
|
685
|
+
ledgerEntries: [
|
|
686
|
+
...group.ledgerTokens,
|
|
687
|
+
roleToken
|
|
688
|
+
]
|
|
369
689
|
};
|
|
370
690
|
return {
|
|
371
691
|
invite
|
|
372
692
|
};
|
|
373
693
|
}
|
|
374
694
|
/**
|
|
375
|
-
*
|
|
376
|
-
*
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
695
|
+
* The GroupContext extension list a commit installs when it enacts `entryIDs`: the
|
|
696
|
+
* group's current list with only the ledger-head extension replaced by the head
|
|
697
|
+
* extended by those ids, in envelope order. Every other extension — the anchor above
|
|
698
|
+
* all — is the verbatim object out of the current GroupContext, never a re-encode of
|
|
699
|
+
* a decoded value, because the receiving policy byte-compares the anchor.
|
|
700
|
+
*/ function extensionsWithHead(group, entryIDs) {
|
|
701
|
+
const current = readLedgerHead(group);
|
|
702
|
+
if (current == null) {
|
|
703
|
+
throw new Error('group has no ledger head extension; it cannot enact ledger entries');
|
|
704
|
+
}
|
|
705
|
+
const next = buildLedgerHeadExtension(extendHead(current.head, entryIDs));
|
|
706
|
+
return group.state.groupContext.extensions.map((ext)=>ext.extensionType === LEDGER_HEAD_EXTENSION_TYPE ? next : ext);
|
|
707
|
+
}
|
|
708
|
+
/** Build the CommitPolicyContext both the receive gate and the send-side pending
|
|
709
|
+
* filter judge against, so the two always agree. `entryIDs` are the ledger entry
|
|
710
|
+
* ids this commit enacts (drives the expected head); `candidateRoster` is the
|
|
711
|
+
* post-fold roster receivers install. */ function buildCommitPolicyContext(handle, args) {
|
|
712
|
+
const leafToDID = new Map();
|
|
713
|
+
for (const member of handle.listMembers())leafToDID.set(member.leafIndex, member.id);
|
|
714
|
+
const headExt = readLedgerHeadExtension(handle);
|
|
715
|
+
const currentHead = headExt != null && headExt.extensionData instanceof Uint8Array ? decodeLedgerHead(headExt.extensionData) : null;
|
|
716
|
+
const expectedHeadExtensionData = currentHead == null ? new Uint8Array() : encodeLedgerHead(extendHead(currentHead.head, args.entryIDs));
|
|
717
|
+
return {
|
|
718
|
+
baseRoster: args.baseRoster,
|
|
719
|
+
candidateRoster: args.candidateRoster,
|
|
720
|
+
didOfLeaf: (leafIndex)=>leafToDID.get(leafIndex),
|
|
721
|
+
currentExtensions: handle.state.groupContext.extensions,
|
|
722
|
+
expectedHeadExtensionData,
|
|
723
|
+
commitEnactsEntries: args.entryIDs.length > 0,
|
|
724
|
+
...args.externalCommitDID !== undefined && {
|
|
725
|
+
externalCommitDID: args.externalCommitDID
|
|
382
726
|
}
|
|
383
727
|
};
|
|
384
|
-
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* The one place a commit carrying control-ledger entries is built: `commitInvite`,
|
|
731
|
+
* `removeMember`, and `commitLedgerEntries` all route through it, so the envelope and
|
|
732
|
+
* the head can never drift apart.
|
|
733
|
+
*
|
|
734
|
+
* `enacted` is exactly what this commit enacts — the caller decides, and the caller is
|
|
735
|
+
* the only one that can: entries are enacted by *position* in the log, so an entry whose
|
|
736
|
+
* content the log already carries is a legitimate re-enactment (a demotion back to a
|
|
737
|
+
* previously-held role is precisely that) and must not be filtered out by content.
|
|
738
|
+
*
|
|
739
|
+
* The envelope names only what this commit enacts, never the whole history: replaying the
|
|
740
|
+
* history would re-judge every past entry against the present roster, and a grant issued
|
|
741
|
+
* by a since-demoted admin would read as coming from a non-admin, freezing every group
|
|
742
|
+
* that ever rotated its admins.
|
|
743
|
+
*
|
|
744
|
+
* When `enacted` is non-empty the commit also carries a group-context-extensions proposal
|
|
745
|
+
* advancing the ledger head by exactly those ids, in envelope order. An empty list moves
|
|
746
|
+
* no head and carries no envelope.
|
|
747
|
+
*/ async function commitWithEntries(group, extraProposals, enacted, ratchetTreeExtension = false) {
|
|
748
|
+
// Same reason createInvite guards the inviter: a non-admin's commit is rejected by
|
|
749
|
+
// every receiver, so fail here rather than emitting a commit nobody will apply.
|
|
750
|
+
if (group.roster.roles.get(normalizeDID(group.credential.id)) !== 'admin') {
|
|
751
|
+
throw new Error('the committer must be an admin in the group roster');
|
|
752
|
+
}
|
|
753
|
+
// Fold the entries exactly as every receiver will, and refuse to author a commit the
|
|
754
|
+
// group would reject. Without this the write path fails *open*: the committer advances
|
|
755
|
+
// its own log and head while every receiver rejects the commit, forking itself off the
|
|
756
|
+
// group. Being an admin is not enough — an entry's own issuer must still hold authority
|
|
757
|
+
// at the position it lands in, so a token signed by a since-demoted admin is dead paper
|
|
758
|
+
// no matter who commits it.
|
|
759
|
+
const inputs = [];
|
|
760
|
+
for (const token of enacted){
|
|
761
|
+
const verified = await verifyLedgerEntry(token);
|
|
762
|
+
if (verified == null) {
|
|
763
|
+
throw new Error('cannot enact a ledger entry whose signature does not verify');
|
|
764
|
+
}
|
|
765
|
+
inputs.push({
|
|
766
|
+
verified,
|
|
767
|
+
entryID: ledgerEntryDigest(token)
|
|
768
|
+
});
|
|
769
|
+
}
|
|
770
|
+
const fold = foldEnvelope(group.roster, inputs, group.groupID);
|
|
771
|
+
if (!fold.ok) {
|
|
772
|
+
throw new Error(`cannot enact ledger entry ${fold.entryID}: ${fold.reason}`);
|
|
773
|
+
}
|
|
774
|
+
const entryIDs = enacted.map(ledgerEntryDigest);
|
|
775
|
+
// Filter the pending-proposal set the committer would otherwise absorb: ts-mls folds every
|
|
776
|
+
// unappliedProposal into the commit, so a non-admin's pending proposal would ride this commit
|
|
777
|
+
// and every peer would reject the whole thing — a single member could stall the group. Judge
|
|
778
|
+
// each pending proposal against the same defaultCommitPolicy and the same context receivers
|
|
779
|
+
// build for this commit, dropping any the group would reject.
|
|
780
|
+
const filterContext = buildCommitPolicyContext(group, {
|
|
781
|
+
baseRoster: group.roster,
|
|
782
|
+
candidateRoster: fold.roster,
|
|
783
|
+
entryIDs
|
|
784
|
+
});
|
|
785
|
+
const keptPending = {};
|
|
786
|
+
for (const [ref, pws] of Object.entries(group.state.unappliedProposals)){
|
|
787
|
+
if (defaultCommitPolicy({
|
|
788
|
+
kind: 'proposal',
|
|
789
|
+
proposal: pws
|
|
790
|
+
}, filterContext) !== 'reject') {
|
|
791
|
+
keptPending[ref] = pws;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
const commitState = {
|
|
795
|
+
...group.state,
|
|
796
|
+
unappliedProposals: keptPending
|
|
797
|
+
};
|
|
798
|
+
const proposals = [
|
|
799
|
+
...extraProposals
|
|
800
|
+
];
|
|
801
|
+
if (entryIDs.length > 0) {
|
|
802
|
+
proposals.push({
|
|
803
|
+
proposalType: defaultProposalTypes.group_context_extensions,
|
|
804
|
+
groupContextExtensions: {
|
|
805
|
+
extensions: extensionsWithHead(group, entryIDs)
|
|
806
|
+
}
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
return await createCommit({
|
|
385
810
|
context: group.context,
|
|
386
|
-
state:
|
|
387
|
-
extraProposals:
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
811
|
+
state: commitState,
|
|
812
|
+
extraProposals: proposals,
|
|
813
|
+
...ratchetTreeExtension && {
|
|
814
|
+
ratchetTreeExtension: true
|
|
815
|
+
},
|
|
816
|
+
...entryIDs.length > 0 && {
|
|
817
|
+
authenticatedData: encodeControlEnvelope({
|
|
818
|
+
v: 1,
|
|
819
|
+
entries: entryIDs
|
|
820
|
+
})
|
|
821
|
+
}
|
|
391
822
|
});
|
|
392
|
-
|
|
393
|
-
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* The entries an invite adds beyond the committer's own log: everything past the log's
|
|
826
|
+
* length. Positional, never by content — a re-granted role is the same token the log
|
|
827
|
+
* already carries at an earlier position, and narrowing by content would drop the very
|
|
828
|
+
* entry the invite exists to enact.
|
|
829
|
+
*
|
|
830
|
+
* Positional narrowing is only sound when the invite's list *begins with* the
|
|
831
|
+
* committer's log, so that is asserted rather than assumed: an invite built against a
|
|
832
|
+
* different history would mis-slice, and the commit would move the head by ids that do
|
|
833
|
+
* not follow the group's own — corrupting the chain for every receiver.
|
|
834
|
+
*/ function entriesAddedByInvite(group, invite) {
|
|
835
|
+
const held = group.ledgerTokens;
|
|
836
|
+
if (invite.ledgerEntries.length < held.length || held.some((token, index)=>invite.ledgerEntries[index] !== token)) {
|
|
837
|
+
throw new Error("commitInvite: the invite's ledger does not extend this group's own");
|
|
838
|
+
}
|
|
839
|
+
return invite.ledgerEntries.slice(held.length);
|
|
840
|
+
}
|
|
841
|
+
/** Build the handle a commit hands back: the post-commit state, everything else inherited. */ function deriveGroup(group, state) {
|
|
842
|
+
return new GroupHandle({
|
|
843
|
+
state,
|
|
394
844
|
credential: group.credential,
|
|
395
845
|
context: group.context,
|
|
396
|
-
|
|
846
|
+
ledger: group.ledger,
|
|
397
847
|
cache: group.cache,
|
|
398
848
|
resolver: group.resolver,
|
|
399
|
-
commitPolicy: group.commitPolicy
|
|
849
|
+
commitPolicy: group.commitPolicy,
|
|
850
|
+
resolveLedgerEntries: group.resolveLedgerEntries,
|
|
851
|
+
onLedgerEntries: group.onLedgerEntries
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* The admin write path for the control ledger: a commit that carries no membership
|
|
856
|
+
* proposal, only the entries it enacts and the head move that covers them. This is how
|
|
857
|
+
* an admin promotes, demotes, or writes any other entry type — an entry that never
|
|
858
|
+
* rides a commit is invisible to the head, and a joiner recomputing the head would
|
|
859
|
+
* read the group's history as doctored.
|
|
860
|
+
*
|
|
861
|
+
* Enacts exactly `tokens`, at the end of the log — including one whose content the log
|
|
862
|
+
* already carries, which is how an admin is demoted back to a role they previously held.
|
|
863
|
+
* Rejects an empty `tokens` list: a commit that enacts nothing has no reason to be
|
|
864
|
+
* authored here.
|
|
865
|
+
*
|
|
866
|
+
* Reads `group`'s state and returns a NEW derived handle (`newGroup`); it never
|
|
867
|
+
* advances `group` itself. The caller must adopt `newGroup` — never reuse `group` —
|
|
868
|
+
* before issuing the next commit: two commits issued from the same source handle
|
|
869
|
+
* both frame at that handle's epoch and diverge. The per-handle mutex only
|
|
870
|
+
* serializes concurrent calls against one handle; it does not make it safe to
|
|
871
|
+
* produce a second commit from a handle a prior commit has already superseded.
|
|
872
|
+
*/ export async function commitLedgerEntries(group, tokens) {
|
|
873
|
+
return mutexFor(group).run(async ()=>{
|
|
874
|
+
if (tokens.length === 0) {
|
|
875
|
+
throw new Error('commitLedgerEntries: no ledger entries to commit');
|
|
876
|
+
}
|
|
877
|
+
const result = await commitWithEntries(group, [], tokens);
|
|
878
|
+
const newGroup = deriveGroup(group, result.newState);
|
|
879
|
+
await newGroup.applyLedgerEntries(tokens);
|
|
880
|
+
return {
|
|
881
|
+
commitMessage: encode(mlsMessageEncoder, result.commit),
|
|
882
|
+
newGroup,
|
|
883
|
+
epoch: newGroup.epoch
|
|
884
|
+
};
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
/**
|
|
888
|
+
* Commit an invite by adding the invitee's key package to the group.
|
|
889
|
+
* Produces an MLS Commit + Welcome.
|
|
890
|
+
*
|
|
891
|
+
* The invite's ledger entries are enacted by this commit: their content ids ride in
|
|
892
|
+
* the commit's control envelope and the commit advances the ledger head by exactly
|
|
893
|
+
* those ids, so every receiver folds the invitee's role entry into its roster as it
|
|
894
|
+
* applies the Add. The envelope carries ids, not bodies — a receiver that holds
|
|
895
|
+
* neither the entry nor a `resolveLedgerEntries` resolver throws
|
|
896
|
+
* MissingLedgerEntriesError on this commit.
|
|
897
|
+
*
|
|
898
|
+
* The invite itself carries the group's whole history — a joiner has nothing to fold
|
|
899
|
+
* it onto — but only the entries it adds beyond that history ride the commit; see
|
|
900
|
+
* {@link entriesAddedByInvite} and {@link commitWithEntries}.
|
|
901
|
+
*
|
|
902
|
+
* Reads `group`'s state and returns a NEW derived handle (`newGroup`); it never
|
|
903
|
+
* advances `group` itself. The caller must adopt `newGroup` — never reuse `group` —
|
|
904
|
+
* before issuing the next commit: two commits issued from the same source handle
|
|
905
|
+
* both frame at that handle's epoch and diverge. The per-handle mutex only
|
|
906
|
+
* serializes concurrent calls against one handle; it does not make it safe to
|
|
907
|
+
* produce a second commit from a handle a prior commit has already superseded.
|
|
908
|
+
*/ export async function commitInvite(group, keyPackage, invite) {
|
|
909
|
+
return mutexFor(group).run(async ()=>{
|
|
910
|
+
if (invite.groupID !== group.groupID) {
|
|
911
|
+
throw new Error(`commitInvite: invite is for group ${invite.groupID}, not ${group.groupID}`);
|
|
912
|
+
}
|
|
913
|
+
const enacted = entriesAddedByInvite(group, invite);
|
|
914
|
+
const addProposal = {
|
|
915
|
+
proposalType: defaultProposalTypes.add,
|
|
916
|
+
add: {
|
|
917
|
+
keyPackage
|
|
918
|
+
}
|
|
919
|
+
};
|
|
920
|
+
const result = await commitWithEntries(group, [
|
|
921
|
+
addProposal
|
|
922
|
+
], enacted, true);
|
|
923
|
+
const newGroup = deriveGroup(group, result.newState);
|
|
924
|
+
if (result.welcome == null) {
|
|
925
|
+
throw new Error('commitInvite: expected a Welcome message for the add proposal');
|
|
926
|
+
}
|
|
927
|
+
// The entries this commit enacts are now part of the group's ledger.
|
|
928
|
+
await newGroup.applyLedgerEntries(enacted);
|
|
929
|
+
return {
|
|
930
|
+
commitMessage: encode(mlsMessageEncoder, result.commit),
|
|
931
|
+
welcomeMessage: encode(mlsMessageEncoder, result.welcome),
|
|
932
|
+
newGroup,
|
|
933
|
+
epoch: newGroup.epoch
|
|
934
|
+
};
|
|
400
935
|
});
|
|
401
|
-
if (result.welcome == null) {
|
|
402
|
-
throw new Error('commitInvite: expected a Welcome message for the add proposal');
|
|
403
|
-
}
|
|
404
|
-
return {
|
|
405
|
-
commitMessage: encode(mlsMessageEncoder, result.commit),
|
|
406
|
-
welcomeMessage: encode(mlsMessageEncoder, result.welcome),
|
|
407
|
-
newGroup,
|
|
408
|
-
epoch: newGroup.epoch
|
|
409
|
-
};
|
|
410
936
|
}
|
|
411
937
|
/**
|
|
412
938
|
* Process a Welcome message to join a group.
|
|
@@ -414,19 +940,20 @@ export async function restoreGroup(params) {
|
|
|
414
940
|
const { identity, invite, welcome, keyPackageBundle, ratchetTree, options } = params;
|
|
415
941
|
const cache = options?.cache ?? createInMemoryDIDCache();
|
|
416
942
|
const context = await resolveMlsContext(options);
|
|
417
|
-
//
|
|
418
|
-
//
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
const
|
|
422
|
-
|
|
423
|
-
groupID
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
cache,
|
|
427
|
-
resolver: options?.resolver
|
|
943
|
+
// A Welcome is only this member's when the invite carries a role entry naming
|
|
944
|
+
// them: an invite minted for someone else is not an invitation to join.
|
|
945
|
+
const selfDID = normalizeDID(identity.id);
|
|
946
|
+
let namesSelf = false;
|
|
947
|
+
for (const token of invite.ledgerEntries){
|
|
948
|
+
const verified = await verifyLedgerEntry(token);
|
|
949
|
+
if (verified != null && verified.entry.type === ROLE_ENTRY_TYPE && verified.entry.groupID === invite.groupID && normalizeDID(verified.entry.subject) === selfDID) {
|
|
950
|
+
namesSelf = true;
|
|
951
|
+
break;
|
|
428
952
|
}
|
|
429
|
-
}
|
|
953
|
+
}
|
|
954
|
+
if (!namesSelf) {
|
|
955
|
+
throw new Error('processWelcome: the invite carries no role entry naming this identity');
|
|
956
|
+
}
|
|
430
957
|
let resolvedWelcome = welcome;
|
|
431
958
|
if (welcome instanceof Uint8Array) {
|
|
432
959
|
const decoded = decode(mlsMessageDecoder, welcome);
|
|
@@ -447,22 +974,32 @@ export async function restoreGroup(params) {
|
|
|
447
974
|
});
|
|
448
975
|
const credential = {
|
|
449
976
|
id: identity.id,
|
|
450
|
-
capabilityChain: invite.capabilityChain,
|
|
451
|
-
capability: capToken,
|
|
452
|
-
permission: invite.permission,
|
|
453
977
|
groupID: invite.groupID
|
|
454
978
|
};
|
|
455
979
|
const group = new GroupHandle({
|
|
456
980
|
state,
|
|
457
981
|
credential,
|
|
458
982
|
context,
|
|
459
|
-
rootCapability: invite.capabilityChain[0] ?? (()=>{
|
|
460
|
-
throw new Error('Invalid invite: capability chain must not be empty');
|
|
461
|
-
})(),
|
|
462
983
|
cache,
|
|
463
984
|
resolver: options?.resolver,
|
|
464
|
-
commitPolicy: options?.commitPolicy
|
|
985
|
+
commitPolicy: options?.commitPolicy,
|
|
986
|
+
resolveLedgerEntries: options?.resolveLedgerEntries,
|
|
987
|
+
onLedgerEntries: options?.onLedgerEntries
|
|
465
988
|
});
|
|
989
|
+
// Every ledger entry reaches the group inside a commit that extends the head by its
|
|
990
|
+
// id, so the head authenticated in the joined GroupContext is the fold from genesis
|
|
991
|
+
// over the group's entries, in order. Recompute it over the entries the inviter
|
|
992
|
+
// supplied: an omitted, reordered, or truncated list cannot reproduce it. Checked
|
|
993
|
+
// before folding, so an incomplete ledger never reaches the roster.
|
|
994
|
+
const authenticated = readLedgerHead(group);
|
|
995
|
+
if (authenticated == null) {
|
|
996
|
+
throw new Error('processWelcome: the group has no ledger head extension');
|
|
997
|
+
}
|
|
998
|
+
assertHeadMatches(authenticated.head, computeHead(invite.groupID, invite.ledgerEntries.map(ledgerEntryDigest)));
|
|
999
|
+
// Fold the invite's entries: the roster is seeded from the anchor, and the fold
|
|
1000
|
+
// grants authority only to an admin-so-far, so a member-signed entry cannot
|
|
1001
|
+
// promote anyone even though applyLedgerEntries itself is the permissive primitive.
|
|
1002
|
+
await group.applyLedgerEntries(invite.ledgerEntries);
|
|
466
1003
|
return {
|
|
467
1004
|
group,
|
|
468
1005
|
credential
|
|
@@ -470,34 +1007,38 @@ export async function restoreGroup(params) {
|
|
|
470
1007
|
}
|
|
471
1008
|
/**
|
|
472
1009
|
* Remove a member from the group. Advances the epoch and rotates keys.
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
1010
|
+
*
|
|
1011
|
+
* Removal must demote: a receiver rejects a Remove whose target is still `admin` in
|
|
1012
|
+
* the roster the commit's entries fold to. So removing an admin means riding the
|
|
1013
|
+
* demotion entry on the same commit — pass it as `ledgerEntries`. The entry is signed
|
|
1014
|
+
* by the caller, who holds the identity; this only carries it.
|
|
1015
|
+
*
|
|
1016
|
+
* Reads `group`'s state and returns a NEW derived handle (`newGroup`); it never
|
|
1017
|
+
* advances `group` itself. The caller must adopt `newGroup` — never reuse `group` —
|
|
1018
|
+
* before issuing the next commit: two commits issued from the same source handle
|
|
1019
|
+
* both frame at that handle's epoch and diverge. The per-handle mutex only
|
|
1020
|
+
* serializes concurrent calls against one handle; it does not make it safe to
|
|
1021
|
+
* produce a second commit from a handle a prior commit has already superseded.
|
|
1022
|
+
*/ export async function removeMember(group, leafIndex, ledgerEntries) {
|
|
1023
|
+
return mutexFor(group).run(async ()=>{
|
|
1024
|
+
const removeProposal = {
|
|
1025
|
+
proposalType: defaultProposalTypes.remove,
|
|
1026
|
+
remove: {
|
|
1027
|
+
removed: leafIndex
|
|
1028
|
+
}
|
|
1029
|
+
};
|
|
1030
|
+
const enacted = ledgerEntries ?? [];
|
|
1031
|
+
const result = await commitWithEntries(group, [
|
|
484
1032
|
removeProposal
|
|
485
|
-
]
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
resolver: group.resolver,
|
|
494
|
-
commitPolicy: group.commitPolicy
|
|
1033
|
+
], enacted);
|
|
1034
|
+
const newGroup = deriveGroup(group, result.newState);
|
|
1035
|
+
await newGroup.applyLedgerEntries(enacted);
|
|
1036
|
+
return {
|
|
1037
|
+
commitMessage: encode(mlsMessageEncoder, result.commit),
|
|
1038
|
+
newGroup,
|
|
1039
|
+
epoch: newGroup.epoch
|
|
1040
|
+
};
|
|
495
1041
|
});
|
|
496
|
-
return {
|
|
497
|
-
commitMessage: encode(mlsMessageEncoder, result.commit),
|
|
498
|
-
newGroup,
|
|
499
|
-
epoch: newGroup.epoch
|
|
500
|
-
};
|
|
501
1042
|
}
|
|
502
1043
|
/**
|
|
503
1044
|
* Read the MLS epoch from a framed handshake/application message's cleartext
|
|
@@ -564,7 +1105,9 @@ export async function restoreGroup(params) {
|
|
|
564
1105
|
publicKey: identity.publicKey
|
|
565
1106
|
},
|
|
566
1107
|
cipherSuite,
|
|
567
|
-
|
|
1108
|
+
// An invitee leaf must advertise the control extension types or ts-mls
|
|
1109
|
+
// refuses to add it to an anchored group. An explicit override still wins.
|
|
1110
|
+
capabilities: options?.capabilities ?? controlCapabilities()
|
|
568
1111
|
});
|
|
569
1112
|
return {
|
|
570
1113
|
...result,
|
|
@@ -584,15 +1127,12 @@ export async function exportGroupInfo(params) {
|
|
|
584
1127
|
}
|
|
585
1128
|
export async function joinGroupExternal(params) {
|
|
586
1129
|
const { identity, groupInfo: groupInfoBytes, credential, resync, options, authenticatedData } = params;
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
//
|
|
592
|
-
//
|
|
593
|
-
// findIndex returns -1 and the downstream `removeLeafNodeMutable(tree, -1)`
|
|
594
|
-
// call enters an unbounded loop (ts-mls bug; the no-match branch is not
|
|
595
|
-
// guarded). Reject early with a clear error.
|
|
1130
|
+
// Guard: resync replaces the caller's own prior leaf, so the rejoining identity
|
|
1131
|
+
// must match the credential it presents. On a mismatch ts-mls rejects the
|
|
1132
|
+
// external commit downstream (it finds no prior leaf matching the KeyPackage and
|
|
1133
|
+
// throws); reject early here with a clearer error. This is a friendly precheck,
|
|
1134
|
+
// not the security boundary — eviction completeness rests on ts-mls requiring a
|
|
1135
|
+
// matching prior leaf in the resynced tree, which a removed member no longer has.
|
|
596
1136
|
if (normalizeDID(identity.id) !== normalizeDID(credential.id)) {
|
|
597
1137
|
throw new Error(`joinGroupExternal: identity.id (${identity.id}) must match credential.id (${credential.id}) for resync`);
|
|
598
1138
|
}
|
|
@@ -641,10 +1181,11 @@ export async function joinGroupExternal(params) {
|
|
|
641
1181
|
state: newState,
|
|
642
1182
|
credential,
|
|
643
1183
|
context,
|
|
644
|
-
rootCapability,
|
|
645
1184
|
cache,
|
|
646
1185
|
resolver: options?.resolver,
|
|
647
|
-
commitPolicy: options?.commitPolicy
|
|
1186
|
+
commitPolicy: options?.commitPolicy,
|
|
1187
|
+
resolveLedgerEntries: options?.resolveLedgerEntries,
|
|
1188
|
+
onLedgerEntries: options?.onLedgerEntries
|
|
648
1189
|
});
|
|
649
1190
|
return {
|
|
650
1191
|
commitMessage,
|