@kumiai/mls 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/crypto.js ADDED
@@ -0,0 +1,387 @@
1
+ /**
2
+ * Pure @noble/* CryptoProvider for ts-mls.
3
+ *
4
+ * Replaces @hpke/core (which requires crypto.subtle) with direct use of:
5
+ * - @noble/curves for X25519 ECDH and Ed25519 signatures
6
+ * - @noble/hashes for SHA-256/384/512 and HKDF
7
+ * - @noble/ciphers for AES-GCM and ChaCha20-Poly1305
8
+ *
9
+ * This enables ts-mls to run on Hermes (React Native) where crypto.subtle is unavailable.
10
+ */ import { gcm } from '@noble/ciphers/aes.js';
11
+ import { chacha20poly1305 } from '@noble/ciphers/chacha.js';
12
+ import { ed25519, x25519 } from '@noble/curves/ed25519.js';
13
+ import { expand as hkdfExpand, extract as hkdfExtract } from '@noble/hashes/hkdf.js';
14
+ import { hmac } from '@noble/hashes/hmac.js';
15
+ import { sha256, sha384, sha512 } from '@noble/hashes/sha2.js';
16
+ import { createRuntime } from '@sozai/runtime';
17
+ // ---------------------------------------------------------------------------
18
+ // Helpers
19
+ // ---------------------------------------------------------------------------
20
+ function constantTimeEqual(a, b) {
21
+ if (a.length !== b.length) return false;
22
+ let diff = 0;
23
+ for(let i = 0; i < a.length; i++){
24
+ // biome-ignore lint/style/noNonNullAssertion: index is within bounds
25
+ diff |= a[i] ^ b[i];
26
+ }
27
+ return diff === 0;
28
+ }
29
+ function concatBytes(...arrays) {
30
+ let totalLen = 0;
31
+ for (const a of arrays)totalLen += a.length;
32
+ const result = new Uint8Array(totalLen);
33
+ let offset = 0;
34
+ for (const a of arrays){
35
+ result.set(a, offset);
36
+ offset += a.length;
37
+ }
38
+ return result;
39
+ }
40
+ function i2osp(value, w) {
41
+ const result = new Uint8Array(w);
42
+ let n = value;
43
+ for(let i = w - 1; i >= 0 && n > 0; i--){
44
+ result[i] = n & 0xff;
45
+ n >>>= 8;
46
+ }
47
+ return result;
48
+ }
49
+ function getHashFn(name) {
50
+ // Normalize: ts-mls uses both "SHA-256" and "SHA256" (from HKDF-SHA256)
51
+ const normalized = name.replace('-', '');
52
+ switch(normalized){
53
+ case 'SHA256':
54
+ return {
55
+ hash: sha256,
56
+ size: 32
57
+ };
58
+ case 'SHA384':
59
+ return {
60
+ hash: sha384,
61
+ size: 48
62
+ };
63
+ case 'SHA512':
64
+ return {
65
+ hash: sha512,
66
+ size: 64
67
+ };
68
+ default:
69
+ throw new Error(`Unsupported hash: ${name}`);
70
+ }
71
+ }
72
+ // ---------------------------------------------------------------------------
73
+ // Hash
74
+ // ---------------------------------------------------------------------------
75
+ function makeHash(hashName) {
76
+ const { hash } = getHashFn(hashName);
77
+ return {
78
+ async digest (data) {
79
+ return hash(data);
80
+ },
81
+ async mac (key, data) {
82
+ return hmac(hash, key, data);
83
+ },
84
+ async verifyMac (key, mac, data) {
85
+ const expected = hmac(hash, key, data);
86
+ return constantTimeEqual(mac, expected);
87
+ }
88
+ };
89
+ }
90
+ // ---------------------------------------------------------------------------
91
+ // KDF (HKDF)
92
+ // ---------------------------------------------------------------------------
93
+ function makeKdf(kdfName) {
94
+ const { hash, size } = getHashFn(kdfName.replace('HKDF-', ''));
95
+ return {
96
+ async extract (salt, ikm) {
97
+ return hkdfExtract(hash, ikm, salt);
98
+ },
99
+ async expand (prk, info, len) {
100
+ return hkdfExpand(hash, prk, info, len);
101
+ },
102
+ size
103
+ };
104
+ }
105
+ // ---------------------------------------------------------------------------
106
+ // Signature (Ed25519)
107
+ // ---------------------------------------------------------------------------
108
+ function makeSignature(sigName) {
109
+ if (sigName !== 'Ed25519') {
110
+ throw new Error(`Unsupported signature algorithm: ${sigName}. Only Ed25519 is supported.`);
111
+ }
112
+ return {
113
+ async sign (signKey, message) {
114
+ return ed25519.sign(message, signKey);
115
+ },
116
+ async verify (publicKey, message, signature) {
117
+ return ed25519.verify(signature, message, publicKey);
118
+ },
119
+ async keygen () {
120
+ const signKey = ed25519.utils.randomSecretKey();
121
+ return {
122
+ signKey,
123
+ publicKey: ed25519.getPublicKey(signKey)
124
+ };
125
+ }
126
+ };
127
+ }
128
+ // ---------------------------------------------------------------------------
129
+ // RNG
130
+ // ---------------------------------------------------------------------------
131
+ function makeRng(runtime, customRandomBytes) {
132
+ if (customRandomBytes != null) {
133
+ return {
134
+ randomBytes: customRandomBytes
135
+ };
136
+ }
137
+ return {
138
+ randomBytes (n) {
139
+ return runtime.getRandomValues(new Uint8Array(n));
140
+ }
141
+ };
142
+ }
143
+ // ---------------------------------------------------------------------------
144
+ // HPKE (RFC 9180) — X25519 KEM + HKDF + AES-GCM / ChaCha20-Poly1305
145
+ // ---------------------------------------------------------------------------
146
+ // HPKE constants for X25519
147
+ const KEM_ID_X25519 = 0x0020;
148
+ const KEM_SUITE_ID = concatBytes(new TextEncoder().encode('KEM'), i2osp(KEM_ID_X25519, 2));
149
+ /**
150
+ * Labeled Extract (RFC 9180 §4)
151
+ */ function labeledExtract(hash, salt, label, ikm, suiteID) {
152
+ const labeledIKM = concatBytes(new TextEncoder().encode('HPKE-v1'), suiteID, new TextEncoder().encode(label), ikm);
153
+ return hkdfExtract(hash, labeledIKM, salt);
154
+ }
155
+ /**
156
+ * Labeled Expand (RFC 9180 §4)
157
+ */ function labeledExpand(hash, prk, label, info, len, suiteID) {
158
+ const labeledInfo = concatBytes(i2osp(len, 2), new TextEncoder().encode('HPKE-v1'), suiteID, new TextEncoder().encode(label), info);
159
+ return hkdfExpand(hash, prk, labeledInfo, len);
160
+ }
161
+ /**
162
+ * ExtractAndExpand (RFC 9180 §4.1)
163
+ */ function extractAndExpand(hash, dh, kemContext, suiteID, nSecret) {
164
+ const prk = labeledExtract(hash, new Uint8Array(0), 'shared_secret', dh, suiteID);
165
+ return labeledExpand(hash, prk, 'shared_secret', kemContext, nSecret, suiteID);
166
+ }
167
+ /**
168
+ * DeriveKeyPair (RFC 9180 §7.1.3 — X25519)
169
+ */ function deriveKeyPairX25519(hash, ikm) {
170
+ const dkpPRK = labeledExtract(hash, new Uint8Array(0), 'dkp_prk', ikm, KEM_SUITE_ID);
171
+ const sk = labeledExpand(hash, dkpPRK, 'sk', new Uint8Array(0), 32, KEM_SUITE_ID);
172
+ const pk = x25519.getPublicKey(sk);
173
+ return {
174
+ privateKey: sk,
175
+ publicKey: pk
176
+ };
177
+ }
178
+ function makeHpke(hpkeAlg) {
179
+ if (!hpkeAlg.kem.includes('X25519')) {
180
+ throw new Error(`Unsupported KEM: ${hpkeAlg.kem}. Only DHKEM-X25519-HKDF-SHA256 is supported.`);
181
+ }
182
+ const { hash: kemHash } = getHashFn('SHA-256') // X25519 KEM always uses SHA-256
183
+ ;
184
+ const nSecret = 32 // SHA-256 output length
185
+ ;
186
+ let aeadKeySize;
187
+ let createAEADCipher;
188
+ switch(hpkeAlg.aead){
189
+ case 'AES128GCM':
190
+ aeadKeySize = 16;
191
+ createAEADCipher = gcm;
192
+ break;
193
+ case 'AES256GCM':
194
+ aeadKeySize = 32;
195
+ createAEADCipher = gcm;
196
+ break;
197
+ case 'CHACHA20POLY1305':
198
+ aeadKeySize = 32;
199
+ createAEADCipher = chacha20poly1305;
200
+ break;
201
+ default:
202
+ throw new Error(`Unsupported AEAD: ${hpkeAlg.aead}`);
203
+ }
204
+ const aeadNonceSize = 12;
205
+ // HPKE suite ID for the full suite (KDF + AEAD)
206
+ const kdfID = hpkeAlg.kdf === 'HKDF-SHA256' ? 0x0001 : hpkeAlg.kdf === 'HKDF-SHA384' ? 0x0002 : 0x0003;
207
+ const aeadID = hpkeAlg.aead === 'AES128GCM' ? 0x0001 : hpkeAlg.aead === 'AES256GCM' ? 0x0002 : 0x0003;
208
+ const hpkeSuiteID = concatBytes(new TextEncoder().encode('HPKE'), i2osp(KEM_ID_X25519, 2), i2osp(kdfID, 2), i2osp(aeadID, 2));
209
+ const { hash: kdfHash } = getHashFn(hpkeAlg.kdf.replace('HKDF-', ''));
210
+ function wrapPrivateKey(raw) {
211
+ return {
212
+ raw,
213
+ type: 'private'
214
+ };
215
+ }
216
+ function wrapPublicKey(raw) {
217
+ return {
218
+ raw,
219
+ type: 'public'
220
+ };
221
+ }
222
+ function unwrapKey(key) {
223
+ if (key == null || typeof key !== 'object' || !('raw' in key)) {
224
+ throw new Error('Invalid key: expected a wrapped key object with raw Uint8Array');
225
+ }
226
+ return key.raw;
227
+ }
228
+ /**
229
+ * Encap (RFC 9180 §4.1) — generate ephemeral keypair and shared secret
230
+ */ function encap(recipientPublicKey) {
231
+ const ek = x25519.utils.randomSecretKey();
232
+ const enc = x25519.getPublicKey(ek);
233
+ const dh = x25519.getSharedSecret(ek, recipientPublicKey);
234
+ const kemContext = concatBytes(enc, recipientPublicKey);
235
+ const sharedSecret = extractAndExpand(kemHash, dh, kemContext, KEM_SUITE_ID, nSecret);
236
+ return {
237
+ sharedSecret,
238
+ enc
239
+ };
240
+ }
241
+ /**
242
+ * Decap (RFC 9180 §4.1) — derive shared secret from received enc
243
+ */ function decap(enc, recipientPrivateKey) {
244
+ const dh = x25519.getSharedSecret(recipientPrivateKey, enc);
245
+ const recipientPublicKey = x25519.getPublicKey(recipientPrivateKey);
246
+ const kemContext = concatBytes(enc, recipientPublicKey);
247
+ return extractAndExpand(kemHash, dh, kemContext, KEM_SUITE_ID, nSecret);
248
+ }
249
+ /**
250
+ * KeySchedule (RFC 9180 §5.1)
251
+ */ function keySchedule(sharedSecret, info) {
252
+ const mode = 0 // mode_base
253
+ ;
254
+ const pskIDHash = labeledExtract(kdfHash, new Uint8Array(0), 'psk_id_hash', new Uint8Array(0), hpkeSuiteID);
255
+ const infoHash = labeledExtract(kdfHash, new Uint8Array(0), 'info_hash', info, hpkeSuiteID);
256
+ const ksContext = concatBytes(new Uint8Array([
257
+ mode
258
+ ]), pskIDHash, infoHash);
259
+ const secret = labeledExtract(kdfHash, sharedSecret, 'secret', new Uint8Array(0), hpkeSuiteID);
260
+ const key = labeledExpand(kdfHash, secret, 'key', ksContext, aeadKeySize, hpkeSuiteID);
261
+ const baseNonce = labeledExpand(kdfHash, secret, 'base_nonce', ksContext, aeadNonceSize, hpkeSuiteID);
262
+ const exporterSecret = labeledExpand(kdfHash, secret, 'exp', ksContext, kdfHash.outputLen, hpkeSuiteID);
263
+ return {
264
+ key,
265
+ baseNonce,
266
+ exporterSecret
267
+ };
268
+ }
269
+ function aeadEncrypt(key, nonce, aad, plaintext) {
270
+ const cipher = createAEADCipher(key, nonce, aad);
271
+ return cipher.encrypt(plaintext);
272
+ }
273
+ function aeadDecrypt(key, nonce, aad, ciphertext) {
274
+ const cipher = createAEADCipher(key, nonce, aad);
275
+ return cipher.decrypt(ciphertext);
276
+ }
277
+ return {
278
+ async seal (publicKey, plaintext, info, aad) {
279
+ const { sharedSecret, enc } = encap(unwrapKey(publicKey));
280
+ const { key, baseNonce } = keySchedule(sharedSecret, info);
281
+ const ct = aeadEncrypt(key, baseNonce, aad ?? new Uint8Array(0), plaintext);
282
+ return {
283
+ ct,
284
+ enc
285
+ };
286
+ },
287
+ async open (privateKey, kemOutput, ciphertext, info, aad) {
288
+ const sharedSecret = decap(kemOutput, unwrapKey(privateKey));
289
+ const { key, baseNonce } = keySchedule(sharedSecret, info);
290
+ return aeadDecrypt(key, baseNonce, aad ?? new Uint8Array(0), ciphertext);
291
+ },
292
+ async importPrivateKey (k) {
293
+ return wrapPrivateKey(k);
294
+ },
295
+ async importPublicKey (k) {
296
+ return wrapPublicKey(k);
297
+ },
298
+ async exportPublicKey (k) {
299
+ return unwrapKey(k);
300
+ },
301
+ async exportPrivateKey (k) {
302
+ return unwrapKey(k);
303
+ },
304
+ async encryptAead (key, nonce, aad, plaintext) {
305
+ return aeadEncrypt(key, nonce, aad ?? new Uint8Array(0), plaintext);
306
+ },
307
+ async decryptAead (key, nonce, aad, ciphertext) {
308
+ return aeadDecrypt(key, nonce, aad ?? new Uint8Array(0), ciphertext);
309
+ },
310
+ async exportSecret (publicKey, exporterContext, length, info) {
311
+ const { sharedSecret, enc } = encap(unwrapKey(publicKey));
312
+ const { exporterSecret } = keySchedule(sharedSecret, info);
313
+ const secret = labeledExpand(kdfHash, exporterSecret, 'sec', exporterContext, length, hpkeSuiteID);
314
+ return {
315
+ enc,
316
+ secret
317
+ };
318
+ },
319
+ async importSecret (privateKey, exporterContext, kemOutput, length, info) {
320
+ const sharedSecret = decap(kemOutput, unwrapKey(privateKey));
321
+ const { exporterSecret } = keySchedule(sharedSecret, info);
322
+ return labeledExpand(kdfHash, exporterSecret, 'sec', exporterContext, length, hpkeSuiteID);
323
+ },
324
+ async deriveKeyPair (ikm) {
325
+ const { privateKey, publicKey } = deriveKeyPairX25519(kemHash, ikm);
326
+ return {
327
+ privateKey: wrapPrivateKey(privateKey),
328
+ publicKey: wrapPublicKey(publicKey)
329
+ };
330
+ },
331
+ async generateKeyPair () {
332
+ const privateKey = x25519.utils.randomSecretKey();
333
+ const publicKey = x25519.getPublicKey(privateKey);
334
+ return {
335
+ privateKey: wrapPrivateKey(privateKey),
336
+ publicKey: wrapPublicKey(publicKey)
337
+ };
338
+ },
339
+ keyLength: aeadKeySize,
340
+ nonceLength: aeadNonceSize
341
+ };
342
+ }
343
+ // Lookup from numeric ciphersuite ID to algorithm configuration.
344
+ // We only support the ciphersuites that use X25519 + Ed25519 (noble-compatible).
345
+ const CIPHERSUITE_CONFIGS = {
346
+ // MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519
347
+ 1: {
348
+ hash: 'SHA-256',
349
+ hpke: {
350
+ kem: 'DHKEM-X25519-HKDF-SHA256',
351
+ kdf: 'HKDF-SHA256',
352
+ aead: 'AES128GCM'
353
+ },
354
+ signature: 'Ed25519'
355
+ },
356
+ // MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519
357
+ 3: {
358
+ hash: 'SHA-256',
359
+ hpke: {
360
+ kem: 'DHKEM-X25519-HKDF-SHA256',
361
+ kdf: 'HKDF-SHA256',
362
+ aead: 'CHACHA20POLY1305'
363
+ },
364
+ signature: 'Ed25519'
365
+ }
366
+ };
367
+ export function createNobleCryptoProvider(options) {
368
+ const runtime = options?.runtime ?? createRuntime();
369
+ const rng = makeRng(runtime, options?.randomBytes);
370
+ return {
371
+ async getCiphersuiteImpl (id) {
372
+ const config = CIPHERSUITE_CONFIGS[id];
373
+ if (config == null) {
374
+ throw new Error(`Unsupported ciphersuite ID: ${id}. Only X25519+Ed25519 suites (IDs 1, 3) are supported.`);
375
+ }
376
+ return {
377
+ hash: makeHash(config.hash),
378
+ kdf: makeKdf(config.hpke.kdf),
379
+ signature: makeSignature(config.signature),
380
+ hpke: makeHpke(config.hpke),
381
+ rng,
382
+ id
383
+ };
384
+ }
385
+ };
386
+ }
387
+ /** Default noble CryptoProvider using the default runtime for RNG. */ export const nobleCryptoProvider = createNobleCryptoProvider();
package/lib/group.d.ts ADDED
@@ -0,0 +1,233 @@
1
+ import { type DIDCache, type DIDResolver, type OwnIdentity, type SigningIdentity } from '@kokuin/token';
2
+ import { type ClientState, type Credential, type IncomingMessageCallback, type KeyPackage, type MlsContext, type ProposalWithSender } from 'ts-mls';
3
+ import { type GroupPermission } from './capability.js';
4
+ import { type GroupMember, type MemberCredential } from './credential.js';
5
+ import type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
6
+ export declare function makeMLSCredential(identity: OwnIdentity): Credential;
7
+ /**
8
+ * Thrown by GroupHandle.processMessage/decrypt when the active commit policy
9
+ * rejects an incoming commit. The handle is left at its pre-commit epoch.
10
+ */
11
+ export declare class CommitRejectedError extends Error {
12
+ #private;
13
+ constructor(proposals: Array<ProposalWithSender>, senderLeafIndex?: number);
14
+ get proposals(): Array<ProposalWithSender>;
15
+ get senderLeafIndex(): number | undefined;
16
+ }
17
+ export type GroupHandleParams = {
18
+ state: ClientState;
19
+ credential: MemberCredential;
20
+ context: MlsContext;
21
+ /** Stringified root capability (for delegation) */
22
+ rootCapability: string;
23
+ cache: DIDCache;
24
+ resolver?: DIDResolver;
25
+ /** Default commit policy applied by processMessage/decrypt. */
26
+ commitPolicy?: IncomingMessageCallback;
27
+ };
28
+ /**
29
+ * Mutable wrapper around MLS group state + Enkaku credential.
30
+ */
31
+ export declare class GroupHandle {
32
+ #private;
33
+ constructor(params: GroupHandleParams);
34
+ get groupID(): string;
35
+ get epoch(): bigint;
36
+ get treeHash(): Uint8Array;
37
+ get credential(): MemberCredential;
38
+ get state(): ClientState;
39
+ get rootCapability(): string;
40
+ get context(): MlsContext;
41
+ get cache(): DIDCache;
42
+ get resolver(): DIDResolver | undefined;
43
+ /** The commit policy enforced by processMessage/decrypt, if any. Carried
44
+ * onto handles derived from this one (commitInvite/removeMember). */
45
+ get commitPolicy(): IncomingMessageCallback | undefined;
46
+ get memberCount(): number;
47
+ findMemberLeafIndex(id: string): number | undefined;
48
+ /**
49
+ * Enumerate the group's current members from the ratchet tree, in ascending
50
+ * leaf-index order. Leaves whose credential identity fails to parse are skipped
51
+ * (same tolerance as findMemberLeafIndex). Reflects the handle's current #state
52
+ * — call before and after processMessage to diff a commit's membership change.
53
+ */
54
+ listMembers(): Array<GroupMember>;
55
+ /**
56
+ * Encrypt an application message for the group.
57
+ */
58
+ encrypt(plaintext: Uint8Array): Promise<{
59
+ message: unknown;
60
+ consumed: Array<Uint8Array>;
61
+ }>;
62
+ /**
63
+ * Decrypt an application message from the group.
64
+ *
65
+ * Accepts either wire-form bytes (framed MLSMessage `Uint8Array`) or a
66
+ * pre-decoded ts-mls message object. The param type widens to `unknown`
67
+ * because `Uint8Array | unknown` collapses to `unknown` in TypeScript; the
68
+ * runtime `instanceof` check selects the decode path. Note: `encrypt`
69
+ * currently emits objects, so the bytes path is for symmetry with
70
+ * processMessage and future wire-form application messages.
71
+ */
72
+ decrypt(message: Uint8Array | unknown, opts?: {
73
+ commitPolicy?: IncomingMessageCallback;
74
+ }): Promise<Uint8Array>;
75
+ /**
76
+ * Process a received MLS message (Commit, Proposal, or application).
77
+ *
78
+ * Accepts either wire-form bytes (the preferred input — framed MLSMessage
79
+ * `Uint8Array`, e.g. from commitInvite/removeMember) or a pre-decoded ts-mls
80
+ * message object (legacy path). The param type widens to `unknown` because
81
+ * `Uint8Array | unknown` collapses to `unknown` in TypeScript; the runtime
82
+ * `instanceof` check selects the decode path.
83
+ */
84
+ processMessage(message: Uint8Array | unknown, opts?: {
85
+ commitPolicy?: IncomingMessageCallback;
86
+ }): Promise<Uint8Array | null>;
87
+ }
88
+ export type CreateGroupResult = {
89
+ group: GroupHandle;
90
+ credential: MemberCredential;
91
+ };
92
+ /**
93
+ * Create a new MLS group. The identity becomes the sole member and admin.
94
+ */
95
+ export declare function createGroup(identity: OwnIdentity, groupID: string, options?: GroupOptions): Promise<CreateGroupResult>;
96
+ export type RestoreGroupParams = {
97
+ state: ClientState;
98
+ credential: MemberCredential;
99
+ rootCapability: string;
100
+ options?: GroupOptions;
101
+ };
102
+ export declare function restoreGroup(params: RestoreGroupParams): Promise<GroupHandle>;
103
+ export type CreateInviteParams = {
104
+ group: GroupHandle;
105
+ identity: SigningIdentity;
106
+ recipientDID: string;
107
+ permission: GroupPermission;
108
+ };
109
+ export type CreateInviteResult = {
110
+ invite: Invite;
111
+ };
112
+ /**
113
+ * Create an invite for a new member.
114
+ * Does NOT add them to the group — call commitInvite with their key package to do that.
115
+ */
116
+ export declare function createInvite(params: CreateInviteParams): Promise<CreateInviteResult>;
117
+ export type CommitInviteResult = {
118
+ /** Framed MLSMessage bytes. Broadcast to existing members via the DS. */
119
+ commitMessage: Uint8Array;
120
+ /** Framed MLSMessage(Welcome) bytes. Delivered to the new member. */
121
+ welcomeMessage: Uint8Array;
122
+ newGroup: GroupHandle;
123
+ /** Post-commit epoch the group is now at (== newGroup.epoch). NOTE: this is
124
+ * NOT the epoch carried in the commit's wire header — a commit is framed at
125
+ * the sender's pre-commit epoch (== epoch - 1n), which is what receivers
126
+ * compare against their own handle.epoch for ordering (see readMessageEpoch). */
127
+ epoch: bigint;
128
+ };
129
+ /**
130
+ * Commit an invite by adding the invitee's key package to the group.
131
+ * Produces an MLS Commit + Welcome.
132
+ */
133
+ export declare function commitInvite(group: GroupHandle, keyPackage: KeyPackage): Promise<CommitInviteResult>;
134
+ export type ProcessWelcomeResult = {
135
+ group: GroupHandle;
136
+ credential: MemberCredential;
137
+ };
138
+ export type ProcessWelcomeParams = {
139
+ identity: OwnIdentity;
140
+ invite: Invite;
141
+ /** Wire-form framed MLSMessage(Welcome) bytes (preferred), or a pre-decoded
142
+ * ts-mls Welcome object (legacy). `Uint8Array | unknown` collapses to
143
+ * `unknown` in TypeScript; the runtime `instanceof` check selects the path. */
144
+ welcome: Uint8Array | unknown;
145
+ keyPackageBundle: KeyPackageBundle;
146
+ ratchetTree?: unknown;
147
+ options?: GroupOptions;
148
+ };
149
+ /**
150
+ * Process a Welcome message to join a group.
151
+ */
152
+ export declare function processWelcome(params: ProcessWelcomeParams): Promise<ProcessWelcomeResult>;
153
+ export type RemoveMemberResult = {
154
+ /** Framed MLSMessage bytes. Broadcast to existing members via the DS. */
155
+ commitMessage: Uint8Array;
156
+ newGroup: GroupHandle;
157
+ /** Post-commit epoch the group is now at (== newGroup.epoch). NOTE: this is
158
+ * NOT the epoch carried in the commit's wire header — a commit is framed at
159
+ * the sender's pre-commit epoch (== epoch - 1n), which is what receivers
160
+ * compare against their own handle.epoch for ordering (see readMessageEpoch). */
161
+ epoch: bigint;
162
+ };
163
+ /**
164
+ * Remove a member from the group. Advances the epoch and rotates keys.
165
+ */
166
+ export declare function removeMember(group: GroupHandle, leafIndex: number): Promise<RemoveMemberResult>;
167
+ /**
168
+ * Read the MLS epoch from a framed handshake/application message's cleartext
169
+ * header, without decrypting. Advisory only — the header epoch is unauthenticated;
170
+ * use it to drop stale / buffer future messages before the authenticated
171
+ * processMessage. Returns undefined for non-message or undecodable bytes.
172
+ *
173
+ * Total by contract: this is a safe pre-filter over bytes arriving from an
174
+ * untrusted Delivery Service, so it never throws. ts-mls `decode` throws (e.g.
175
+ * CodecError on input larger than its max size) rather than returning undefined
176
+ * for some malformed inputs; that is caught and treated as "not a message".
177
+ */
178
+ export declare function readMessageEpoch(bytes: Uint8Array): bigint | undefined;
179
+ export type InspectGroupInfoResult = {
180
+ /** The GroupInfo's epoch, read from its groupContext. */
181
+ epoch: bigint;
182
+ /** The GroupInfo's ratchet-tree hash, read from its groupContext. Compare for
183
+ * equality against a known post-commit state's treeHash to confirm canonical
184
+ * convergence (same epoch + same treeHash ⟺ same group state). */
185
+ treeHash: Uint8Array;
186
+ };
187
+ /**
188
+ * Non-destructively inspect a framed MLSMessage(GroupInfo) — read its epoch and
189
+ * ratchet-tree hash without joining or mutating any state. Used to confirm an
190
+ * external-resync Commit was canonically accepted: compare the returned
191
+ * (epoch, treeHash) for equality against the rejoiner's own post-commit state
192
+ * (GroupHandle.epoch / GroupHandle.treeHash). Equal ⟹ this device's Commit won
193
+ * the epoch; unequal ⟹ another Commit won and the rejoin must retry.
194
+ *
195
+ * Structural read only: it does NOT verify the GroupInfo signature. The caller
196
+ * is expected to have obtained the bytes over the group's authorized channel.
197
+ * Unlike readMessageEpoch (a total pre-filter over untrusted DS bytes), this
198
+ * THROWS on malformed input — a malformed already-trusted GroupInfo is a
199
+ * programming error, not expected traffic.
200
+ */
201
+ export declare function inspectGroupInfo(groupInfoBytes: Uint8Array): InspectGroupInfoResult;
202
+ /**
203
+ * Generate a key package for joining groups.
204
+ */
205
+ export declare function createKeyPackageBundle(identity: OwnIdentity, options?: GroupOptions): Promise<KeyPackageBundle>;
206
+ export type ExportGroupInfoParams = {
207
+ group: GroupHandle;
208
+ };
209
+ export type ExportGroupInfoResult = {
210
+ /** Framed MLSMessage(GroupInfo) bytes. Self-describing with protocol
211
+ * version + wireformat + GroupInfo (external_pub + ratchet tree embedded). */
212
+ groupInfo: Uint8Array;
213
+ };
214
+ export declare function exportGroupInfo(params: ExportGroupInfoParams): Promise<ExportGroupInfoResult>;
215
+ export type JoinGroupExternalParams = {
216
+ identity: OwnIdentity;
217
+ /** Framed MLSMessage(GroupInfo) bytes from exportGroupInfo. */
218
+ groupInfo: Uint8Array;
219
+ /** Caller's cached credential (from prior processWelcome). Reused as-is,
220
+ * not re-validated. */
221
+ credential: MemberCredential;
222
+ /** Stale-recovery only: atomically removes prior leaf for same identity. */
223
+ resync: true;
224
+ options?: GroupOptions;
225
+ authenticatedData?: Uint8Array;
226
+ };
227
+ export type JoinGroupExternalResult = {
228
+ /** Framed MLSMessage(PublicMessage) bytes. Broadcast to existing members. */
229
+ commitMessage: Uint8Array;
230
+ /** New GroupHandle at post-commit epoch. */
231
+ group: GroupHandle;
232
+ };
233
+ export declare function joinGroupExternal(params: JoinGroupExternalParams): Promise<JoinGroupExternalResult>;