@kumiai/mls 0.10.0 → 0.10.2
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/anchor.d.ts +10 -4
- package/lib/anchor.js +26 -2
- package/lib/authentication.d.ts +24 -12
- package/lib/authentication.js +192 -83
- package/lib/capability.d.ts +37 -0
- package/lib/capability.js +141 -0
- package/lib/credential.d.ts +7 -7
- package/lib/credential.js +15 -10
- package/lib/device-proof.d.ts +2 -0
- package/lib/device-proof.js +8 -12
- package/lib/envelope-fold.d.ts +16 -1
- package/lib/envelope-fold.js +49 -9
- package/lib/errors.d.ts +18 -0
- package/lib/errors.js +33 -0
- package/lib/group-commit.d.ts +24 -35
- package/lib/group-commit.js +139 -110
- package/lib/group-context.d.ts +6 -2
- package/lib/group-context.js +11 -4
- package/lib/group-create.js +56 -11
- package/lib/group-credential.d.ts +3 -1
- package/lib/group-credential.js +17 -3
- package/lib/group-device.js +34 -21
- package/lib/group-handle.d.ts +31 -8
- package/lib/group-handle.js +275 -58
- package/lib/group-lifecycle.d.ts +49 -0
- package/lib/group-lifecycle.js +341 -0
- package/lib/group-membership.js +7 -3
- package/lib/group-welcome.d.ts +11 -2
- package/lib/group-welcome.js +122 -22
- package/lib/group.d.ts +2 -1
- package/lib/group.js +1 -0
- package/lib/history.d.ts +6 -0
- package/lib/history.js +26 -0
- package/lib/index.d.ts +12 -5
- package/lib/index.js +10 -3
- package/lib/lifecycle-proof.d.ts +33 -0
- package/lib/lifecycle-proof.js +218 -0
- package/lib/lifecycle.d.ts +46 -0
- package/lib/lifecycle.js +410 -0
- package/lib/policy.d.ts +20 -0
- package/lib/policy.js +8 -5
- package/lib/recovery-verdict.d.ts +43 -0
- package/lib/recovery-verdict.js +135 -0
- package/lib/recovery.d.ts +70 -0
- package/lib/recovery.js +110 -36
- package/lib/registry.d.ts +34 -7
- package/lib/registry.js +113 -15
- package/lib/roster.d.ts +1 -1
- package/lib/roster.js +2 -2
- package/lib/secret-tree.d.ts +3 -0
- package/lib/secret-tree.js +60 -0
- package/lib/types.d.ts +13 -8
- package/package.json +5 -5
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import { didFromInception, foldLog } from '@kokuin/controller';
|
|
2
|
+
import { createSigningIdentityForDID, normalizeDID } from '@kokuin/token';
|
|
3
|
+
import { defaultProposalTypes, encode, isDefaultProposal, mlsMessageEncoder, nodeTypes } from 'ts-mls';
|
|
4
|
+
import { readCapability } from './capability.js';
|
|
5
|
+
import { parseMLSCredentialIdentity } from './credential.js';
|
|
6
|
+
import { LeafBindingError, RevokeProofError } from './errors.js';
|
|
7
|
+
import { commitWithEntries } from './group-commit.js';
|
|
8
|
+
import { assertBindingAuthorTime } from './group-credential.js';
|
|
9
|
+
import { deriveGroup, mutexFor } from './group-handle.js';
|
|
10
|
+
import { HISTORY_HORIZON, historySize } from './history.js';
|
|
11
|
+
import { signLedgerEntry } from './ledger.js';
|
|
12
|
+
import { isLapsed, leafAt, treeTime, validateEntry } from './lifecycle.js';
|
|
13
|
+
import { authenticateLifecycleProof, isExemptMember, verifyLifecycleProof } from './lifecycle-proof.js';
|
|
14
|
+
import { DEVICE_ENTRY_TYPE } from './registry.js';
|
|
15
|
+
/**
|
|
16
|
+
* Author a by-reference Remove for this handle's own leaf at its current epoch.
|
|
17
|
+
* Once a member processes a pending self-removal, application encrypt throws until
|
|
18
|
+
* a commit lands. Callers should commit pending self-removals promptly.
|
|
19
|
+
*/ export async function proposeSelfRemoval(group) {
|
|
20
|
+
return group.proposeSelfRemoval();
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Commit other members' pending self-removals without absorbing other pending proposals.
|
|
24
|
+
* Returns null when only the committer's own self-removal (or none) is pending.
|
|
25
|
+
* Once a member processes a pending self-removal, application encrypt throws until
|
|
26
|
+
* a commit lands. Callers should commit pending self-removals promptly.
|
|
27
|
+
*/ export async function commitSelfRemovals(group) {
|
|
28
|
+
return mutexFor(group).run(async ()=>{
|
|
29
|
+
const pendingProposals = Object.fromEntries(Object.entries(group.state.unappliedProposals).filter(([, { proposal, senderLeafIndex }])=>isDefaultProposal(proposal) && proposal.proposalType === defaultProposalTypes.remove && proposal.remove.removed === senderLeafIndex && senderLeafIndex !== group.state.privatePath.leafIndex));
|
|
30
|
+
if (Object.keys(pendingProposals).length === 0) return null;
|
|
31
|
+
const tree = group.state.ratchetTree.slice();
|
|
32
|
+
for (const { proposal } of Object.values(pendingProposals)){
|
|
33
|
+
if (isDefaultProposal(proposal) && proposal.proposalType === defaultProposalTypes.remove) tree[proposal.remove.removed * 2] = undefined;
|
|
34
|
+
}
|
|
35
|
+
const tokens = await clockEntries(group, tree);
|
|
36
|
+
const result = await commitWithEntries({
|
|
37
|
+
group,
|
|
38
|
+
extraProposals: [],
|
|
39
|
+
pendingProposals,
|
|
40
|
+
enacted: tokens,
|
|
41
|
+
requireAdmin: false
|
|
42
|
+
});
|
|
43
|
+
const newGroup = deriveGroup(group, result.newState);
|
|
44
|
+
await newGroup.applyLedgerEntries(tokens);
|
|
45
|
+
return {
|
|
46
|
+
commitMessage: encode(mlsMessageEncoder, result.commit),
|
|
47
|
+
newGroup,
|
|
48
|
+
epoch: newGroup.epoch
|
|
49
|
+
};
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
function ownIdentity(group) {
|
|
53
|
+
const leaf = leafAt(group.state.ratchetTree, group.state.privatePath.leafIndex);
|
|
54
|
+
if (leaf == null || !('identity' in leaf.credential)) throw new LeafBindingError('identity-change');
|
|
55
|
+
const parsed = parseMLSCredentialIdentity(leaf.credential.identity);
|
|
56
|
+
return createSigningIdentityForDID(parsed.longForm ?? parsed.id, group.state.signaturePrivateKey);
|
|
57
|
+
}
|
|
58
|
+
async function clockEntries(group, tree) {
|
|
59
|
+
const controller = group.anchor.controller;
|
|
60
|
+
if (controller == null) return [];
|
|
61
|
+
const before = treeTime(group, controller);
|
|
62
|
+
let after = group.registry.controllers.get(normalizeDID(controller))?.timeFloor ?? 0;
|
|
63
|
+
for (const node of tree){
|
|
64
|
+
if (node?.nodeType !== nodeTypes.leaf || !('identity' in node.leaf.credential)) continue;
|
|
65
|
+
const binding = parseMLSCredentialIdentity(node.leaf.credential.identity).controller;
|
|
66
|
+
if (binding == null || normalizeDID(binding.id) !== normalizeDID(controller)) continue;
|
|
67
|
+
const payload = readCapability(binding.capability).payload;
|
|
68
|
+
const parent = Array.isArray(payload.cap) ? payload.cap[0] : payload.cap;
|
|
69
|
+
after = Math.max(after, parent == null ? payload.iat : readCapability(parent).payload.iat);
|
|
70
|
+
}
|
|
71
|
+
if (after >= before) return [];
|
|
72
|
+
return [
|
|
73
|
+
await signLedgerEntry(ownIdentity(group), {
|
|
74
|
+
type: DEVICE_ENTRY_TYPE,
|
|
75
|
+
groupID: group.groupID,
|
|
76
|
+
subject: controller,
|
|
77
|
+
value: {
|
|
78
|
+
op: 'clock',
|
|
79
|
+
time: before
|
|
80
|
+
}
|
|
81
|
+
})
|
|
82
|
+
];
|
|
83
|
+
}
|
|
84
|
+
async function buildResult(params) {
|
|
85
|
+
const { group, proposals, tokens, commitState } = params;
|
|
86
|
+
const result = await commitWithEntries({
|
|
87
|
+
group,
|
|
88
|
+
extraProposals: proposals,
|
|
89
|
+
enacted: tokens,
|
|
90
|
+
requireAdmin: false,
|
|
91
|
+
commitState
|
|
92
|
+
});
|
|
93
|
+
// MLS captured the replacement tree as historical data when building a renewal.
|
|
94
|
+
const historical = result.newState.historicalReceiverData.get(group.epoch);
|
|
95
|
+
if (historical != null && commitState != null) historical.ratchetTree = group.state.ratchetTree;
|
|
96
|
+
const newGroup = deriveGroup(group, result.newState);
|
|
97
|
+
await newGroup.applyLedgerEntries(tokens);
|
|
98
|
+
return {
|
|
99
|
+
commitMessage: encode(mlsMessageEncoder, result.commit),
|
|
100
|
+
newGroup,
|
|
101
|
+
epoch: newGroup.epoch
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
export async function renewLeaf(group, binding) {
|
|
105
|
+
return mutexFor(group).run(async ()=>{
|
|
106
|
+
assertBindingAuthorTime(binding);
|
|
107
|
+
const index = group.state.privatePath.leafIndex * 2;
|
|
108
|
+
const tree = group.state.ratchetTree.slice();
|
|
109
|
+
const original = tree[index];
|
|
110
|
+
if (original?.nodeType !== nodeTypes.leaf || !('identity' in original.leaf.credential)) throw new LeafBindingError('identity-change');
|
|
111
|
+
const own = structuredClone(original);
|
|
112
|
+
if (!('identity' in own.leaf.credential)) throw new LeafBindingError('identity-change');
|
|
113
|
+
const parsed = parseMLSCredentialIdentity(own.leaf.credential.identity);
|
|
114
|
+
own.leaf.credential.identity = new TextEncoder().encode(JSON.stringify({
|
|
115
|
+
v: 1,
|
|
116
|
+
...parsed,
|
|
117
|
+
controller: binding
|
|
118
|
+
}));
|
|
119
|
+
tree[index] = own;
|
|
120
|
+
await validateEntry(group, own.leaf, original.leaf);
|
|
121
|
+
if (group.anchor.controller != null) {
|
|
122
|
+
const entries = group.ledger.map(({ verified })=>verified);
|
|
123
|
+
const before = historySize(group.state.ratchetTree, entries);
|
|
124
|
+
const after = historySize(tree, entries);
|
|
125
|
+
if (after > HISTORY_HORIZON && after > before) throw new LeafBindingError('history-horizon');
|
|
126
|
+
}
|
|
127
|
+
const tokens = await clockEntries(group, tree);
|
|
128
|
+
return buildResult({
|
|
129
|
+
group,
|
|
130
|
+
proposals: [],
|
|
131
|
+
tokens,
|
|
132
|
+
commitState: {
|
|
133
|
+
...group.state,
|
|
134
|
+
ratchetTree: tree
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
export async function removeLapsedLeaves(group) {
|
|
140
|
+
return mutexFor(group).run(async ()=>{
|
|
141
|
+
const removed = [];
|
|
142
|
+
const proposals = [];
|
|
143
|
+
const tree = group.state.ratchetTree.slice();
|
|
144
|
+
for (const member of group.listMembers()){
|
|
145
|
+
const leaf = leafAt(tree, member.leafIndex);
|
|
146
|
+
if (leaf == null || !isLapsed(group, leaf)) continue;
|
|
147
|
+
removed.push(member.id);
|
|
148
|
+
tree[member.leafIndex * 2] = undefined;
|
|
149
|
+
proposals.push({
|
|
150
|
+
proposalType: defaultProposalTypes.remove,
|
|
151
|
+
remove: {
|
|
152
|
+
removed: member.leafIndex
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
if (removed.length === 0) return {
|
|
157
|
+
removed
|
|
158
|
+
};
|
|
159
|
+
const tokens = await clockEntries(group, tree);
|
|
160
|
+
return {
|
|
161
|
+
removed,
|
|
162
|
+
result: await buildResult({
|
|
163
|
+
group,
|
|
164
|
+
proposals,
|
|
165
|
+
tokens
|
|
166
|
+
})
|
|
167
|
+
};
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
/** The slice of `log` a receiver needs on top of the controller events it already recorded. */ function proofFor(params) {
|
|
171
|
+
const { group, log, subject, reset } = params;
|
|
172
|
+
const controller = group.anchor.controller;
|
|
173
|
+
if (controller == null) throw new RevokeProofError('wrong-controller');
|
|
174
|
+
if (log.length === 0) throw new RevokeProofError('no-rev');
|
|
175
|
+
const first = log[0];
|
|
176
|
+
if (first?.event.t === 'icp') {
|
|
177
|
+
let did;
|
|
178
|
+
try {
|
|
179
|
+
did = didFromInception(first.event);
|
|
180
|
+
} catch (cause) {
|
|
181
|
+
const rejection = new RevokeProofError('not-authority-signed');
|
|
182
|
+
rejection.cause = cause;
|
|
183
|
+
throw rejection;
|
|
184
|
+
}
|
|
185
|
+
if (normalizeDID(did) !== normalizeDID(controller)) throw new RevokeProofError('wrong-controller');
|
|
186
|
+
}
|
|
187
|
+
if (log.some(({ event })=>event.t !== 'icp' && event.i !== controller)) throw new RevokeProofError('wrong-controller');
|
|
188
|
+
const folded = foldLog(controller, log);
|
|
189
|
+
if (!folded.ok) {
|
|
190
|
+
const detached = /sequence|digest|prior|inception must/.test(folded.reason);
|
|
191
|
+
throw new RevokeProofError(detached ? 'detached' : 'not-authority-signed');
|
|
192
|
+
}
|
|
193
|
+
// Drop events that leave the folded state unchanged.
|
|
194
|
+
const advancing = log.filter((_, index)=>index === 0 || folded.states[index]?.digest !== folded.states[index - 1]?.digest);
|
|
195
|
+
const canonical = foldLog(controller, advancing);
|
|
196
|
+
if (!canonical.ok) throw new RevokeProofError('not-authority-signed');
|
|
197
|
+
let resetIndex = -1;
|
|
198
|
+
for(let index = 1; index < advancing.length; index++){
|
|
199
|
+
if (advancing[index]?.event.g !== advancing[index - 1]?.event.g) resetIndex = index;
|
|
200
|
+
}
|
|
201
|
+
const projection = group.registry.controllers.get(normalizeDID(controller));
|
|
202
|
+
const recorded = projection?.recordedLog ?? [];
|
|
203
|
+
const floor = projection?.genFloor ?? 0;
|
|
204
|
+
if (reset) {
|
|
205
|
+
if (resetIndex < 0) throw new RevokeProofError('no-rev');
|
|
206
|
+
return [
|
|
207
|
+
advancing[0],
|
|
208
|
+
...advancing.slice(resetIndex)
|
|
209
|
+
];
|
|
210
|
+
}
|
|
211
|
+
const recordedFold = foldLog(controller, recorded);
|
|
212
|
+
const recordedHead = recordedFold.ok ? recordedFold.states.at(-1) : undefined;
|
|
213
|
+
const generation = canonical.states.at(-1)?.gen ?? 0;
|
|
214
|
+
if (recorded.length > 0 && generation > (recordedHead?.gen ?? floor)) throw new RevokeProofError('needs-reset');
|
|
215
|
+
const start = recorded.length === 0 ? Math.max(1, resetIndex) : 1;
|
|
216
|
+
let end = advancing.findIndex(({ event }, index)=>index >= start && event.t === 'rev' && 'x' in event && typeof event.x === 'string' && normalizeDID(event.x) === subject && (canonical.states[index]?.gen ?? 0) >= floor);
|
|
217
|
+
if (end < 0) {
|
|
218
|
+
if (generation < floor) throw new RevokeProofError('generation-floor');
|
|
219
|
+
throw new RevokeProofError('no-rev');
|
|
220
|
+
}
|
|
221
|
+
if (recorded.length === 0) {
|
|
222
|
+
return [
|
|
223
|
+
advancing[0],
|
|
224
|
+
...advancing.slice(start, end + 1)
|
|
225
|
+
];
|
|
226
|
+
}
|
|
227
|
+
const headIndex = canonical.states.findIndex(({ digest })=>digest === recordedHead?.digest);
|
|
228
|
+
if (headIndex < 0) throw new RevokeProofError('detached');
|
|
229
|
+
end = Math.max(headIndex, end);
|
|
230
|
+
return advancing.slice(headIndex + 1, end + 1);
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Revoked in the registry, with no leaf of its own and no leaf it issued left in the tree, apart
|
|
234
|
+
* from evidenced children, which its revocation never removes.
|
|
235
|
+
*/ function isFullyRevoked(group, subject) {
|
|
236
|
+
if (group.registry.devices.get(subject)?.status !== 'revoked') return false;
|
|
237
|
+
if (group.findMemberLeafIndex(subject) != null) return false;
|
|
238
|
+
return !group.listMembers().some((member)=>{
|
|
239
|
+
const capability = group.bindingOfDID(member.id)?.capability;
|
|
240
|
+
return capability != null && normalizeDID(readCapability(capability).payload.iss) === subject && !isExemptMember(group, member.leafIndex);
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
export async function revokeWithProof(group, params) {
|
|
244
|
+
return mutexFor(group).run(async ()=>{
|
|
245
|
+
try {
|
|
246
|
+
const controller = group.anchor.controller;
|
|
247
|
+
if (controller == null) throw new RevokeProofError('wrong-controller');
|
|
248
|
+
const reset = 'reset' in params;
|
|
249
|
+
const subject = normalizeDID(reset ? controller : params.subject);
|
|
250
|
+
if (!reset && isFullyRevoked(group, subject)) return {
|
|
251
|
+
status: 'already-revoked'
|
|
252
|
+
};
|
|
253
|
+
const value = {
|
|
254
|
+
op: reset ? 'reset' : 'revoke',
|
|
255
|
+
proof: proofFor({
|
|
256
|
+
group,
|
|
257
|
+
log: params.log,
|
|
258
|
+
subject,
|
|
259
|
+
reset
|
|
260
|
+
}),
|
|
261
|
+
revoked: []
|
|
262
|
+
};
|
|
263
|
+
const verified = {
|
|
264
|
+
issuer: group.credential.id,
|
|
265
|
+
entry: {
|
|
266
|
+
type: DEVICE_ENTRY_TYPE,
|
|
267
|
+
groupID: group.groupID,
|
|
268
|
+
subject,
|
|
269
|
+
value
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
const authenticated = authenticateLifecycleProof(controller, verified, group.registry);
|
|
273
|
+
const revoked = reset ? [] : [
|
|
274
|
+
{
|
|
275
|
+
did: subject
|
|
276
|
+
}
|
|
277
|
+
];
|
|
278
|
+
const leaves = group.listMembers().map((member)=>{
|
|
279
|
+
const binding = group.bindingOfDID(member.id);
|
|
280
|
+
const payload = binding?.capability == null ? undefined : readCapability(binding.capability).payload;
|
|
281
|
+
const folded = binding?.prefix == null ? undefined : foldLog(controller, binding.prefix);
|
|
282
|
+
return {
|
|
283
|
+
...member,
|
|
284
|
+
issuer: payload?.cap == null ? undefined : normalizeDID(payload.iss),
|
|
285
|
+
generation: folded?.ok ? folded.states.at(-1)?.gen : undefined,
|
|
286
|
+
exempt: isExemptMember(group, member.leafIndex)
|
|
287
|
+
};
|
|
288
|
+
});
|
|
289
|
+
if (reset) for (const leaf of leaves){
|
|
290
|
+
if (leaf.generation != null && leaf.generation < authenticated.genFloor) revoked.push({
|
|
291
|
+
did: normalizeDID(leaf.id)
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
const direct = new Set(revoked.map(({ did })=>did));
|
|
295
|
+
for (const leaf of leaves){
|
|
296
|
+
if (leaf.issuer != null && direct.has(leaf.issuer) && !direct.has(normalizeDID(leaf.id)) && !leaf.exempt) revoked.push({
|
|
297
|
+
did: normalizeDID(leaf.id),
|
|
298
|
+
cascadedFrom: leaf.issuer
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
value.revoked = revoked;
|
|
302
|
+
if (revoked.some(({ did })=>did === normalizeDID(group.credential.id))) return {
|
|
303
|
+
status: 'self-affected',
|
|
304
|
+
subject: group.credential.id
|
|
305
|
+
};
|
|
306
|
+
const effects = await verifyLifecycleProof(group, verified);
|
|
307
|
+
const tree = group.state.ratchetTree.slice();
|
|
308
|
+
const proposals = effects.removeLeafIndices.map((removed)=>{
|
|
309
|
+
tree[removed * 2] = undefined;
|
|
310
|
+
return {
|
|
311
|
+
proposalType: defaultProposalTypes.remove,
|
|
312
|
+
remove: {
|
|
313
|
+
removed
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
});
|
|
317
|
+
const tokens = [
|
|
318
|
+
await signLedgerEntry(ownIdentity(group), verified.entry),
|
|
319
|
+
...await clockEntries(group, tree)
|
|
320
|
+
];
|
|
321
|
+
return {
|
|
322
|
+
status: 'built',
|
|
323
|
+
result: await buildResult({
|
|
324
|
+
group,
|
|
325
|
+
proposals,
|
|
326
|
+
tokens
|
|
327
|
+
})
|
|
328
|
+
};
|
|
329
|
+
} catch (error) {
|
|
330
|
+
if (error instanceof RevokeProofError) return {
|
|
331
|
+
status: 'not-provable',
|
|
332
|
+
reason: error.reason
|
|
333
|
+
};
|
|
334
|
+
if (error instanceof LeafBindingError && error.reason === 'history-horizon') return {
|
|
335
|
+
status: 'not-provable',
|
|
336
|
+
reason: 'too-large'
|
|
337
|
+
};
|
|
338
|
+
throw error;
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
}
|
package/lib/group-membership.js
CHANGED
|
@@ -22,9 +22,13 @@ import { deriveGroup, mutexFor } from './group-handle.js';
|
|
|
22
22
|
}
|
|
23
23
|
};
|
|
24
24
|
const enacted = ledgerEntries ?? [];
|
|
25
|
-
const result = await commitWithEntries(
|
|
26
|
-
|
|
27
|
-
|
|
25
|
+
const result = await commitWithEntries({
|
|
26
|
+
group,
|
|
27
|
+
extraProposals: [
|
|
28
|
+
removeProposal
|
|
29
|
+
],
|
|
30
|
+
enacted
|
|
31
|
+
});
|
|
28
32
|
const newGroup = deriveGroup(group, result.newState);
|
|
29
33
|
await newGroup.applyLedgerEntries(enacted);
|
|
30
34
|
return {
|
package/lib/group-welcome.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { type OwnIdentity } from '@kokuin/token';
|
|
2
|
-
import { type Welcome } from 'ts-mls';
|
|
3
|
-
import type
|
|
2
|
+
import { type ClientState, type Welcome } from 'ts-mls';
|
|
3
|
+
import { type ControllerBinding, type MemberCredential } from './credential.js';
|
|
4
4
|
import { GroupHandle } from './group-handle.js';
|
|
5
|
+
import type { DeviceRegistry } from './registry.js';
|
|
5
6
|
import type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
|
|
6
7
|
export type ProcessWelcomeResult = {
|
|
7
8
|
group: GroupHandle;
|
|
@@ -52,13 +53,21 @@ export type JoinGroupExternalParams = {
|
|
|
52
53
|
credential: MemberCredential;
|
|
53
54
|
/** Stale-recovery only: atomically removes prior leaf for same identity. */
|
|
54
55
|
resync: true;
|
|
56
|
+
/** Authenticated recovery reply ledger, checked against the source GroupContext. */
|
|
57
|
+
ledgerEntries?: Array<string>;
|
|
58
|
+
controller?: ControllerBinding;
|
|
55
59
|
options?: GroupOptions;
|
|
56
60
|
authenticatedData?: Uint8Array;
|
|
61
|
+
/** @internal Judge the attestation before any replacement-binding checks. */
|
|
62
|
+
beforeBinding?: (pending: GroupHandle, source: GroupHandle) => Promise<void>;
|
|
57
63
|
};
|
|
58
64
|
export type JoinGroupExternalResult = {
|
|
59
65
|
/** Framed MLSMessage(PublicMessage) bytes. Broadcast to existing members. */
|
|
60
66
|
commitMessage: Uint8Array;
|
|
61
67
|
/** New GroupHandle at post-commit epoch. */
|
|
62
68
|
group: GroupHandle;
|
|
69
|
+
/** @internal Inputs from the source admission gate, without operational source secrets. */
|
|
70
|
+
sourceTree: ClientState['ratchetTree'];
|
|
71
|
+
sourceRegistry: DeviceRegistry;
|
|
63
72
|
};
|
|
64
73
|
export declare function joinGroupExternal(params: JoinGroupExternalParams): Promise<JoinGroupExternalResult>;
|
package/lib/group-welcome.js
CHANGED
|
@@ -1,28 +1,22 @@
|
|
|
1
1
|
import { normalizeDID } from '@kokuin/token';
|
|
2
|
-
import { decode, encode, generateKeyPackageWithKey, joinGroup as mlsJoinGroup, joinGroupExternal as mlsJoinGroupExternal, mlsMessageDecoder, mlsMessageEncoder, protocolVersions, wireformats } from 'ts-mls';
|
|
2
|
+
import { contentTypes, decode, defaultCredentialTypes, defaultProposalTypes, encode, generateKeyPackageWithKey, isDefaultCredential, isDefaultProposal, joinGroup as mlsJoinGroup, joinGroupExternal as mlsJoinGroupExternal, mlsMessageDecoder, mlsMessageEncoder, nodeTypes, proposalOrRefTypes, protocolVersions, wireformats } from 'ts-mls';
|
|
3
|
+
import { decodeGroupAnchor, GROUP_ANCHOR_EXTENSION_TYPE } from './anchor.js';
|
|
4
|
+
import { verifyLeafCredential } from './authentication.js';
|
|
3
5
|
import { sanitizeRatchetTree } from './codec.js';
|
|
6
|
+
import { parseMLSCredentialIdentity } from './credential.js';
|
|
7
|
+
import { LeafBindingError } from './errors.js';
|
|
4
8
|
import { buildLeafCapabilities, resolveMlsContext } from './group-context.js';
|
|
5
|
-
import { makeMLSCredential } from './group-credential.js';
|
|
6
|
-
import { GroupHandle } from './group-handle.js';
|
|
9
|
+
import { assertBindingAuthorTime, makeMLSCredential } from './group-credential.js';
|
|
10
|
+
import { buildCommitPolicyContext, GroupHandle } from './group-handle.js';
|
|
7
11
|
import { assertHeadMatches, computeHead, readLedgerHead } from './head.js';
|
|
8
12
|
import { ledgerEntryDigest, verifyLedgerEntry } from './ledger.js';
|
|
13
|
+
import { prepareLifecycleGate, validateWelcomeTree } from './lifecycle.js';
|
|
9
14
|
import { ROLE_ENTRY_TYPE } from './roster.js';
|
|
10
15
|
export async function processWelcome(params) {
|
|
11
16
|
const { identity, invite, welcome, keyPackageBundle, ratchetTree, options } = params;
|
|
12
17
|
const context = await resolveMlsContext(options);
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
const selfDID = normalizeDID(identity.id);
|
|
16
|
-
let namesSelf = false;
|
|
17
|
-
for (const token of invite.ledgerEntries){
|
|
18
|
-
const verified = await verifyLedgerEntry(token);
|
|
19
|
-
if (verified != null && verified.entry.type === ROLE_ENTRY_TYPE && verified.entry.groupID === invite.groupID && normalizeDID(verified.entry.subject) === selfDID) {
|
|
20
|
-
namesSelf = true;
|
|
21
|
-
break;
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
if (!namesSelf) {
|
|
25
|
-
throw new Error('processWelcome: the invite carries no role entry naming this identity');
|
|
18
|
+
if (normalizeDID(invite.recipientDID) !== normalizeDID(identity.id)) {
|
|
19
|
+
throw new Error('processWelcome: the invite recipient is not this identity');
|
|
26
20
|
}
|
|
27
21
|
let resolvedWelcome = welcome;
|
|
28
22
|
if (welcome instanceof Uint8Array) {
|
|
@@ -34,7 +28,15 @@ export async function processWelcome(params) {
|
|
|
34
28
|
}
|
|
35
29
|
const sanitizedTree = Array.isArray(ratchetTree) ? sanitizeRatchetTree(ratchetTree) : ratchetTree;
|
|
36
30
|
const state = await mlsJoinGroup({
|
|
37
|
-
context
|
|
31
|
+
context: {
|
|
32
|
+
...context,
|
|
33
|
+
authService: {
|
|
34
|
+
async validateCredential (credential, signaturePublicKey) {
|
|
35
|
+
await verifyLeafCredential(credential, signaturePublicKey);
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
},
|
|
38
40
|
welcome: resolvedWelcome,
|
|
39
41
|
keyPackage: keyPackageBundle.publicPackage,
|
|
40
42
|
privateKeys: keyPackageBundle.privatePackage,
|
|
@@ -42,6 +44,10 @@ export async function processWelcome(params) {
|
|
|
42
44
|
ratchetTree: sanitizedTree
|
|
43
45
|
}
|
|
44
46
|
});
|
|
47
|
+
const joinedLeaf = state.ratchetTree[state.privatePath.leafIndex * 2];
|
|
48
|
+
if (joinedLeaf?.nodeType !== nodeTypes.leaf || !isDefaultCredential(joinedLeaf.leaf.credential) || joinedLeaf.leaf.credential.credentialType !== defaultCredentialTypes.basic || normalizeDID(parseMLSCredentialIdentity(joinedLeaf.leaf.credential.identity).id) !== normalizeDID(invite.recipientDID)) {
|
|
49
|
+
throw new Error('processWelcome: the joined leaf does not name the invite recipient');
|
|
50
|
+
}
|
|
45
51
|
const credential = {
|
|
46
52
|
id: identity.id,
|
|
47
53
|
groupID: invite.groupID
|
|
@@ -66,7 +72,16 @@ export async function processWelcome(params) {
|
|
|
66
72
|
// Fold the invite's entries: the roster is seeded from the anchor and the fold grants
|
|
67
73
|
// authority only to an admin-so-far, so a member-signed entry cannot promote anyone
|
|
68
74
|
// even though applyLedgerEntries itself is the permissive primitive.
|
|
75
|
+
if (group.anchor.controller == null) {
|
|
76
|
+
let namesSelf = false;
|
|
77
|
+
for (const token of invite.ledgerEntries){
|
|
78
|
+
const verified = await verifyLedgerEntry(token);
|
|
79
|
+
if (verified?.entry.type === ROLE_ENTRY_TYPE && verified.entry.groupID === invite.groupID && normalizeDID(verified.entry.subject) === normalizeDID(identity.id)) namesSelf = true;
|
|
80
|
+
}
|
|
81
|
+
if (!namesSelf) throw new Error('processWelcome: the invite carries no role entry naming this identity');
|
|
82
|
+
}
|
|
69
83
|
await group.applyLedgerEntries(invite.ledgerEntries);
|
|
84
|
+
await validateWelcomeTree(group);
|
|
70
85
|
return {
|
|
71
86
|
group,
|
|
72
87
|
credential
|
|
@@ -101,7 +116,7 @@ export async function processWelcome(params) {
|
|
|
101
116
|
return result;
|
|
102
117
|
}
|
|
103
118
|
export async function joinGroupExternal(params) {
|
|
104
|
-
const { identity, groupInfo: groupInfoBytes, credential, resync, options, authenticatedData } = params;
|
|
119
|
+
const { identity, groupInfo: groupInfoBytes, credential, resync, options, authenticatedData, controller, ledgerEntries } = params;
|
|
105
120
|
// Resync replaces the caller's own prior leaf, so the rejoining identity must match
|
|
106
121
|
// the presented credential. A friendly precheck, not the security boundary: on a
|
|
107
122
|
// mismatch ts-mls rejects the external commit downstream anyway. Eviction
|
|
@@ -110,7 +125,6 @@ export async function joinGroupExternal(params) {
|
|
|
110
125
|
if (normalizeDID(identity.id) !== normalizeDID(credential.id)) {
|
|
111
126
|
throw new Error(`joinGroupExternal: identity.id (${identity.id}) must match credential.id (${credential.id}) for resync`);
|
|
112
127
|
}
|
|
113
|
-
const context = await resolveMlsContext(options);
|
|
114
128
|
const message = decode(mlsMessageDecoder, groupInfoBytes);
|
|
115
129
|
if (message == null) {
|
|
116
130
|
throw new Error('Invalid groupInfo: failed to decode MLSMessage');
|
|
@@ -127,11 +141,36 @@ export async function joinGroupExternal(params) {
|
|
|
127
141
|
if (offeredGroupID !== credential.groupID) {
|
|
128
142
|
throw new Error(`joinGroupExternal: groupInfo names group ${offeredGroupID}, not credential.groupID (${credential.groupID})`);
|
|
129
143
|
}
|
|
144
|
+
const anchorExtension = groupInfo.groupContext.extensions.find((extension)=>extension.extensionType === GROUP_ANCHOR_EXTENSION_TYPE);
|
|
145
|
+
const anchor = anchorExtension?.extensionData instanceof Uint8Array ? decodeGroupAnchor(anchorExtension.extensionData) : null;
|
|
146
|
+
if (anchor == null) throw new Error('joinGroupExternal: the group has no valid anchor');
|
|
147
|
+
const context = await resolveMlsContext(options, anchor);
|
|
148
|
+
const originalCredentials = [];
|
|
149
|
+
const joinContext = {
|
|
150
|
+
...context,
|
|
151
|
+
authService: {
|
|
152
|
+
async validateCredential (leafCredential, signaturePublicKey) {
|
|
153
|
+
if (!isDefaultCredential(leafCredential) || leafCredential.credentialType !== defaultCredentialTypes.basic) return false;
|
|
154
|
+
const parsed = parseMLSCredentialIdentity(leafCredential.identity);
|
|
155
|
+
if (anchor.controller != null && parsed.controller == null) throw new LeafBindingError('floating-refused');
|
|
156
|
+
if (anchor.controller != null && parsed.controller != null && normalizeDID(parsed.controller.id) !== normalizeDID(anchor.controller)) throw new LeafBindingError('controller-mismatch');
|
|
157
|
+
await verifyLeafCredential(leafCredential, signaturePublicKey, {
|
|
158
|
+
leafLifetime: ()=>anchor.controller == null ? undefined : anchor.leafLifetime ?? 86_400,
|
|
159
|
+
trustedGrantLifetime: ()=>anchor.controller == null ? undefined : anchor.trustedGrantLifetime ?? 2_592_000
|
|
160
|
+
});
|
|
161
|
+
originalCredentials.push({
|
|
162
|
+
credential: leafCredential,
|
|
163
|
+
signaturePublicKey
|
|
164
|
+
});
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
};
|
|
130
169
|
// The rejoining leaf must advertise every GroupContext extension the group uses, or
|
|
131
170
|
// ts-mls rejects the external join. Derive them from the GroupInfo being resynced
|
|
132
171
|
// against, honoring an explicit capabilities override.
|
|
133
172
|
const keyPackage = await generateKeyPackageWithKey({
|
|
134
|
-
credential: makeMLSCredential(identity),
|
|
173
|
+
credential: makeMLSCredential(identity, controller),
|
|
135
174
|
signatureKeyPair: {
|
|
136
175
|
signKey: identity.privateKey,
|
|
137
176
|
publicKey: identity.publicKey
|
|
@@ -140,7 +179,7 @@ export async function joinGroupExternal(params) {
|
|
|
140
179
|
capabilities: buildLeafCapabilities(groupInfo.groupContext.extensions, options?.capabilities)
|
|
141
180
|
});
|
|
142
181
|
const { publicMessage, newState } = await mlsJoinGroupExternal({
|
|
143
|
-
context,
|
|
182
|
+
context: joinContext,
|
|
144
183
|
groupInfo,
|
|
145
184
|
keyPackage: keyPackage.publicPackage,
|
|
146
185
|
privateKeys: keyPackage.privatePackage,
|
|
@@ -163,8 +202,69 @@ export async function joinGroupExternal(params) {
|
|
|
163
202
|
resolveLedgerEntries: options?.resolveLedgerEntries,
|
|
164
203
|
onLedgerEntries: options?.onLedgerEntries
|
|
165
204
|
});
|
|
205
|
+
const ownIndex = newState.privatePath.leafIndex;
|
|
206
|
+
const own = newState.ratchetTree[ownIndex * 2];
|
|
207
|
+
const previous = originalCredentials.find(({ credential: candidate })=>isDefaultCredential(candidate) && candidate.credentialType === defaultCredentialTypes.basic && normalizeDID(parseMLSCredentialIdentity(candidate.identity).id) === normalizeDID(identity.id));
|
|
208
|
+
if (own?.nodeType !== nodeTypes.leaf || previous == null) throw new LeafBindingError('identity-change');
|
|
209
|
+
// Only the replaced leaf's credential and key affect the lifecycle predicates.
|
|
210
|
+
if (publicMessage.content.contentType !== contentTypes.commit) throw new Error('Expected external commit');
|
|
211
|
+
const proposals = publicMessage.content.commit.proposals.map((proposal)=>{
|
|
212
|
+
if (proposal.proposalOrRefType !== proposalOrRefTypes.proposal) throw new Error('Expected inline proposal');
|
|
213
|
+
return {
|
|
214
|
+
proposal: proposal.proposal,
|
|
215
|
+
senderLeafIndex: ownIndex
|
|
216
|
+
};
|
|
217
|
+
});
|
|
218
|
+
const removed = proposals.find(({ proposal })=>isDefaultProposal(proposal) && proposal.proposalType === defaultProposalTypes.remove)?.proposal;
|
|
219
|
+
if (removed == null || !isDefaultProposal(removed) || removed.proposalType !== defaultProposalTypes.remove) throw new Error('Missing replacement target');
|
|
220
|
+
const beforeTree = newState.ratchetTree.slice();
|
|
221
|
+
beforeTree[ownIndex * 2] = undefined;
|
|
222
|
+
beforeTree[removed.remove.removed * 2] = {
|
|
223
|
+
...own,
|
|
224
|
+
leaf: {
|
|
225
|
+
...own.leaf,
|
|
226
|
+
...previous
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
const before = new GroupHandle({
|
|
230
|
+
state: {
|
|
231
|
+
...newState,
|
|
232
|
+
ratchetTree: beforeTree,
|
|
233
|
+
groupContext: groupInfo.groupContext
|
|
234
|
+
},
|
|
235
|
+
credential,
|
|
236
|
+
context: await resolveMlsContext(options, anchor)
|
|
237
|
+
});
|
|
238
|
+
if (ledgerEntries != null) {
|
|
239
|
+
await before.bootstrapLedger(ledgerEntries);
|
|
240
|
+
await group.bootstrapLedger(ledgerEntries);
|
|
241
|
+
}
|
|
242
|
+
await params.beforeBinding?.(group, before);
|
|
243
|
+
if (anchor.controller != null && controller == null) throw new LeafBindingError('floating-refused');
|
|
244
|
+
assertBindingAuthorTime(controller);
|
|
245
|
+
const gate = await prepareLifecycleGate({
|
|
246
|
+
group: before,
|
|
247
|
+
entries: [],
|
|
248
|
+
candidateRegistry: before.registry,
|
|
249
|
+
context: buildCommitPolicyContext(before, {
|
|
250
|
+
baseRoster: before.roster,
|
|
251
|
+
candidateRoster: before.roster,
|
|
252
|
+
entryIDs: [],
|
|
253
|
+
enactedDeviceEntries: []
|
|
254
|
+
}),
|
|
255
|
+
externalLeaf: own.leaf
|
|
256
|
+
});
|
|
257
|
+
gate.check({
|
|
258
|
+
kind: 'commit',
|
|
259
|
+
senderLeafIndex: undefined,
|
|
260
|
+
proposals
|
|
261
|
+
});
|
|
262
|
+
await gate.postApply(newState);
|
|
263
|
+
await validateWelcomeTree(group);
|
|
166
264
|
return {
|
|
167
265
|
commitMessage,
|
|
168
|
-
group
|
|
266
|
+
group,
|
|
267
|
+
sourceTree: beforeTree,
|
|
268
|
+
sourceRegistry: before.registry
|
|
169
269
|
};
|
|
170
270
|
}
|
package/lib/group.d.ts
CHANGED
|
@@ -2,7 +2,8 @@ export { type CommitInviteResult, type CommitLedgerEntriesResult, type CreateInv
|
|
|
2
2
|
export { type CreateGroupResult, createGroup, type RestoreGroupParams, restoreGroup, } from './group-create.js';
|
|
3
3
|
export { createKeyPackageBundle, createLastResortKeyPackageBundle, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, } from './group-credential.js';
|
|
4
4
|
export { addDevice, announceControllerBeacon, type DeviceWriteResult, labelDevice, registerDevice, revokeDevice, } from './group-device.js';
|
|
5
|
-
export { CommitRejectedError, GroupHandle, type GroupHandleEvents, type GroupHandleParams, type HeldLedgerEntry, type LedgerLogEntry, } from './group-handle.js';
|
|
5
|
+
export { CommitRejectedError, GroupHandle, type GroupHandleEvents, type GroupHandleParams, type HeldLedgerEntry, type LedgerLogEntry, type SendAdmission, } from './group-handle.js';
|
|
6
6
|
export { type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, type GroupInfoBinding, type InspectGroupInfoResult, inspectGroupInfo, readCommitEntryIDs, readGroupInfoBinding, readMessageAAD, readMessageEpoch, } from './group-info.js';
|
|
7
|
+
export { type RevokeBuildResult, removeLapsedLeaves, renewLeaf, revokeWithProof, } from './group-lifecycle.js';
|
|
7
8
|
export { type RemoveMemberResult, removeMember } from './group-membership.js';
|
|
8
9
|
export { type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, type ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, } from './group-welcome.js';
|
package/lib/group.js
CHANGED
|
@@ -4,5 +4,6 @@ export { createKeyPackageBundle, createLastResortKeyPackageBundle, LAST_RESORT_E
|
|
|
4
4
|
export { addDevice, announceControllerBeacon, labelDevice, registerDevice, revokeDevice } from './group-device.js';
|
|
5
5
|
export { CommitRejectedError, GroupHandle } from './group-handle.js';
|
|
6
6
|
export { exportGroupInfo, inspectGroupInfo, readCommitEntryIDs, readGroupInfoBinding, readMessageAAD, readMessageEpoch } from './group-info.js';
|
|
7
|
+
export { removeLapsedLeaves, renewLeaf, revokeWithProof } from './group-lifecycle.js';
|
|
7
8
|
export { removeMember } from './group-membership.js';
|
|
8
9
|
export { joinGroupExternal, processWelcome, processWelcomeOnce } from './group-welcome.js';
|
package/lib/history.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type ClientState } from 'ts-mls';
|
|
2
|
+
import type { VerifiedLedgerEntry } from './ledger.js';
|
|
3
|
+
export declare const HISTORY_HORIZON = 393216;
|
|
4
|
+
export declare function controllerLogSize(events: ReadonlyArray<unknown>): number;
|
|
5
|
+
/** Count validated controller history. Callers apply the horizon only to lifecycle groups. */
|
|
6
|
+
export declare function historySize(tree: ClientState['ratchetTree'], entries: ReadonlyArray<VerifiedLedgerEntry>): number;
|
package/lib/history.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { defaultCredentialTypes, isDefaultCredential, nodeTypes } from 'ts-mls';
|
|
2
|
+
import { parseMLSCredentialIdentity } from './credential.js';
|
|
3
|
+
import { DEVICE_ENTRY_TYPE } from './registry.js';
|
|
4
|
+
export const HISTORY_HORIZON = 393_216;
|
|
5
|
+
const utf8 = new TextEncoder();
|
|
6
|
+
export function controllerLogSize(events) {
|
|
7
|
+
return events.reduce((total, event)=>total + utf8.encode(JSON.stringify(event)).length, 0);
|
|
8
|
+
}
|
|
9
|
+
/** Count validated controller history. Callers apply the horizon only to lifecycle groups. */ export function historySize(tree, entries) {
|
|
10
|
+
let size = 0;
|
|
11
|
+
for (const node of tree){
|
|
12
|
+
if (node == null || node.nodeType !== nodeTypes.leaf) continue;
|
|
13
|
+
const credential = node.leaf.credential;
|
|
14
|
+
if (!isDefaultCredential(credential) || credential.credentialType !== defaultCredentialTypes.basic) continue;
|
|
15
|
+
const binding = parseMLSCredentialIdentity(credential.identity).controller;
|
|
16
|
+
if (binding != null) size += controllerLogSize(binding.prefix);
|
|
17
|
+
}
|
|
18
|
+
for (const { entry } of entries){
|
|
19
|
+
if (entry.type !== DEVICE_ENTRY_TYPE || entry.value == null || typeof entry.value !== 'object') {
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
const proof = entry.value.proof;
|
|
23
|
+
if (Array.isArray(proof)) size += controllerLogSize(proof);
|
|
24
|
+
}
|
|
25
|
+
return size;
|
|
26
|
+
}
|