@kumiai/mls 0.9.0 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -0
- package/lib/anchor.d.ts +10 -4
- package/lib/anchor.js +26 -2
- package/lib/authentication.d.ts +11 -14
- package/lib/authentication.js +127 -86
- package/lib/capability.d.ts +37 -0
- package/lib/capability.js +141 -0
- package/lib/codec.js +2 -1
- package/lib/device-proof.d.ts +1 -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 +22 -35
- package/lib/group-commit.js +122 -103
- 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 +60 -24
- package/lib/group-handle.js +331 -77
- package/lib/group-info.d.ts +8 -0
- package/lib/group-info.js +29 -1
- package/lib/group-lifecycle.d.ts +32 -0
- package/lib/group-lifecycle.js +300 -0
- package/lib/group-membership.js +7 -3
- package/lib/group-welcome.d.ts +13 -4
- package/lib/group-welcome.js +113 -21
- package/lib/group.d.ts +3 -2
- package/lib/group.js +2 -1
- package/lib/history.d.ts +6 -0
- package/lib/history.js +26 -0
- package/lib/index.d.ts +10 -4
- package/lib/index.js +9 -3
- package/lib/lifecycle-proof.d.ts +24 -0
- package/lib/lifecycle-proof.js +193 -0
- package/lib/lifecycle.d.ts +44 -0
- package/lib/lifecycle.js +385 -0
- package/lib/policy.d.ts +20 -0
- package/lib/policy.js +8 -4
- 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/types.d.ts +13 -8
- package/lib/welcome-refs.d.ts +2 -1
- package/package.json +6 -6
package/lib/group-info.d.ts
CHANGED
|
@@ -10,6 +10,14 @@ import type { GroupHandle } from './group-handle.js';
|
|
|
10
10
|
* caught and treated as "not a message".
|
|
11
11
|
*/
|
|
12
12
|
export declare function readMessageEpoch(bytes: Uint8Array): bigint | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* Read an app PrivateMessage's cleartext authenticated data without an epoch key.
|
|
15
|
+
* This is an untrusted routing hint until decrypt authenticates the complete AAD.
|
|
16
|
+
* Total over arbitrary bytes: malformed or non-app frames return null.
|
|
17
|
+
*/
|
|
18
|
+
export declare function readMessageAAD(bytes: Uint8Array): Uint8Array | null;
|
|
19
|
+
/** Cleartext entry IDs are only a fetch hint; processMessage verifies every body. */
|
|
20
|
+
export declare function readCommitEntryIDs(bytes: Uint8Array): Array<string>;
|
|
13
21
|
export type InspectGroupInfoResult = {
|
|
14
22
|
/** The GroupInfo's epoch, read from its groupContext. */
|
|
15
23
|
epoch: bigint;
|
package/lib/group-info.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { createGroupInfoWithExternalPubAndRatchetTree, decode, encode, mlsMessageDecoder, mlsMessageEncoder, protocolVersions, wireformats } from 'ts-mls';
|
|
1
|
+
import { contentTypes, createGroupInfoWithExternalPubAndRatchetTree, decode, encode, mlsMessageDecoder, mlsMessageEncoder, protocolVersions, wireformats } from 'ts-mls';
|
|
2
2
|
import { GROUP_ANCHOR_EXTENSION_TYPE } from './anchor.js';
|
|
3
|
+
import { decodeControlEnvelope } from './envelope.js';
|
|
3
4
|
/**
|
|
4
5
|
* Read the MLS epoch from a framed message's cleartext header without decrypting.
|
|
5
6
|
* Advisory only — the header epoch is unauthenticated; use it to drop stale / buffer
|
|
@@ -26,6 +27,33 @@ import { GROUP_ANCHOR_EXTENSION_TYPE } from './anchor.js';
|
|
|
26
27
|
}
|
|
27
28
|
return undefined;
|
|
28
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* Read an app PrivateMessage's cleartext authenticated data without an epoch key.
|
|
32
|
+
* This is an untrusted routing hint until decrypt authenticates the complete AAD.
|
|
33
|
+
* Total over arbitrary bytes: malformed or non-app frames return null.
|
|
34
|
+
*/ export function readMessageAAD(bytes) {
|
|
35
|
+
try {
|
|
36
|
+
const message = decode(mlsMessageDecoder, bytes);
|
|
37
|
+
if (message?.wireformat !== wireformats.mls_private_message) return null;
|
|
38
|
+
const frame = message.privateMessage;
|
|
39
|
+
if (frame.contentType !== contentTypes.application) return null;
|
|
40
|
+
return frame.authenticatedData instanceof Uint8Array ? frame.authenticatedData : null;
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** Cleartext entry IDs are only a fetch hint; processMessage verifies every body. */ export function readCommitEntryIDs(bytes) {
|
|
46
|
+
try {
|
|
47
|
+
const message = decode(mlsMessageDecoder, bytes);
|
|
48
|
+
if (message?.wireformat !== wireformats.mls_private_message) return [];
|
|
49
|
+
const frame = message.privateMessage;
|
|
50
|
+
if (frame.contentType !== contentTypes.commit) return [];
|
|
51
|
+
const envelope = decodeControlEnvelope(frame.authenticatedData);
|
|
52
|
+
return envelope.ok ? envelope.envelope.entries ?? [] : [];
|
|
53
|
+
} catch {
|
|
54
|
+
return [];
|
|
55
|
+
}
|
|
56
|
+
}
|
|
29
57
|
/**
|
|
30
58
|
* Read a framed MLSMessage(GroupInfo)'s epoch and ratchet-tree hash without joining
|
|
31
59
|
* or mutating state. Used to confirm an external-resync Commit was canonically
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type SignedEvent } from '@kokuin/controller';
|
|
2
|
+
import { type ControllerBinding } from './credential.js';
|
|
3
|
+
import { type RevokeProofReason } from './errors.js';
|
|
4
|
+
import type { DeviceWriteResult } from './group-device.js';
|
|
5
|
+
import { type GroupHandle } from './group-handle.js';
|
|
6
|
+
export type RevokeBuildResult = {
|
|
7
|
+
status: 'built';
|
|
8
|
+
result: DeviceWriteResult;
|
|
9
|
+
} | {
|
|
10
|
+
status: 'already-revoked';
|
|
11
|
+
} | {
|
|
12
|
+
status: 'self-affected';
|
|
13
|
+
subject: string;
|
|
14
|
+
} | {
|
|
15
|
+
status: 'not-provable';
|
|
16
|
+
reason: RevokeProofReason;
|
|
17
|
+
};
|
|
18
|
+
export declare function renewLeaf(group: GroupHandle, binding: ControllerBinding): Promise<DeviceWriteResult>;
|
|
19
|
+
export type RemoveLapsedLeavesResult = {
|
|
20
|
+
removed: Array<string>;
|
|
21
|
+
/** Absent when no leaf had lapsed. */
|
|
22
|
+
result?: DeviceWriteResult;
|
|
23
|
+
};
|
|
24
|
+
export declare function removeLapsedLeaves(group: GroupHandle): Promise<RemoveLapsedLeavesResult>;
|
|
25
|
+
export type RevokeWithProofParams = {
|
|
26
|
+
subject: string;
|
|
27
|
+
log: Array<SignedEvent>;
|
|
28
|
+
} | {
|
|
29
|
+
reset: true;
|
|
30
|
+
log: Array<SignedEvent>;
|
|
31
|
+
};
|
|
32
|
+
export declare function revokeWithProof(group: GroupHandle, params: RevokeWithProofParams): Promise<RevokeBuildResult>;
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import { didFromInception, foldLog } from '@kokuin/controller';
|
|
2
|
+
import { createSigningIdentityForDID, normalizeDID } from '@kokuin/token';
|
|
3
|
+
import { defaultProposalTypes, encode, 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, verifyLifecycleProof } from './lifecycle-proof.js';
|
|
14
|
+
import { DEVICE_ENTRY_TYPE } from './registry.js';
|
|
15
|
+
function ownIdentity(group) {
|
|
16
|
+
const leaf = leafAt(group.state.ratchetTree, group.state.privatePath.leafIndex);
|
|
17
|
+
if (leaf == null || !('identity' in leaf.credential)) throw new LeafBindingError('identity-change');
|
|
18
|
+
const parsed = parseMLSCredentialIdentity(leaf.credential.identity);
|
|
19
|
+
return createSigningIdentityForDID(parsed.longForm ?? parsed.id, group.state.signaturePrivateKey);
|
|
20
|
+
}
|
|
21
|
+
async function clockEntries(group, tree) {
|
|
22
|
+
const controller = group.anchor.controller;
|
|
23
|
+
if (controller == null) return [];
|
|
24
|
+
const before = treeTime(group, controller);
|
|
25
|
+
let after = group.registry.controllers.get(normalizeDID(controller))?.timeFloor ?? 0;
|
|
26
|
+
for (const node of tree){
|
|
27
|
+
if (node?.nodeType !== nodeTypes.leaf || !('identity' in node.leaf.credential)) continue;
|
|
28
|
+
const binding = parseMLSCredentialIdentity(node.leaf.credential.identity).controller;
|
|
29
|
+
if (binding == null || normalizeDID(binding.id) !== normalizeDID(controller)) continue;
|
|
30
|
+
const payload = readCapability(binding.capability).payload;
|
|
31
|
+
const parent = Array.isArray(payload.cap) ? payload.cap[0] : payload.cap;
|
|
32
|
+
after = Math.max(after, parent == null ? payload.iat : readCapability(parent).payload.iat);
|
|
33
|
+
}
|
|
34
|
+
if (after >= before) return [];
|
|
35
|
+
return [
|
|
36
|
+
await signLedgerEntry(ownIdentity(group), {
|
|
37
|
+
type: DEVICE_ENTRY_TYPE,
|
|
38
|
+
groupID: group.groupID,
|
|
39
|
+
subject: controller,
|
|
40
|
+
value: {
|
|
41
|
+
op: 'clock',
|
|
42
|
+
time: before
|
|
43
|
+
}
|
|
44
|
+
})
|
|
45
|
+
];
|
|
46
|
+
}
|
|
47
|
+
async function buildResult(params) {
|
|
48
|
+
const { group, proposals, tokens, commitState } = params;
|
|
49
|
+
const result = await commitWithEntries({
|
|
50
|
+
group,
|
|
51
|
+
extraProposals: proposals,
|
|
52
|
+
enacted: tokens,
|
|
53
|
+
requireAdmin: false,
|
|
54
|
+
commitState
|
|
55
|
+
});
|
|
56
|
+
// MLS captured the replacement tree as historical data when building a renewal.
|
|
57
|
+
const historical = result.newState.historicalReceiverData.get(group.epoch);
|
|
58
|
+
if (historical != null && commitState != null) historical.ratchetTree = group.state.ratchetTree;
|
|
59
|
+
const newGroup = deriveGroup(group, result.newState);
|
|
60
|
+
await newGroup.applyLedgerEntries(tokens);
|
|
61
|
+
return {
|
|
62
|
+
commitMessage: encode(mlsMessageEncoder, result.commit),
|
|
63
|
+
newGroup,
|
|
64
|
+
epoch: newGroup.epoch
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
export async function renewLeaf(group, binding) {
|
|
68
|
+
return mutexFor(group).run(async ()=>{
|
|
69
|
+
assertBindingAuthorTime(binding);
|
|
70
|
+
const index = group.state.privatePath.leafIndex * 2;
|
|
71
|
+
const tree = group.state.ratchetTree.slice();
|
|
72
|
+
const original = tree[index];
|
|
73
|
+
if (original?.nodeType !== nodeTypes.leaf || !('identity' in original.leaf.credential)) throw new LeafBindingError('identity-change');
|
|
74
|
+
const own = structuredClone(original);
|
|
75
|
+
if (!('identity' in own.leaf.credential)) throw new LeafBindingError('identity-change');
|
|
76
|
+
const parsed = parseMLSCredentialIdentity(own.leaf.credential.identity);
|
|
77
|
+
own.leaf.credential.identity = new TextEncoder().encode(JSON.stringify({
|
|
78
|
+
v: 1,
|
|
79
|
+
...parsed,
|
|
80
|
+
controller: binding
|
|
81
|
+
}));
|
|
82
|
+
tree[index] = own;
|
|
83
|
+
await validateEntry(group, own.leaf, original.leaf);
|
|
84
|
+
if (group.anchor.controller != null) {
|
|
85
|
+
const entries = group.ledger.map(({ verified })=>verified);
|
|
86
|
+
const before = historySize(group.state.ratchetTree, entries);
|
|
87
|
+
const after = historySize(tree, entries);
|
|
88
|
+
if (after > HISTORY_HORIZON && after > before) throw new LeafBindingError('history-horizon');
|
|
89
|
+
}
|
|
90
|
+
const tokens = await clockEntries(group, tree);
|
|
91
|
+
return buildResult({
|
|
92
|
+
group,
|
|
93
|
+
proposals: [],
|
|
94
|
+
tokens,
|
|
95
|
+
commitState: {
|
|
96
|
+
...group.state,
|
|
97
|
+
ratchetTree: tree
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
export async function removeLapsedLeaves(group) {
|
|
103
|
+
return mutexFor(group).run(async ()=>{
|
|
104
|
+
const removed = [];
|
|
105
|
+
const proposals = [];
|
|
106
|
+
const tree = group.state.ratchetTree.slice();
|
|
107
|
+
for (const member of group.listMembers()){
|
|
108
|
+
const leaf = leafAt(tree, member.leafIndex);
|
|
109
|
+
if (leaf == null || !isLapsed(group, leaf)) continue;
|
|
110
|
+
removed.push(member.id);
|
|
111
|
+
tree[member.leafIndex * 2] = undefined;
|
|
112
|
+
proposals.push({
|
|
113
|
+
proposalType: defaultProposalTypes.remove,
|
|
114
|
+
remove: {
|
|
115
|
+
removed: member.leafIndex
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
if (removed.length === 0) return {
|
|
120
|
+
removed
|
|
121
|
+
};
|
|
122
|
+
const tokens = await clockEntries(group, tree);
|
|
123
|
+
return {
|
|
124
|
+
removed,
|
|
125
|
+
result: await buildResult({
|
|
126
|
+
group,
|
|
127
|
+
proposals,
|
|
128
|
+
tokens
|
|
129
|
+
})
|
|
130
|
+
};
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
/** The slice of `log` a receiver needs on top of the controller events it already recorded. */ function proofFor(params) {
|
|
134
|
+
const { group, log, subject, reset } = params;
|
|
135
|
+
const controller = group.anchor.controller;
|
|
136
|
+
if (controller == null) throw new RevokeProofError('wrong-controller');
|
|
137
|
+
if (log.length === 0) throw new RevokeProofError('no-rev');
|
|
138
|
+
const first = log[0];
|
|
139
|
+
if (first?.event.t === 'icp') {
|
|
140
|
+
let did;
|
|
141
|
+
try {
|
|
142
|
+
did = didFromInception(first.event);
|
|
143
|
+
} catch (cause) {
|
|
144
|
+
const rejection = new RevokeProofError('not-authority-signed');
|
|
145
|
+
rejection.cause = cause;
|
|
146
|
+
throw rejection;
|
|
147
|
+
}
|
|
148
|
+
if (normalizeDID(did) !== normalizeDID(controller)) throw new RevokeProofError('wrong-controller');
|
|
149
|
+
}
|
|
150
|
+
if (log.some(({ event })=>event.t !== 'icp' && event.i !== controller)) throw new RevokeProofError('wrong-controller');
|
|
151
|
+
const folded = foldLog(controller, log);
|
|
152
|
+
if (!folded.ok) {
|
|
153
|
+
const detached = /sequence|digest|prior|inception must/.test(folded.reason);
|
|
154
|
+
throw new RevokeProofError(detached ? 'detached' : 'not-authority-signed');
|
|
155
|
+
}
|
|
156
|
+
// Drop events that leave the folded state unchanged.
|
|
157
|
+
const advancing = log.filter((_, index)=>index === 0 || folded.states[index]?.digest !== folded.states[index - 1]?.digest);
|
|
158
|
+
const canonical = foldLog(controller, advancing);
|
|
159
|
+
if (!canonical.ok) throw new RevokeProofError('not-authority-signed');
|
|
160
|
+
let resetIndex = -1;
|
|
161
|
+
for(let index = 1; index < advancing.length; index++){
|
|
162
|
+
if (advancing[index]?.event.g !== advancing[index - 1]?.event.g) resetIndex = index;
|
|
163
|
+
}
|
|
164
|
+
const projection = group.registry.controllers.get(normalizeDID(controller));
|
|
165
|
+
const recorded = projection?.recordedLog ?? [];
|
|
166
|
+
const floor = projection?.genFloor ?? 0;
|
|
167
|
+
if (reset) {
|
|
168
|
+
if (resetIndex < 0) throw new RevokeProofError('no-rev');
|
|
169
|
+
return [
|
|
170
|
+
advancing[0],
|
|
171
|
+
...advancing.slice(resetIndex)
|
|
172
|
+
];
|
|
173
|
+
}
|
|
174
|
+
const recordedFold = foldLog(controller, recorded);
|
|
175
|
+
const recordedHead = recordedFold.ok ? recordedFold.states.at(-1) : undefined;
|
|
176
|
+
const generation = canonical.states.at(-1)?.gen ?? 0;
|
|
177
|
+
if (recorded.length > 0 && generation > (recordedHead?.gen ?? floor)) throw new RevokeProofError('needs-reset');
|
|
178
|
+
const start = recorded.length === 0 ? Math.max(1, resetIndex) : 1;
|
|
179
|
+
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);
|
|
180
|
+
if (end < 0) {
|
|
181
|
+
if (generation < floor) throw new RevokeProofError('generation-floor');
|
|
182
|
+
throw new RevokeProofError('no-rev');
|
|
183
|
+
}
|
|
184
|
+
if (recorded.length === 0) {
|
|
185
|
+
return [
|
|
186
|
+
advancing[0],
|
|
187
|
+
...advancing.slice(start, end + 1)
|
|
188
|
+
];
|
|
189
|
+
}
|
|
190
|
+
const headIndex = canonical.states.findIndex(({ digest })=>digest === recordedHead?.digest);
|
|
191
|
+
if (headIndex < 0) throw new RevokeProofError('detached');
|
|
192
|
+
end = Math.max(headIndex, end);
|
|
193
|
+
return advancing.slice(headIndex + 1, end + 1);
|
|
194
|
+
}
|
|
195
|
+
/** Revoked in the registry, with no leaf of its own and no leaf it issued left in the tree. */ function isFullyRevoked(group, subject) {
|
|
196
|
+
if (group.registry.devices.get(subject)?.status !== 'revoked') return false;
|
|
197
|
+
if (group.findMemberLeafIndex(subject) != null) return false;
|
|
198
|
+
return !group.listMembers().some((member)=>{
|
|
199
|
+
const capability = group.bindingOfDID(member.id)?.capability;
|
|
200
|
+
return capability != null && normalizeDID(readCapability(capability).payload.iss) === subject;
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
export async function revokeWithProof(group, params) {
|
|
204
|
+
return mutexFor(group).run(async ()=>{
|
|
205
|
+
try {
|
|
206
|
+
const controller = group.anchor.controller;
|
|
207
|
+
if (controller == null) throw new RevokeProofError('wrong-controller');
|
|
208
|
+
const reset = 'reset' in params;
|
|
209
|
+
const subject = normalizeDID(reset ? controller : params.subject);
|
|
210
|
+
if (!reset && isFullyRevoked(group, subject)) return {
|
|
211
|
+
status: 'already-revoked'
|
|
212
|
+
};
|
|
213
|
+
const value = {
|
|
214
|
+
op: reset ? 'reset' : 'revoke',
|
|
215
|
+
proof: proofFor({
|
|
216
|
+
group,
|
|
217
|
+
log: params.log,
|
|
218
|
+
subject,
|
|
219
|
+
reset
|
|
220
|
+
}),
|
|
221
|
+
revoked: []
|
|
222
|
+
};
|
|
223
|
+
const verified = {
|
|
224
|
+
issuer: group.credential.id,
|
|
225
|
+
entry: {
|
|
226
|
+
type: DEVICE_ENTRY_TYPE,
|
|
227
|
+
groupID: group.groupID,
|
|
228
|
+
subject,
|
|
229
|
+
value
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
const authenticated = authenticateLifecycleProof(controller, verified, group.registry);
|
|
233
|
+
const revoked = reset ? [] : [
|
|
234
|
+
{
|
|
235
|
+
did: subject
|
|
236
|
+
}
|
|
237
|
+
];
|
|
238
|
+
const leaves = group.listMembers().map((member)=>{
|
|
239
|
+
const binding = group.bindingOfDID(member.id);
|
|
240
|
+
const payload = binding?.capability == null ? undefined : readCapability(binding.capability).payload;
|
|
241
|
+
const folded = binding?.prefix == null ? undefined : foldLog(controller, binding.prefix);
|
|
242
|
+
return {
|
|
243
|
+
...member,
|
|
244
|
+
issuer: payload?.cap == null ? undefined : normalizeDID(payload.iss),
|
|
245
|
+
generation: folded?.ok ? folded.states.at(-1)?.gen : undefined
|
|
246
|
+
};
|
|
247
|
+
});
|
|
248
|
+
if (reset) for (const leaf of leaves){
|
|
249
|
+
if (leaf.generation != null && leaf.generation < authenticated.genFloor) revoked.push({
|
|
250
|
+
did: normalizeDID(leaf.id)
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
const direct = new Set(revoked.map(({ did })=>did));
|
|
254
|
+
for (const leaf of leaves){
|
|
255
|
+
if (leaf.issuer != null && direct.has(leaf.issuer) && !direct.has(normalizeDID(leaf.id))) revoked.push({
|
|
256
|
+
did: normalizeDID(leaf.id),
|
|
257
|
+
cascadedFrom: leaf.issuer
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
value.revoked = revoked;
|
|
261
|
+
if (revoked.some(({ did })=>did === normalizeDID(group.credential.id))) return {
|
|
262
|
+
status: 'self-affected',
|
|
263
|
+
subject: group.credential.id
|
|
264
|
+
};
|
|
265
|
+
const effects = await verifyLifecycleProof(group, verified);
|
|
266
|
+
const tree = group.state.ratchetTree.slice();
|
|
267
|
+
const proposals = effects.removeLeafIndices.map((removed)=>{
|
|
268
|
+
tree[removed * 2] = undefined;
|
|
269
|
+
return {
|
|
270
|
+
proposalType: defaultProposalTypes.remove,
|
|
271
|
+
remove: {
|
|
272
|
+
removed
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
});
|
|
276
|
+
const tokens = [
|
|
277
|
+
await signLedgerEntry(ownIdentity(group), verified.entry),
|
|
278
|
+
...await clockEntries(group, tree)
|
|
279
|
+
];
|
|
280
|
+
return {
|
|
281
|
+
status: 'built',
|
|
282
|
+
result: await buildResult({
|
|
283
|
+
group,
|
|
284
|
+
proposals,
|
|
285
|
+
tokens
|
|
286
|
+
})
|
|
287
|
+
};
|
|
288
|
+
} catch (error) {
|
|
289
|
+
if (error instanceof RevokeProofError) return {
|
|
290
|
+
status: 'not-provable',
|
|
291
|
+
reason: error.reason
|
|
292
|
+
};
|
|
293
|
+
if (error instanceof LeafBindingError && error.reason === 'history-horizon') return {
|
|
294
|
+
status: 'not-provable',
|
|
295
|
+
reason: 'too-large'
|
|
296
|
+
};
|
|
297
|
+
throw error;
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
}
|
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,6 +1,8 @@
|
|
|
1
1
|
import { type OwnIdentity } from '@kokuin/token';
|
|
2
|
-
import type
|
|
2
|
+
import { type ClientState, type Welcome } from 'ts-mls';
|
|
3
|
+
import { type ControllerBinding, type MemberCredential } from './credential.js';
|
|
3
4
|
import { GroupHandle } from './group-handle.js';
|
|
5
|
+
import type { DeviceRegistry } from './registry.js';
|
|
4
6
|
import type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
|
|
5
7
|
export type ProcessWelcomeResult = {
|
|
6
8
|
group: GroupHandle;
|
|
@@ -10,9 +12,8 @@ export type ProcessWelcomeParams = {
|
|
|
10
12
|
identity: OwnIdentity;
|
|
11
13
|
invite: Invite;
|
|
12
14
|
/** Wire-form framed MLSMessage(Welcome) bytes (preferred), or a pre-decoded
|
|
13
|
-
* ts-mls Welcome object (legacy).
|
|
14
|
-
|
|
15
|
-
welcome: Uint8Array | unknown;
|
|
15
|
+
* ts-mls Welcome object (legacy). */
|
|
16
|
+
welcome: Uint8Array | Welcome;
|
|
16
17
|
keyPackageBundle: KeyPackageBundle;
|
|
17
18
|
ratchetTree?: unknown;
|
|
18
19
|
options?: GroupOptions;
|
|
@@ -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) {
|
|
@@ -42,6 +36,10 @@ export async function processWelcome(params) {
|
|
|
42
36
|
ratchetTree: sanitizedTree
|
|
43
37
|
}
|
|
44
38
|
});
|
|
39
|
+
const joinedLeaf = state.ratchetTree[state.privatePath.leafIndex * 2];
|
|
40
|
+
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)) {
|
|
41
|
+
throw new Error('processWelcome: the joined leaf does not name the invite recipient');
|
|
42
|
+
}
|
|
45
43
|
const credential = {
|
|
46
44
|
id: identity.id,
|
|
47
45
|
groupID: invite.groupID
|
|
@@ -66,7 +64,16 @@ export async function processWelcome(params) {
|
|
|
66
64
|
// Fold the invite's entries: the roster is seeded from the anchor and the fold grants
|
|
67
65
|
// authority only to an admin-so-far, so a member-signed entry cannot promote anyone
|
|
68
66
|
// even though applyLedgerEntries itself is the permissive primitive.
|
|
67
|
+
if (group.anchor.controller == null) {
|
|
68
|
+
let namesSelf = false;
|
|
69
|
+
for (const token of invite.ledgerEntries){
|
|
70
|
+
const verified = await verifyLedgerEntry(token);
|
|
71
|
+
if (verified?.entry.type === ROLE_ENTRY_TYPE && verified.entry.groupID === invite.groupID && normalizeDID(verified.entry.subject) === normalizeDID(identity.id)) namesSelf = true;
|
|
72
|
+
}
|
|
73
|
+
if (!namesSelf) throw new Error('processWelcome: the invite carries no role entry naming this identity');
|
|
74
|
+
}
|
|
69
75
|
await group.applyLedgerEntries(invite.ledgerEntries);
|
|
76
|
+
await validateWelcomeTree(group);
|
|
70
77
|
return {
|
|
71
78
|
group,
|
|
72
79
|
credential
|
|
@@ -101,7 +108,7 @@ export async function processWelcome(params) {
|
|
|
101
108
|
return result;
|
|
102
109
|
}
|
|
103
110
|
export async function joinGroupExternal(params) {
|
|
104
|
-
const { identity, groupInfo: groupInfoBytes, credential, resync, options, authenticatedData } = params;
|
|
111
|
+
const { identity, groupInfo: groupInfoBytes, credential, resync, options, authenticatedData, controller, ledgerEntries } = params;
|
|
105
112
|
// Resync replaces the caller's own prior leaf, so the rejoining identity must match
|
|
106
113
|
// the presented credential. A friendly precheck, not the security boundary: on a
|
|
107
114
|
// mismatch ts-mls rejects the external commit downstream anyway. Eviction
|
|
@@ -110,7 +117,6 @@ export async function joinGroupExternal(params) {
|
|
|
110
117
|
if (normalizeDID(identity.id) !== normalizeDID(credential.id)) {
|
|
111
118
|
throw new Error(`joinGroupExternal: identity.id (${identity.id}) must match credential.id (${credential.id}) for resync`);
|
|
112
119
|
}
|
|
113
|
-
const context = await resolveMlsContext(options);
|
|
114
120
|
const message = decode(mlsMessageDecoder, groupInfoBytes);
|
|
115
121
|
if (message == null) {
|
|
116
122
|
throw new Error('Invalid groupInfo: failed to decode MLSMessage');
|
|
@@ -127,11 +133,36 @@ export async function joinGroupExternal(params) {
|
|
|
127
133
|
if (offeredGroupID !== credential.groupID) {
|
|
128
134
|
throw new Error(`joinGroupExternal: groupInfo names group ${offeredGroupID}, not credential.groupID (${credential.groupID})`);
|
|
129
135
|
}
|
|
136
|
+
const anchorExtension = groupInfo.groupContext.extensions.find((extension)=>extension.extensionType === GROUP_ANCHOR_EXTENSION_TYPE);
|
|
137
|
+
const anchor = anchorExtension?.extensionData instanceof Uint8Array ? decodeGroupAnchor(anchorExtension.extensionData) : null;
|
|
138
|
+
if (anchor == null) throw new Error('joinGroupExternal: the group has no valid anchor');
|
|
139
|
+
const context = await resolveMlsContext(options, anchor);
|
|
140
|
+
const originalCredentials = [];
|
|
141
|
+
const joinContext = {
|
|
142
|
+
...context,
|
|
143
|
+
authService: {
|
|
144
|
+
async validateCredential (leafCredential, signaturePublicKey) {
|
|
145
|
+
if (!isDefaultCredential(leafCredential) || leafCredential.credentialType !== defaultCredentialTypes.basic) return false;
|
|
146
|
+
const parsed = parseMLSCredentialIdentity(leafCredential.identity);
|
|
147
|
+
if (anchor.controller != null && parsed.controller == null) throw new LeafBindingError('floating-refused');
|
|
148
|
+
if (anchor.controller != null && parsed.controller != null && normalizeDID(parsed.controller.id) !== normalizeDID(anchor.controller)) throw new LeafBindingError('controller-mismatch');
|
|
149
|
+
await verifyLeafCredential(leafCredential, signaturePublicKey, {
|
|
150
|
+
leafLifetime: ()=>anchor.controller == null ? undefined : anchor.leafLifetime ?? 86_400,
|
|
151
|
+
trustedGrantLifetime: ()=>anchor.controller == null ? undefined : anchor.trustedGrantLifetime ?? 2_592_000
|
|
152
|
+
});
|
|
153
|
+
originalCredentials.push({
|
|
154
|
+
credential: leafCredential,
|
|
155
|
+
signaturePublicKey
|
|
156
|
+
});
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
};
|
|
130
161
|
// The rejoining leaf must advertise every GroupContext extension the group uses, or
|
|
131
162
|
// ts-mls rejects the external join. Derive them from the GroupInfo being resynced
|
|
132
163
|
// against, honoring an explicit capabilities override.
|
|
133
164
|
const keyPackage = await generateKeyPackageWithKey({
|
|
134
|
-
credential: makeMLSCredential(identity),
|
|
165
|
+
credential: makeMLSCredential(identity, controller),
|
|
135
166
|
signatureKeyPair: {
|
|
136
167
|
signKey: identity.privateKey,
|
|
137
168
|
publicKey: identity.publicKey
|
|
@@ -140,7 +171,7 @@ export async function joinGroupExternal(params) {
|
|
|
140
171
|
capabilities: buildLeafCapabilities(groupInfo.groupContext.extensions, options?.capabilities)
|
|
141
172
|
});
|
|
142
173
|
const { publicMessage, newState } = await mlsJoinGroupExternal({
|
|
143
|
-
context,
|
|
174
|
+
context: joinContext,
|
|
144
175
|
groupInfo,
|
|
145
176
|
keyPackage: keyPackage.publicPackage,
|
|
146
177
|
privateKeys: keyPackage.privatePackage,
|
|
@@ -163,8 +194,69 @@ export async function joinGroupExternal(params) {
|
|
|
163
194
|
resolveLedgerEntries: options?.resolveLedgerEntries,
|
|
164
195
|
onLedgerEntries: options?.onLedgerEntries
|
|
165
196
|
});
|
|
197
|
+
const ownIndex = newState.privatePath.leafIndex;
|
|
198
|
+
const own = newState.ratchetTree[ownIndex * 2];
|
|
199
|
+
const previous = originalCredentials.find(({ credential: candidate })=>isDefaultCredential(candidate) && candidate.credentialType === defaultCredentialTypes.basic && normalizeDID(parseMLSCredentialIdentity(candidate.identity).id) === normalizeDID(identity.id));
|
|
200
|
+
if (own?.nodeType !== nodeTypes.leaf || previous == null) throw new LeafBindingError('identity-change');
|
|
201
|
+
// Only the replaced leaf's credential and key affect the lifecycle predicates.
|
|
202
|
+
if (publicMessage.content.contentType !== contentTypes.commit) throw new Error('Expected external commit');
|
|
203
|
+
const proposals = publicMessage.content.commit.proposals.map((proposal)=>{
|
|
204
|
+
if (proposal.proposalOrRefType !== proposalOrRefTypes.proposal) throw new Error('Expected inline proposal');
|
|
205
|
+
return {
|
|
206
|
+
proposal: proposal.proposal,
|
|
207
|
+
senderLeafIndex: ownIndex
|
|
208
|
+
};
|
|
209
|
+
});
|
|
210
|
+
const removed = proposals.find(({ proposal })=>isDefaultProposal(proposal) && proposal.proposalType === defaultProposalTypes.remove)?.proposal;
|
|
211
|
+
if (removed == null || !isDefaultProposal(removed) || removed.proposalType !== defaultProposalTypes.remove) throw new Error('Missing replacement target');
|
|
212
|
+
const beforeTree = newState.ratchetTree.slice();
|
|
213
|
+
beforeTree[ownIndex * 2] = undefined;
|
|
214
|
+
beforeTree[removed.remove.removed * 2] = {
|
|
215
|
+
...own,
|
|
216
|
+
leaf: {
|
|
217
|
+
...own.leaf,
|
|
218
|
+
...previous
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
const before = new GroupHandle({
|
|
222
|
+
state: {
|
|
223
|
+
...newState,
|
|
224
|
+
ratchetTree: beforeTree,
|
|
225
|
+
groupContext: groupInfo.groupContext
|
|
226
|
+
},
|
|
227
|
+
credential,
|
|
228
|
+
context: await resolveMlsContext(options, anchor)
|
|
229
|
+
});
|
|
230
|
+
if (ledgerEntries != null) {
|
|
231
|
+
await before.bootstrapLedger(ledgerEntries);
|
|
232
|
+
await group.bootstrapLedger(ledgerEntries);
|
|
233
|
+
}
|
|
234
|
+
await params.beforeBinding?.(group, before);
|
|
235
|
+
if (anchor.controller != null && controller == null) throw new LeafBindingError('floating-refused');
|
|
236
|
+
assertBindingAuthorTime(controller);
|
|
237
|
+
const gate = await prepareLifecycleGate({
|
|
238
|
+
group: before,
|
|
239
|
+
entries: [],
|
|
240
|
+
candidateRegistry: before.registry,
|
|
241
|
+
context: buildCommitPolicyContext(before, {
|
|
242
|
+
baseRoster: before.roster,
|
|
243
|
+
candidateRoster: before.roster,
|
|
244
|
+
entryIDs: [],
|
|
245
|
+
enactedDeviceEntries: []
|
|
246
|
+
}),
|
|
247
|
+
externalLeaf: own.leaf
|
|
248
|
+
});
|
|
249
|
+
gate.check({
|
|
250
|
+
kind: 'commit',
|
|
251
|
+
senderLeafIndex: undefined,
|
|
252
|
+
proposals
|
|
253
|
+
});
|
|
254
|
+
await gate.postApply(newState);
|
|
255
|
+
await validateWelcomeTree(group);
|
|
166
256
|
return {
|
|
167
257
|
commitMessage,
|
|
168
|
-
group
|
|
258
|
+
group,
|
|
259
|
+
sourceTree: beforeTree,
|
|
260
|
+
sourceRegistry: before.registry
|
|
169
261
|
};
|
|
170
262
|
}
|
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';
|
|
6
|
-
export { type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, type GroupInfoBinding, type InspectGroupInfoResult, inspectGroupInfo, readGroupInfoBinding, readMessageEpoch, } from './group-info.js';
|
|
5
|
+
export { CommitRejectedError, GroupHandle, type GroupHandleEvents, type GroupHandleParams, type HeldLedgerEntry, type LedgerLogEntry, type SendAdmission, } from './group-handle.js';
|
|
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';
|