@kumiai/mls 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/group-commit.d.ts +100 -0
- package/lib/group-commit.js +252 -0
- package/lib/group-context.d.ts +11 -0
- package/lib/group-context.js +33 -0
- package/lib/group-create.d.ts +19 -0
- package/lib/group-create.js +85 -0
- package/lib/group-credential.d.ts +6 -0
- package/lib/group-credential.js +39 -0
- package/lib/group-handle.d.ts +196 -0
- package/lib/group-handle.js +691 -0
- package/lib/group-info.d.ts +57 -0
- package/lib/group-info.js +85 -0
- package/lib/group-membership.d.ts +25 -0
- package/lib/group-membership.js +36 -0
- package/lib/group-welcome.d.ts +67 -0
- package/lib/group-welcome.js +178 -0
- package/lib/group.d.ts +7 -339
- package/lib/group.js +7 -1194
- package/lib/head.d.ts +35 -38
- package/lib/head.js +43 -48
- package/lib/index.d.ts +3 -2
- package/lib/index.js +3 -2
- package/lib/recovery.d.ts +227 -0
- package/lib/recovery.js +456 -0
- package/lib/sender-data.d.ts +24 -0
- package/lib/sender-data.js +99 -0
- package/package.json +1 -1
package/lib/recovery.js
ADDED
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
import { decodeMultibase, encodeMultibase, isVerifiedToken, normalizeDID, stringifyToken, verifyToken } from '@kokuin/token';
|
|
2
|
+
import { sha256 } from '@noble/hashes/sha2.js';
|
|
3
|
+
import { readGroupAnchorExtension } from './anchor.js';
|
|
4
|
+
import { exportGroupInfo, inspectGroupInfo, readGroupInfoBinding } from './group.js';
|
|
5
|
+
const utf8 = new TextEncoder();
|
|
6
|
+
/** `type` tag on every recovery-request token. Domain-separates it, so a token
|
|
7
|
+
* minted for another purpose can never pose as a request for group state. */ export const RECOVERY_REQUEST_TYPE = 'group.recovery-request';
|
|
8
|
+
/** `type` tag on a responder's GroupInfo attestation. Domain-separates the
|
|
9
|
+
* membership proof, so no token minted elsewhere can stand in for it. */ export const RECOVERY_GROUPINFO_TYPE = 'group.recovery-groupinfo';
|
|
10
|
+
/** The only sealed-reply format this build produces or opens. */ export const SEALED_GROUP_INFO_VERSION = 1;
|
|
11
|
+
/** The sealed ledger reply shares the frame — `[version][enc][ct]` — and nothing
|
|
12
|
+
* else: see {@link LEDGER_REPLY}. */ export const SEALED_LEDGER_VERSION = 1;
|
|
13
|
+
/** X25519 KEM output / public-key length. The only KEM this provider supports, so
|
|
14
|
+
* `enc` is fixed-width and the sealed frame needs no length prefix. */ const KEM_OUTPUT_LENGTH = 32;
|
|
15
|
+
/** X25519 secret-key length. Same 32 bytes as the KEM output, but a DISTINCT
|
|
16
|
+
* invariant: this is the requester's OWN retained key, not a wire field. A wrong
|
|
17
|
+
* length is a host storage fault (corrupt/truncated own key), not a reply for
|
|
18
|
+
* someone else, and must NOT be swallowed as {@link openSealedReply}'s benign
|
|
19
|
+
* `not-for-me` verdict. */ const KEM_PRIVATE_KEY_LENGTH = 32;
|
|
20
|
+
/** Version byte + `enc` + a bare AEAD tag: the shortest well-formed reply. */ const MIN_SEALED_LENGTH = 1 + KEM_OUTPUT_LENGTH + 16;
|
|
21
|
+
const GROUP_INFO_REPLY = {
|
|
22
|
+
hpkeInfo: utf8.encode('kumiai/mls/recovery/v1'),
|
|
23
|
+
aadDomain: utf8.encode('kumiai/mls/recovery-aad/v1'),
|
|
24
|
+
version: SEALED_GROUP_INFO_VERSION,
|
|
25
|
+
fail: (reason, message)=>new SealedGroupInfoError(reason, message)
|
|
26
|
+
};
|
|
27
|
+
const LEDGER_REPLY = {
|
|
28
|
+
hpkeInfo: utf8.encode('kumiai/mls/recovery-ledger/v1'),
|
|
29
|
+
aadDomain: utf8.encode('kumiai/mls/recovery-ledger-aad/v1'),
|
|
30
|
+
version: SEALED_LEDGER_VERSION,
|
|
31
|
+
fail: (reason, message)=>new SealedLedgerError(reason, message)
|
|
32
|
+
};
|
|
33
|
+
/** Thrown by {@link sealGroupInfo}. The primitive refuses loudly rather than
|
|
34
|
+
* returning an empty reply; a responder that wants to stay silent catches this. */ export class RecoveryRequestError extends Error {
|
|
35
|
+
#reason;
|
|
36
|
+
constructor(reason, message){
|
|
37
|
+
super(message);
|
|
38
|
+
this.name = 'RecoveryRequestError';
|
|
39
|
+
this.#reason = reason;
|
|
40
|
+
}
|
|
41
|
+
get reason() {
|
|
42
|
+
return this.#reason;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** Thrown by {@link openSealedGroupInfo}. Distinguishes "not addressed to me" from
|
|
46
|
+
* "corrupt", so a peer sifting a shared lane drops the former quietly. */ export class SealedGroupInfoError extends Error {
|
|
47
|
+
#reason;
|
|
48
|
+
constructor(reason, message){
|
|
49
|
+
super(message);
|
|
50
|
+
this.name = 'SealedGroupInfoError';
|
|
51
|
+
this.#reason = reason;
|
|
52
|
+
}
|
|
53
|
+
get reason() {
|
|
54
|
+
return this.#reason;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/** Thrown by {@link openSealedLedger}, read like its GroupInfo sibling: a requester
|
|
58
|
+
* sifting a shared lane drops `not-for-me` quietly (every other member's reply to
|
|
59
|
+
* every other request looks like this) and shouts about `malformed`. */ export class SealedLedgerError extends Error {
|
|
60
|
+
#reason;
|
|
61
|
+
constructor(reason, message){
|
|
62
|
+
super(message);
|
|
63
|
+
this.name = 'SealedLedgerError';
|
|
64
|
+
this.#reason = reason;
|
|
65
|
+
}
|
|
66
|
+
get reason() {
|
|
67
|
+
return this.#reason;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** 4-byte big-endian length prefix before a field's UTF-8 bytes, so no two
|
|
71
|
+
* distinct field triples can encode to the same AAD. */ function frameField(value) {
|
|
72
|
+
const bytes = utf8.encode(value);
|
|
73
|
+
const framed = new Uint8Array(4 + bytes.length);
|
|
74
|
+
new DataView(framed.buffer).setUint32(0, bytes.length, false);
|
|
75
|
+
framed.set(bytes, 4);
|
|
76
|
+
return framed;
|
|
77
|
+
}
|
|
78
|
+
function concat(parts) {
|
|
79
|
+
let length = 0;
|
|
80
|
+
for (const part of parts)length += part.length;
|
|
81
|
+
const out = new Uint8Array(length);
|
|
82
|
+
let offset = 0;
|
|
83
|
+
for (const part of parts){
|
|
84
|
+
out.set(part, offset);
|
|
85
|
+
offset += part.length;
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
function bytesEqual(a, b) {
|
|
90
|
+
if (a.length !== b.length) return false;
|
|
91
|
+
for(let i = 0; i < a.length; i++){
|
|
92
|
+
if (a[i] !== b[i]) return false;
|
|
93
|
+
}
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
/** The sealed GroupInfo plaintext: `[len(4)][attestation token][GroupInfo bytes]`,
|
|
97
|
+
* big-endian length. Proof and vouched-for GroupInfo are sealed under one AEAD;
|
|
98
|
+
* neither can be lifted from the other. */ function frameAttestedGroupInfo(attestation, groupInfo) {
|
|
99
|
+
const token = utf8.encode(attestation);
|
|
100
|
+
const out = new Uint8Array(4 + token.length + groupInfo.length);
|
|
101
|
+
new DataView(out.buffer).setUint32(0, token.length, false);
|
|
102
|
+
out.set(token, 4);
|
|
103
|
+
out.set(groupInfo, 4 + token.length);
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
function unframeAttestedGroupInfo(bytes) {
|
|
107
|
+
if (bytes.length < 4) throw new Error('attested GroupInfo frame is truncated');
|
|
108
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
109
|
+
const length = view.getUint32(0, false);
|
|
110
|
+
if (4 + length > bytes.length) throw new Error('attested GroupInfo frame is truncated');
|
|
111
|
+
return {
|
|
112
|
+
attestation: new TextDecoder().decode(bytes.subarray(4, 4 + length)),
|
|
113
|
+
groupInfo: bytes.slice(4 + length)
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* The AAD binding a sealed reply to one kind, group, member, and request. The
|
|
118
|
+
* responder builds it from the *verified* request; the requester rebuilds it from
|
|
119
|
+
* its own handle and request id. Any disagreement is an AEAD failure, not a
|
|
120
|
+
* comparison a caller must remember to make.
|
|
121
|
+
*/ function recoveryAAD(kind, groupID, requesterDID, requestID) {
|
|
122
|
+
return concat([
|
|
123
|
+
kind.aadDomain,
|
|
124
|
+
frameField(groupID),
|
|
125
|
+
frameField(normalizeDID(requesterDID)),
|
|
126
|
+
frameField(requestID)
|
|
127
|
+
]);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Verify a request token's signature and parse its payload. The requester DID is
|
|
131
|
+
* the verified issuer, never a payload field. Unsigned (`alg: 'none'`) tokens are
|
|
132
|
+
* rejected: `verifyToken` returns them unchecked, so their `iss` is
|
|
133
|
+
* attacker-chosen. `embedLongForm` lets it verify offline — a responder needs no
|
|
134
|
+
* DID resolver to answer.
|
|
135
|
+
*/ async function verifyRecoveryRequest(token) {
|
|
136
|
+
let verified;
|
|
137
|
+
try {
|
|
138
|
+
verified = await verifyToken(token);
|
|
139
|
+
} catch {
|
|
140
|
+
throw new RecoveryRequestError('unverified', 'recovery request signature did not verify');
|
|
141
|
+
}
|
|
142
|
+
if (!isVerifiedToken(verified)) {
|
|
143
|
+
throw new RecoveryRequestError('unverified', 'recovery request is not signed');
|
|
144
|
+
}
|
|
145
|
+
const { iss, type, groupID, requestID, ephemeralKey } = verified.payload;
|
|
146
|
+
if (type !== RECOVERY_REQUEST_TYPE || typeof groupID !== 'string' || typeof requestID !== 'string' || typeof ephemeralKey !== 'string') {
|
|
147
|
+
throw new RecoveryRequestError('malformed', 'recovery request payload is malformed');
|
|
148
|
+
}
|
|
149
|
+
let ephemeralPublicKey;
|
|
150
|
+
try {
|
|
151
|
+
ephemeralPublicKey = decodeMultibase(ephemeralKey);
|
|
152
|
+
} catch {
|
|
153
|
+
throw new RecoveryRequestError('malformed', 'recovery request ephemeral key is not multibase');
|
|
154
|
+
}
|
|
155
|
+
if (ephemeralPublicKey.length !== KEM_OUTPUT_LENGTH) {
|
|
156
|
+
throw new RecoveryRequestError('malformed', `recovery request ephemeral key must be ${KEM_OUTPUT_LENGTH} bytes`);
|
|
157
|
+
}
|
|
158
|
+
return {
|
|
159
|
+
requesterDID: normalizeDID(iss),
|
|
160
|
+
groupID,
|
|
161
|
+
requestID,
|
|
162
|
+
ephemeralPublicKey
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Mint an ephemeral HPKE keypair and sign the request that publishes its public
|
|
167
|
+
* half. One keypair per request: the private half is what makes the reply openable
|
|
168
|
+
* by this peer and nobody else — an attacker who stole the peer's DID identity key
|
|
169
|
+
* can forge the *request* but cannot read the answer. The keypair is drawn from the
|
|
170
|
+
* group's own ciphersuite HPKE, so no second HPKE enters the system.
|
|
171
|
+
*/ export async function createRecoveryRequest(params) {
|
|
172
|
+
const { group, identity, requestID } = params;
|
|
173
|
+
if (normalizeDID(identity.id) !== normalizeDID(group.credential.id)) {
|
|
174
|
+
throw new Error(`createRecoveryRequest: identity.id (${identity.id}) must match the handle credential (${group.credential.id})`);
|
|
175
|
+
}
|
|
176
|
+
const { hpke } = group.context.cipherSuite;
|
|
177
|
+
const keyPair = await hpke.generateKeyPair();
|
|
178
|
+
const ephemeralPublicKey = await hpke.exportPublicKey(keyPair.publicKey);
|
|
179
|
+
const ephemeralPrivateKey = await hpke.exportPrivateKey(keyPair.privateKey);
|
|
180
|
+
const signed = await identity.signToken({
|
|
181
|
+
type: RECOVERY_REQUEST_TYPE,
|
|
182
|
+
groupID: group.groupID,
|
|
183
|
+
requestID,
|
|
184
|
+
ephemeralKey: encodeMultibase(ephemeralPublicKey)
|
|
185
|
+
}, // Self-verifying offline: a responder must not need a DID resolver to check
|
|
186
|
+
// the signature of a peer it has never resolved.
|
|
187
|
+
{
|
|
188
|
+
embedLongForm: true
|
|
189
|
+
});
|
|
190
|
+
return {
|
|
191
|
+
request: stringifyToken(signed),
|
|
192
|
+
ephemeralPublicKey,
|
|
193
|
+
ephemeralPrivateKey
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Answer a request of one kind: verify it, check the requester still holds a leaf
|
|
198
|
+
* in the responder's current ratchet tree, and seal `plaintext` to the ephemeral
|
|
199
|
+
* key *inside the signed request*.
|
|
200
|
+
*
|
|
201
|
+
* Authorization is roster-intrinsic and lives HERE, not in each caller, so a new
|
|
202
|
+
* kind of answer cannot be added without it. Not a permission a host can forget:
|
|
203
|
+
* only DIDs the responder's own tree still carries a leaf for can be answered, so a
|
|
204
|
+
* removed member gets nothing from any responder that has applied its removal.
|
|
205
|
+
*
|
|
206
|
+
* Throws {@link RecoveryRequestError} for every refusal — see
|
|
207
|
+
* {@link RecoveryRequestRejection}.
|
|
208
|
+
*/ async function sealToRequest(kind, group, request, plaintext) {
|
|
209
|
+
const verified = await verifyRecoveryRequest(request);
|
|
210
|
+
if (verified.groupID !== group.groupID) {
|
|
211
|
+
throw new RecoveryRequestError('group-mismatch', `recovery request names group ${verified.groupID}, not ${group.groupID}`);
|
|
212
|
+
}
|
|
213
|
+
if (group.findMemberLeafIndex(verified.requesterDID) === undefined) {
|
|
214
|
+
throw new RecoveryRequestError('not-a-member', `recovery requester ${verified.requesterDID} has no leaf in the current ratchet tree`);
|
|
215
|
+
}
|
|
216
|
+
const { hpke } = group.context.cipherSuite;
|
|
217
|
+
const aad = recoveryAAD(kind, group.groupID, verified.requesterDID, verified.requestID);
|
|
218
|
+
const { ct, enc } = await hpke.seal(await hpke.importPublicKey(verified.ephemeralPublicKey), plaintext, kind.hpkeInfo, aad);
|
|
219
|
+
const sealed = new Uint8Array(1 + enc.length + ct.length);
|
|
220
|
+
sealed[0] = kind.version;
|
|
221
|
+
sealed.set(enc, 1);
|
|
222
|
+
sealed.set(ct, 1 + enc.length);
|
|
223
|
+
return sealed;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Open a reply of one kind with the key minted for `requestID`; return the sealed
|
|
227
|
+
* plaintext.
|
|
228
|
+
*
|
|
229
|
+
* The AAD is rebuilt from the caller's *own* group id, DID, and request id, so a
|
|
230
|
+
* reply for another member, another request, or another kind (kind is bound into
|
|
231
|
+
* both AAD and HPKE `info`) fails as an AEAD failure, not a skippable comparison.
|
|
232
|
+
*/ async function openSealedReply(kind, group, sealed, requestID, ephemeralPrivateKey) {
|
|
233
|
+
if (sealed.length < MIN_SEALED_LENGTH || sealed[0] !== kind.version) {
|
|
234
|
+
throw kind.fail('malformed', 'sealed reply frame is truncated or carries an unknown version');
|
|
235
|
+
}
|
|
236
|
+
const enc = sealed.slice(1, 1 + KEM_OUTPUT_LENGTH);
|
|
237
|
+
const ct = sealed.slice(1 + KEM_OUTPUT_LENGTH);
|
|
238
|
+
const { hpke } = group.context.cipherSuite;
|
|
239
|
+
const aad = recoveryAAD(kind, group.groupID, group.credential.id, requestID);
|
|
240
|
+
// This member's OWN retained key. A wrong length is a corrupt/truncated own key
|
|
241
|
+
// (host storage fault), not a reply for another member, so it must NOT read as
|
|
242
|
+
// `not-for-me` (the benign verdict a lane-sifter drops). Validate OUTSIDE the open,
|
|
243
|
+
// where a throw cannot be mistaken for the AEAD's refusal, and surface a plain
|
|
244
|
+
// Error, not a SealedReplyRejection: a caller/host bug is not a droppable wire
|
|
245
|
+
// condition. (importPrivateKey only wraps the bytes; length is the whole check.)
|
|
246
|
+
if (ephemeralPrivateKey.length !== KEM_PRIVATE_KEY_LENGTH) {
|
|
247
|
+
throw new Error(`openSealedReply: retained ephemeral private key must be ${KEM_PRIVATE_KEY_LENGTH} bytes, not ${ephemeralPrivateKey.length} — a corrupt or truncated own key, not a reply for another member`);
|
|
248
|
+
}
|
|
249
|
+
const privateKey = await hpke.importPrivateKey(ephemeralPrivateKey);
|
|
250
|
+
try {
|
|
251
|
+
return await hpke.open(privateKey, enc, ct, kind.hpkeInfo, aad);
|
|
252
|
+
} catch {
|
|
253
|
+
throw kind.fail('not-for-me', 'sealed reply does not open for this member and request');
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Answer a recovery request with this group's framed `MLSMessage(GroupInfo)`,
|
|
258
|
+
* sealed to the ephemeral key inside the signed request, plus a membership
|
|
259
|
+
* attestation signed with the responder's DID identity key.
|
|
260
|
+
*
|
|
261
|
+
* The attestation is load-bearing: HPKE base mode seals to the requester's public
|
|
262
|
+
* ephemeral key (which rides the public request in the clear), so the AEAD cannot
|
|
263
|
+
* distinguish a member's reply from a forgery. The attestation — bound to this
|
|
264
|
+
* group, request, and a digest of these exact GroupInfo bytes — lets the requester
|
|
265
|
+
* refuse a reply from anyone holding no leaf in its own last-known tree.
|
|
266
|
+
*
|
|
267
|
+
* Throws {@link RecoveryRequestError} for every refusal. The reply is
|
|
268
|
+
* `[version][enc][ct]`, unreadable without the ephemeral private key and opening
|
|
269
|
+
* for no other member, request, or kind.
|
|
270
|
+
*/ export async function sealGroupInfo(params) {
|
|
271
|
+
const { group, identity, request } = params;
|
|
272
|
+
if (normalizeDID(identity.id) !== normalizeDID(group.credential.id)) {
|
|
273
|
+
throw new Error(`sealGroupInfo: identity.id (${identity.id}) must match the responding handle credential (${group.credential.id})`);
|
|
274
|
+
}
|
|
275
|
+
const verified = await verifyRecoveryRequest(request);
|
|
276
|
+
const { groupInfo } = await exportGroupInfo({
|
|
277
|
+
group
|
|
278
|
+
});
|
|
279
|
+
const signed = await identity.signToken({
|
|
280
|
+
type: RECOVERY_GROUPINFO_TYPE,
|
|
281
|
+
groupID: verified.groupID,
|
|
282
|
+
requestID: verified.requestID,
|
|
283
|
+
groupInfoDigest: encodeMultibase(sha256(groupInfo))
|
|
284
|
+
}, // Self-verifying offline: the healing peer must check the signature without
|
|
285
|
+
// resolving the responder.
|
|
286
|
+
{
|
|
287
|
+
embedLongForm: true
|
|
288
|
+
});
|
|
289
|
+
const plaintext = frameAttestedGroupInfo(stringifyToken(signed), groupInfo);
|
|
290
|
+
return await sealToRequest(GROUP_INFO_REPLY, group, request, plaintext);
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Verify the responder's membership attestation and require the signer to hold a
|
|
294
|
+
* leaf in the requester's own last-known ratchet tree — the authentication the AEAD
|
|
295
|
+
* cannot provide (HPKE base mode proves only that the ephemeral-key holder opened
|
|
296
|
+
* it, never who sealed it).
|
|
297
|
+
*
|
|
298
|
+
* The attestation must bind this group, request, and a digest of these exact
|
|
299
|
+
* GroupInfo bytes, so an honest attestation for one GroupInfo cannot be lifted onto
|
|
300
|
+
* a substituted one. The tree checked against is the requester's OWN — stale by
|
|
301
|
+
* construction, which is the point and the limit: a member absent from it (never
|
|
302
|
+
* joined, or removed before the requester's last-known epoch) is refused; one still
|
|
303
|
+
* in it (including one removed AFTER that epoch) is accepted.
|
|
304
|
+
*/ async function assertResponderIsMember(attestation, group, requestID, groupInfo) {
|
|
305
|
+
let verified;
|
|
306
|
+
try {
|
|
307
|
+
verified = await verifyToken(attestation);
|
|
308
|
+
} catch {
|
|
309
|
+
throw new SealedGroupInfoError('unauthenticated', 'responder attestation signature did not verify');
|
|
310
|
+
}
|
|
311
|
+
if (!isVerifiedToken(verified)) {
|
|
312
|
+
throw new SealedGroupInfoError('unauthenticated', 'responder attestation is not signed');
|
|
313
|
+
}
|
|
314
|
+
const { iss, type, groupID, requestID: attestedRequestID, groupInfoDigest } = verified.payload;
|
|
315
|
+
if (type !== RECOVERY_GROUPINFO_TYPE || groupID !== group.groupID || attestedRequestID !== requestID || typeof groupInfoDigest !== 'string' || groupInfoDigest !== encodeMultibase(sha256(groupInfo))) {
|
|
316
|
+
throw new SealedGroupInfoError('unauthenticated', 'responder attestation does not bind this group, request, and GroupInfo');
|
|
317
|
+
}
|
|
318
|
+
if (group.findMemberLeafIndex(normalizeDID(iss)) === undefined) {
|
|
319
|
+
throw new SealedGroupInfoError('unauthenticated', "responder holds no leaf in the requester's last-known ratchet tree");
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Bind the offered GroupInfo to the group being healed: same group id, same
|
|
324
|
+
* immutable genesis anchor. The anchor is written once at creation and seeds the
|
|
325
|
+
* roster a peer folds, so a byte comparison against the requester's own refuses any
|
|
326
|
+
* group whose authority root differs.
|
|
327
|
+
*/ function assertGroupInfoBoundToGroup(groupInfo, group) {
|
|
328
|
+
const binding = readGroupInfoBinding(groupInfo);
|
|
329
|
+
if (binding.groupID !== group.groupID) {
|
|
330
|
+
throw new SealedGroupInfoError('group-mismatch', `sealed GroupInfo names group ${binding.groupID}, not ${group.groupID}`);
|
|
331
|
+
}
|
|
332
|
+
const ownAnchor = readGroupAnchorExtension(group);
|
|
333
|
+
const ownData = ownAnchor?.extensionData instanceof Uint8Array ? ownAnchor.extensionData : null;
|
|
334
|
+
if (ownData == null || binding.anchorExtensionData == null || !bytesEqual(ownData, binding.anchorExtensionData)) {
|
|
335
|
+
throw new SealedGroupInfoError('group-mismatch', 'sealed GroupInfo carries a different genesis anchor than the group being healed');
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Open a sealed reply and return the framed `MLSMessage(GroupInfo)` — the exact
|
|
340
|
+
* bytes `joinGroupExternal` takes. Throws {@link SealedGroupInfoError}.
|
|
341
|
+
*
|
|
342
|
+
* Opening is not the end of the check: HPKE base mode proves only that this peer
|
|
343
|
+
* held the ephemeral key, not that a member sealed it. Two further gates make the
|
|
344
|
+
* reply roster-intrinsic before the bytes are handed on — the signed attestation
|
|
345
|
+
* must place the sealer in this requester's own last-known tree, and the offered
|
|
346
|
+
* GroupInfo's group id and genesis anchor must match the group being healed.
|
|
347
|
+
*/ export async function openSealedGroupInfo(params) {
|
|
348
|
+
const { group, sealed, requestID, ephemeralPrivateKey } = params;
|
|
349
|
+
const plaintext = await openSealedReply(GROUP_INFO_REPLY, group, sealed, requestID, ephemeralPrivateKey);
|
|
350
|
+
let attestation;
|
|
351
|
+
let groupInfo;
|
|
352
|
+
try {
|
|
353
|
+
;
|
|
354
|
+
({ attestation, groupInfo } = unframeAttestedGroupInfo(plaintext));
|
|
355
|
+
} catch {
|
|
356
|
+
throw new SealedGroupInfoError('malformed', 'sealed plaintext is not a framed, attested GroupInfo');
|
|
357
|
+
}
|
|
358
|
+
// Parse as a GroupInfo before anything trusts its fields.
|
|
359
|
+
try {
|
|
360
|
+
inspectGroupInfo(groupInfo);
|
|
361
|
+
} catch {
|
|
362
|
+
throw new SealedGroupInfoError('malformed', 'sealed plaintext is not a framed MLSMessage(GroupInfo)');
|
|
363
|
+
}
|
|
364
|
+
// Authenticate the responder, then bind the GroupInfo to this group.
|
|
365
|
+
await assertResponderIsMember(attestation, group, requestID, groupInfo);
|
|
366
|
+
assertGroupInfoBoundToGroup(groupInfo, group);
|
|
367
|
+
return groupInfo;
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* The whole ordered ledger, framed for sealing: `[count(4)][ (length(4) | token)... ]`,
|
|
371
|
+
* big-endian throughout. Order is load-bearing: the head is a chain digest, so the
|
|
372
|
+
* same tokens reordered fold to a different head and the requester rejects them — a
|
|
373
|
+
* list, never a set or map.
|
|
374
|
+
*/ function encodeLedgerTokens(tokens) {
|
|
375
|
+
const encoded = tokens.map((token)=>utf8.encode(token));
|
|
376
|
+
const size = encoded.reduce((total, bytes)=>total + 4 + bytes.length, 4);
|
|
377
|
+
const out = new Uint8Array(size);
|
|
378
|
+
const view = new DataView(out.buffer);
|
|
379
|
+
view.setUint32(0, encoded.length, false);
|
|
380
|
+
let offset = 4;
|
|
381
|
+
for (const bytes of encoded){
|
|
382
|
+
view.setUint32(offset, bytes.length, false);
|
|
383
|
+
out.set(bytes, offset + 4);
|
|
384
|
+
offset += 4 + bytes.length;
|
|
385
|
+
}
|
|
386
|
+
return out;
|
|
387
|
+
}
|
|
388
|
+
function decodeLedgerTokens(bytes) {
|
|
389
|
+
if (bytes.length < 4) throw new Error('sealed ledger is too short');
|
|
390
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
391
|
+
const count = view.getUint32(0, false);
|
|
392
|
+
const tokens = [];
|
|
393
|
+
let offset = 4;
|
|
394
|
+
for(let i = 0; i < count; i++){
|
|
395
|
+
if (offset + 4 > bytes.length) throw new Error('sealed ledger is truncated');
|
|
396
|
+
const length = view.getUint32(offset, false);
|
|
397
|
+
const start = offset + 4;
|
|
398
|
+
if (start + length > bytes.length) throw new Error('sealed ledger is truncated');
|
|
399
|
+
tokens.push(new TextDecoder().decode(bytes.subarray(start, start + length)));
|
|
400
|
+
offset = start + length;
|
|
401
|
+
}
|
|
402
|
+
// The count and its framed tokens must consume the whole payload. Reject trailing
|
|
403
|
+
// bytes here (same truncated/malformed class): a lax decoder is a parser
|
|
404
|
+
// differential the downstream head check might not catch.
|
|
405
|
+
if (offset !== bytes.length) {
|
|
406
|
+
throw new Error('sealed ledger has trailing bytes after the last token');
|
|
407
|
+
}
|
|
408
|
+
return tokens;
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Answer a ledger gather: the group's whole ordered authority state, sealed to the
|
|
412
|
+
* ephemeral key inside the signed request.
|
|
413
|
+
*
|
|
414
|
+
* These are the SAME bodies a commit frame seals under the epoch secret, but the
|
|
415
|
+
* rendezvous topic is public and secretless. A reply the hub could open would hand
|
|
416
|
+
* every role change, in order, to anyone who knows the topic; an unauthorized reply
|
|
417
|
+
* would hand them to anyone who can mint a request. {@link sealToRequest}'s roster
|
|
418
|
+
* check closes the second hole and is NOT optional — a seal without it merely
|
|
419
|
+
* encrypts the authority state neatly to the attacker's own key.
|
|
420
|
+
*
|
|
421
|
+
* Epoch-INDEPENDENT, hence HPKE to an ephemeral key and not the epoch secret: the
|
|
422
|
+
* peer most needing a bootstrap may be at an older epoch than every responder, and
|
|
423
|
+
* a reply sealed under the responder's current epoch would be unopenable by it.
|
|
424
|
+
*
|
|
425
|
+
* The ledger sealed is always this handle's own — read from
|
|
426
|
+
* {@link GroupHandle.getLedger} under the mutex — so a responder can only ever seal
|
|
427
|
+
* the authority state of the group whose tree just authorized the requester.
|
|
428
|
+
*
|
|
429
|
+
* Throws {@link RecoveryRequestError} for every refusal; the responder stays silent.
|
|
430
|
+
*/ export async function sealLedger(params) {
|
|
431
|
+
const { group, request } = params;
|
|
432
|
+
const entries = await group.getLedger();
|
|
433
|
+
return await sealToRequest(LEDGER_REPLY, group, request, encodeLedgerTokens(entries));
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Open a sealed ledger reply and return the responder's whole ordered ledger, as
|
|
437
|
+
* signed tokens.
|
|
438
|
+
*
|
|
439
|
+
* Opening proves NOTHING about who sealed these tokens: HPKE base mode over an AAD
|
|
440
|
+
* whose fields all ride the public request in the clear, so any observer (the hub, a
|
|
441
|
+
* stranger who learned the topic) can forge a reply that opens as a member's would.
|
|
442
|
+
* The bound is not the seal but the head check the caller runs next —
|
|
443
|
+
* {@link GroupHandle.bootstrapLedger} re-derives every id from the token bytes and
|
|
444
|
+
* gates on the MLS-authenticated `ledger_head`, which a forger cannot reproduce. So a
|
|
445
|
+
* forged or lying reply can withhold, reorder, or truncate — never rewrite — and a
|
|
446
|
+
* forged one simply fails that check. Residual is DoS only (a forged reply can burn a
|
|
447
|
+
* gather attempt), not compromise. Throws {@link SealedLedgerError}.
|
|
448
|
+
*/ export async function openSealedLedger(params) {
|
|
449
|
+
const { group, sealed, requestID, ephemeralPrivateKey } = params;
|
|
450
|
+
const plaintext = await openSealedReply(LEDGER_REPLY, group, sealed, requestID, ephemeralPrivateKey);
|
|
451
|
+
try {
|
|
452
|
+
return decodeLedgerTokens(plaintext);
|
|
453
|
+
} catch {
|
|
454
|
+
throw new SealedLedgerError('malformed', 'sealed plaintext is not a framed ledger');
|
|
455
|
+
}
|
|
456
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { MlsContext } from 'ts-mls';
|
|
2
|
+
/**
|
|
3
|
+
* PrivateMessage sender-data decrypt, reimplemented from RFC 9420 §6.3.2.
|
|
4
|
+
*
|
|
5
|
+
* ts-mls ships `decryptSenderData` but does not re-export it (its `exports` map exposes
|
|
6
|
+
* only `.`), so this package reproduces the derivation from primitives the live
|
|
7
|
+
* `CiphersuiteImpl` does expose. Frozen wire format — see the backlog note
|
|
8
|
+
* `ts-mls-v2-stable-upgrade.md`: delete this module and delegate to ts-mls once stable
|
|
9
|
+
* re-exports its own.
|
|
10
|
+
*/
|
|
11
|
+
/** The PrivateMessage fields sender-data decrypt reads, narrowed off a decoded frame. */
|
|
12
|
+
export type PrivateCommitFrame = {
|
|
13
|
+
groupId: Uint8Array;
|
|
14
|
+
epoch: bigint;
|
|
15
|
+
contentType: number;
|
|
16
|
+
encryptedSenderData: Uint8Array;
|
|
17
|
+
ciphertext: Uint8Array;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Decrypt a PrivateMessage's sender-data and return the committer's leaf index, or `null`
|
|
21
|
+
* if the AEAD refuses the bytes or the plaintext is malformed. Non-mutating: the
|
|
22
|
+
* sender-data secret is epoch-level and consumes no per-message ratchet key.
|
|
23
|
+
*/
|
|
24
|
+
export declare function readSenderLeafIndex(context: MlsContext, senderDataSecret: Uint8Array, pm: PrivateCommitFrame): Promise<number | null>;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
const LABEL_PREFIX = new TextEncoder().encode('MLS 1.0 ');
|
|
2
|
+
function concat(parts) {
|
|
3
|
+
let length = 0;
|
|
4
|
+
for (const part of parts)length += part.length;
|
|
5
|
+
const out = new Uint8Array(length);
|
|
6
|
+
let offset = 0;
|
|
7
|
+
for (const part of parts){
|
|
8
|
+
out.set(part, offset);
|
|
9
|
+
offset += part.length;
|
|
10
|
+
}
|
|
11
|
+
return out;
|
|
12
|
+
}
|
|
13
|
+
function uint16(n) {
|
|
14
|
+
return new Uint8Array([
|
|
15
|
+
n >> 8 & 0xff,
|
|
16
|
+
n & 0xff
|
|
17
|
+
]);
|
|
18
|
+
}
|
|
19
|
+
function uint64(n) {
|
|
20
|
+
const out = new Uint8Array(8);
|
|
21
|
+
let value = n;
|
|
22
|
+
for(let i = 7; i >= 0; i--){
|
|
23
|
+
out[i] = Number(value & 0xffn);
|
|
24
|
+
value >>= 8n;
|
|
25
|
+
}
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
/** RFC 9420 opaque<V>: QUIC-style variable-length prefix (RFC 9000 §16), then the bytes. */ function varLen(data) {
|
|
29
|
+
const len = data.length;
|
|
30
|
+
let prefix;
|
|
31
|
+
if (len < 64) {
|
|
32
|
+
prefix = new Uint8Array([
|
|
33
|
+
len & 0x3f
|
|
34
|
+
]);
|
|
35
|
+
} else if (len < 16384) {
|
|
36
|
+
prefix = new Uint8Array([
|
|
37
|
+
len >> 8 & 0x3f | 0x40,
|
|
38
|
+
len & 0xff
|
|
39
|
+
]);
|
|
40
|
+
} else if (len < 0x40000000) {
|
|
41
|
+
prefix = new Uint8Array([
|
|
42
|
+
len >> 24 & 0x3f | 0x80,
|
|
43
|
+
len >> 16 & 0xff,
|
|
44
|
+
len >> 8 & 0xff,
|
|
45
|
+
len & 0xff
|
|
46
|
+
]);
|
|
47
|
+
} else {
|
|
48
|
+
throw new Error('sender-data: length too large to encode');
|
|
49
|
+
}
|
|
50
|
+
return concat([
|
|
51
|
+
prefix,
|
|
52
|
+
data
|
|
53
|
+
]);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* MLS `ExpandWithLabel(Secret, Label, Context, Length)`: `KDF.Expand` over the KDFLabel
|
|
57
|
+
* struct `{ uint16 length; opaque label<V> = "MLS 1.0 " + Label; opaque context<V> }`.
|
|
58
|
+
*/ function expandWithLabel(context, secret, label, labelContext, length) {
|
|
59
|
+
const kdfLabel = concat([
|
|
60
|
+
uint16(length),
|
|
61
|
+
varLen(concat([
|
|
62
|
+
LABEL_PREFIX,
|
|
63
|
+
new TextEncoder().encode(label)
|
|
64
|
+
])),
|
|
65
|
+
varLen(labelContext)
|
|
66
|
+
]);
|
|
67
|
+
return context.cipherSuite.kdf.expand(secret, kdfLabel, length);
|
|
68
|
+
}
|
|
69
|
+
/** The ciphertext sample the sender-data key/nonce derive from: the first `KDF.Nh` bytes. */ function sample(context, ciphertext) {
|
|
70
|
+
const size = context.cipherSuite.kdf.size;
|
|
71
|
+
return ciphertext.length < size ? ciphertext : ciphertext.subarray(0, size);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Decrypt a PrivateMessage's sender-data and return the committer's leaf index, or `null`
|
|
75
|
+
* if the AEAD refuses the bytes or the plaintext is malformed. Non-mutating: the
|
|
76
|
+
* sender-data secret is epoch-level and consumes no per-message ratchet key.
|
|
77
|
+
*/ export async function readSenderLeafIndex(context, senderDataSecret, pm) {
|
|
78
|
+
const { hpke } = context.cipherSuite;
|
|
79
|
+
const sampled = sample(context, pm.ciphertext);
|
|
80
|
+
const key = await expandWithLabel(context, senderDataSecret, 'key', sampled, hpke.keyLength);
|
|
81
|
+
const nonce = await expandWithLabel(context, senderDataSecret, 'nonce', sampled, hpke.nonceLength);
|
|
82
|
+
// SenderDataAAD = { opaque group_id<V>; uint64 epoch; ContentType content_type (uint8) }.
|
|
83
|
+
const aad = concat([
|
|
84
|
+
varLen(pm.groupId),
|
|
85
|
+
uint64(pm.epoch),
|
|
86
|
+
new Uint8Array([
|
|
87
|
+
pm.contentType & 0xff
|
|
88
|
+
])
|
|
89
|
+
]);
|
|
90
|
+
let plaintext;
|
|
91
|
+
try {
|
|
92
|
+
plaintext = await hpke.decryptAead(key, nonce, aad, pm.encryptedSenderData);
|
|
93
|
+
} catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
// SenderData = { uint32 leaf_index; uint32 generation; opaque reuse_guard[4] }.
|
|
97
|
+
if (plaintext.length < 4) return null;
|
|
98
|
+
return new DataView(plaintext.buffer, plaintext.byteOffset, plaintext.byteLength).getUint32(0);
|
|
99
|
+
}
|