@kumiai/mls 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,10 +10,33 @@ Credential-aware MLS (RFC 9420) group lifecycle for enkaku. Wraps [`ts-mls`](htt
10
10
  - `commitLedgerEntries` — an admin promotes or demotes by committing signed `kumiai.role` entries
11
11
  - `removeMember` — an admin evicts a leaf and rotates keys
12
12
  - `restoreGroup` — rehydrate a `GroupHandle` from persisted `ClientState` and the stored ledger tokens
13
+ - `GroupHandle.processMessage(message, { persist? })` and `bootstrapLedger(tokens, { persist? })` — persist accepted commits, proposals, or a ledger bootstrap before notifications; a rejected persist restores the prior in-memory state. Application-message receive ratchets are not persisted by this option. Persist runs under the handle mutex, so it must not call back into that handle. Writes must be atomic: rejection must leave storage unchanged.
13
14
  - `encodeKeyPackage` + `decodeKeyPackage` — convert a key package to and from the opaque string a hub stores; decode is strict and returns `null` rather than throwing
14
15
  - `encodePrivateKeyPackage` + `decodePrivateKeyPackage` — the canonical string form of a key package's **private** half, for a host that must persist it across restarts (a reusable last-resort package outlives the process that made it). Secret material: never publish or log it.
15
16
  - `keyPackageRef` — the base64 KeyPackageRef a Welcome names, stable across a codec round trip. Use it as the identity of a stored package.
16
17
  - `exportGroupInfo` + `joinGroupExternal` — stale-device self-rejoin (see below)
18
+ - `GroupHandle.decryptStaged` — open an app frame while withholding its consumed-key state until
19
+ a host has atomically saved that state and its pending delivery record
20
+ - `readMessageAAD(bytes)` — read a PrivateMessage's cleartext authenticated data without a key;
21
+ returns `null` for unreadable bytes and never throws
22
+
23
+ ## Persisting a staged app open
24
+
25
+ `await group.decryptStaged(message, { expectedAAD }, async (stagedState, opened) => { ... })`
26
+ computes the post-open state under the handle mutex but does not adopt it until the callback
27
+ resolves. `stagedState` is encoded `ClientState`, in the same format the host already stores for
28
+ `restoreGroup`; save these bytes as the group's handle state, together with the pending record,
29
+ in one atomic transaction. `opened` contains `payload`, authenticated `senderDID`, and `aad`.
30
+ An unnamed sender is rejected before the callback. If opening or persistence fails, the live
31
+ state and its message key remain available for retry. After persistence succeeds, the handle
32
+ adopts the staged state and the same frame cannot open again.
33
+
34
+ The callback runs while the handle mutex is held. It must not call this handle or its peer.
35
+ The host must order earlier handle saves before the staged write and reject older writes at the
36
+ same epoch using a monotonic state version; otherwise an earlier delayed save can overwrite the
37
+ consumed-key state while leaving the pending record. No database transaction or single connection
38
+ may be held while awaiting a handle or peer operation. The real `@kumiai/mls-rpc` port's optional
39
+ `pending` adapter calls `decryptStaged` for durable logged events.
17
40
 
18
41
  ## Authority model
19
42
 
package/lib/codec.js CHANGED
@@ -29,7 +29,8 @@ export function decodeClientState(encoded) {
29
29
  if (encoded[0] !== CLIENT_STATE_VERSION) {
30
30
  throw new Error(`decodeClientState: unsupported client-state version ${encoded[0]}`);
31
31
  }
32
- return decode(clientStateDecoder, encoded.subarray(1));
32
+ // A copy: ts-mls decodes secrets as views, and ratcheting zeroes consumed ones in place.
33
+ return decode(clientStateDecoder, encoded.slice(1));
33
34
  }
34
35
  export function encodeClientState(state) {
35
36
  const body = encode(clientStateEncoder, state);
@@ -1,5 +1,5 @@
1
1
  import { EventEmitter, type EventsSource } from '@sozai/event';
2
- import { type ClientState, type IncomingMessageCallback, type MlsContext, type ProposalWithSender } from 'ts-mls';
2
+ import { type ClientState, type IncomingMessageCallback, type MlsContext, type MlsFramedMessage, type ProposalWithSender } from 'ts-mls';
3
3
  import { type GroupAnchor } from './anchor.js';
4
4
  import { type GroupMember, type MemberCredential } from './credential.js';
5
5
  import { type LeafBinding } from './device-proof.js';
@@ -177,9 +177,13 @@ export declare class GroupHandle {
177
177
  * signatures do not. The bound: **a lying responder can withhold, never rewrite.**
178
178
  *
179
179
  * Throws {@link LedgerIncompleteError} on a head mismatch; the caller drops that
180
- * responder and tries the next.
180
+ * responder and tries the next. `persist` runs under this handle's mutex and must not
181
+ * call back into it. It must write atomically: rejection means nothing was stored.
182
+ * Host callbacks run after successful persist; a callback throw does not undo bootstrap.
181
183
  */
182
- bootstrapLedger(tokens: Array<string>): Promise<void>;
184
+ bootstrapLedger(tokens: Array<string>, opts?: {
185
+ persist?: (handle: GroupHandle) => Promise<void> | void;
186
+ }): Promise<void>;
183
187
  get memberCount(): number;
184
188
  findMemberLeafIndex(id: string): number | undefined;
185
189
  /**
@@ -200,10 +204,10 @@ export declare class GroupHandle {
200
204
  * The diff sees MEMBERSHIP, and only membership: an Add, a Remove, or both in
201
205
  * one commit (compare as a set — a count misses that last case). It does NOT
202
206
  * see an external-commit REJOIN by a member the group still holds. That member
203
- * keeps its id, so the id set is unchanged; and its leaf index is unchanged
204
- * too, because a resync blanks the member's old leaf and the new leaf then
205
- * takes the leftmost blank — the one just blanked (RFC 9420 §12.4.3.2). No
206
- * field of this result moves, and no before/after diff of it can be made to.
207
+ * keeps its id, so the id set is unchanged; the new leaf takes the leftmost blank, which is the
208
+ * just-vacated slot only when no earlier blank exists — otherwise the rejoiner's `leafIndex`
209
+ * moves. Only the id-set projection of this result is guaranteed unchanged across a rejoin;
210
+ * `leafIndex` is not, so a before/after diff on `leafIndex` cannot be relied on either.
207
211
  * A caller that must detect a rejoin reads the COMMIT instead — an external
208
212
  * commit is structurally one: a public message from a non-member carrying a
209
213
  * commit, recognizable from its own bytes before it is applied, and carrying
@@ -242,18 +246,22 @@ export declare class GroupHandle {
242
246
  * {@link commitInvite}, {@link removeMember}, {@link commitLedgerEntries}) must not
243
247
  * be reused to send — it silently emits at the now-stale epoch. Adopt the commit's
244
248
  * `newGroup` and encrypt on that.
249
+ *
250
+ * `opts.aad` becomes the frame's MLS `authenticated_data` — bound into the AEAD but
251
+ * carried in the clear, so a caller reading it back (or comparing via `decrypt`'s
252
+ * `expectedAAD`) needs no key. Defaults to empty.
245
253
  */
246
- encrypt(plaintext: Uint8Array): Promise<Uint8Array>;
254
+ encrypt(plaintext: Uint8Array, opts?: {
255
+ aad?: Uint8Array;
256
+ }): Promise<Uint8Array>;
247
257
  /**
248
258
  * Open an application message sealed for the group and recover WHO SENT IT — the
249
259
  * counterpart to {@link encrypt}, and the read half of the group's application lane.
250
260
  *
251
- * Throws for bytes this handle cannot open, which for an application message means
252
- * ANY epoch but its own: MLS ratchets forward, so a frame sealed below this handle's
253
- * epoch is gone and one sealed above it has not arrived yet. That is ordinary control
254
- * flow for a caller walking a retained log full of frames from epochs it does not hold
255
- * — it is how a frame says "not mine" — and such a caller must not read the throw as
256
- * corruption. Use {@link readMessageEpoch} to tell those two cases apart before trying.
261
+ * Throws for bytes this handle cannot open. A future-epoch frame cannot open yet;
262
+ * ts-mls can open some past-epoch frames while their retained key material lasts.
263
+ * That window is bounded by epoch transitions. Use {@link readMessageEpoch} to
264
+ * distinguish an epoch mismatch from malformed bytes before trying.
257
265
  *
258
266
  * WHY THE SENDER IS AUTHENTICATED and not merely claimed: the leaf index comes from the
259
267
  * message's sender-data, encrypted under this epoch's sender-data secret, and the
@@ -267,10 +275,35 @@ export declare class GroupHandle {
267
275
  *
268
276
  * ts-mls's own `processMessage` returns an application message's plaintext WITHOUT any
269
277
  * sender, which is why this exists rather than delegating.
278
+ *
279
+ * `opts.expectedAAD`, when given, is compared against the frame's CLEARTEXT
280
+ * `authenticatedData` BEFORE `mlsProcessMessage` runs — a mismatch throws having consumed
281
+ * no ratchet generation, so a wrong-topic frame costs nothing to reject. The frame's AAD
282
+ * is always returned, whether or not `expectedAAD` was given.
270
283
  */
271
- decrypt(message: Uint8Array): Promise<{
284
+ decrypt(message: Uint8Array, opts?: {
285
+ expectedAAD?: Uint8Array;
286
+ }): Promise<{
272
287
  payload: Uint8Array;
273
288
  senderDID?: string;
289
+ aad: Uint8Array;
290
+ }>;
291
+ /**
292
+ * Open an application frame, but make its post-open state durable before adopting it.
293
+ * The callback runs under this handle's mutex and must store `stagedState` as the
294
+ * group's handle state. It must not call this handle or the peer. If opening or
295
+ * persistence fails, the live state and its ratchet secrets remain untouched.
296
+ */
297
+ decryptStaged(message: Uint8Array, opts: {
298
+ expectedAAD?: Uint8Array;
299
+ }, persist: (stagedState: Uint8Array, opened: {
300
+ payload: Uint8Array;
301
+ senderDID: string;
302
+ aad: Uint8Array;
303
+ }) => Promise<void>): Promise<{
304
+ payload: Uint8Array;
305
+ senderDID: string;
306
+ aad: Uint8Array;
274
307
  }>;
275
308
  /**
276
309
  * The device-proof binding at the leaf naming `did`: its bound controller (if any), the embedded
@@ -321,11 +354,15 @@ export declare class GroupHandle {
321
354
  /**
322
355
  * Process a received MLS message (Commit, Proposal, or application). Accepts
323
356
  * wire-form bytes (preferred, e.g. from commitInvite/removeMember) or a pre-decoded
324
- * ts-mls object (legacy). Param widens to `unknown` because `Uint8Array | unknown`
325
- * collapses to `unknown`; the runtime `instanceof` selects the decode path.
357
+ * ts-mls framed message (legacy). The runtime `instanceof` selects the decode path.
358
+ * `persist` covers accepted commits and proposals, not application messages or their
359
+ * receive ratchet. It runs under this handle's mutex and must not call back into it.
360
+ * It must write atomically: rejection means nothing was stored. Host callbacks run
361
+ * after successful persist; a callback throw does not undo an advance.
326
362
  */
327
- processMessage(message: Uint8Array | unknown, opts?: {
363
+ processMessage(message: Uint8Array | MlsFramedMessage, opts?: {
328
364
  commitPolicy?: IncomingMessageCallback;
365
+ persist?: (handle: GroupHandle) => Promise<void> | void;
329
366
  }): Promise<Uint8Array | null>;
330
367
  }
331
368
  /** Build the CommitPolicyContext both the receive gate and the send-side pending
@@ -2,6 +2,7 @@ import { normalizeDID } from '@kokuin/token';
2
2
  import { EventEmitter } from '@sozai/event';
3
3
  import { contentTypes, createApplicationMessage, decode, encode, mlsExporter, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, wireformats } from 'ts-mls';
4
4
  import { readGroupAnchor } from './anchor.js';
5
+ import { encodeClientState } from './codec.js';
5
6
  import { parseMLSCredentialIdentity } from './credential.js';
6
7
  import { verifyDeviceEntry } from './device-proof.js';
7
8
  import { decodeControlEnvelope } from './envelope.js';
@@ -37,6 +38,11 @@ export function mutexFor(handle) {
37
38
  * material does not linger in the heap after the state that used it is replaced. */ function zeroAll(buffers) {
38
39
  for (const buffer of buffers)buffer.fill(0);
39
40
  }
41
+ /** AAD is not secret, so a length/byte compare is enough — no constant-time need. */ function bytesEqual(a, b) {
42
+ if (a.length !== b.length) return false;
43
+ for(let i = 0; i < a.length; i++)if (a[i] !== b[i]) return false;
44
+ return true;
45
+ }
40
46
  /** Thrown by GroupHandle.processMessage when the commit policy rejects an incoming
41
47
  * commit. The handle is left at its pre-commit epoch. */ export class CommitRejectedError extends Error {
42
48
  #proposals;
@@ -100,7 +106,7 @@ export function mutexFor(handle) {
100
106
  if (frame.wireformat !== wireformats.mls_private_message) return undefined;
101
107
  const pm = frame.privateMessage;
102
108
  if (pm == null || pm.contentType !== contentType) return undefined;
103
- if (!(pm.groupId instanceof Uint8Array) || typeof pm.epoch !== 'bigint' || !(pm.encryptedSenderData instanceof Uint8Array) || !(pm.ciphertext instanceof Uint8Array)) {
109
+ if (!(pm.groupId instanceof Uint8Array) || typeof pm.epoch !== 'bigint' || !(pm.encryptedSenderData instanceof Uint8Array) || !(pm.ciphertext instanceof Uint8Array) || !(pm.authenticatedData instanceof Uint8Array)) {
104
110
  return undefined;
105
111
  }
106
112
  return {
@@ -108,7 +114,8 @@ export function mutexFor(handle) {
108
114
  epoch: pm.epoch,
109
115
  contentType: pm.contentType,
110
116
  encryptedSenderData: pm.encryptedSenderData,
111
- ciphertext: pm.ciphertext
117
+ ciphertext: pm.ciphertext,
118
+ authenticatedData: pm.authenticatedData
112
119
  };
113
120
  }
114
121
  /**
@@ -322,6 +329,21 @@ export function mutexFor(handle) {
322
329
  }
323
330
  if (revoked.length > 0) emitter.fire('deviceRevoked', revoked);
324
331
  }
332
+ /** Deliver independent host notifications after acceptance and any requested persist. */ #notifyAccepted(surfaced, enactedDevice) {
333
+ const errors = [];
334
+ try {
335
+ if (surfaced.length > 0) this.#onLedgerEntries?.(surfaced);
336
+ } catch (error) {
337
+ errors.push(error);
338
+ }
339
+ try {
340
+ this.emitControlEvents(enactedDevice);
341
+ } catch (error) {
342
+ errors.push(error);
343
+ }
344
+ if (errors.length === 1) throw errors[0];
345
+ if (errors.length > 1) throw new AggregateError(errors, 'host notifications failed');
346
+ }
325
347
  /**
326
348
  * Verify signed ledger tokens, append the valid ones in the order given, and
327
349
  * refold the roster. Tokens that fail verification or whose groupID mismatches are
@@ -409,8 +431,10 @@ export function mutexFor(handle) {
409
431
  * signatures do not. The bound: **a lying responder can withhold, never rewrite.**
410
432
  *
411
433
  * Throws {@link LedgerIncompleteError} on a head mismatch; the caller drops that
412
- * responder and tries the next.
413
- */ async bootstrapLedger(tokens) {
434
+ * responder and tries the next. `persist` runs under this handle's mutex and must not
435
+ * call back into it. It must write atomically: rejection means nothing was stored.
436
+ * Host callbacks run after successful persist; a callback throw does not undo bootstrap.
437
+ */ async bootstrapLedger(tokens, opts) {
414
438
  return mutexFor(this).run(async ()=>{
415
439
  const authenticated = readLedgerHead(this);
416
440
  if (authenticated == null) {
@@ -442,6 +466,14 @@ export function mutexFor(handle) {
442
466
  // Same dedupe as `surfaced`, narrowed to device entries — feeds emitControlEvents below so a
443
467
  // heal fires deviceRevoked for entries this bootstrap actually adds, not ones already held.
444
468
  const enactedDevice = log.filter(({ entryID, verified })=>!this.#entryBodies.has(entryID) && verified.entry.type === DEVICE_ENTRY_TYPE).map(({ verified })=>verified);
469
+ const previous = {
470
+ state: this.#state,
471
+ ledger: this.#ledger,
472
+ entryBodies: this.#entryBodies,
473
+ roster: this.#roster,
474
+ registry: this.#registry
475
+ };
476
+ const folded = foldLedgerControl(log, this.#anchor, this.groupID);
445
477
  this.#ledger = log;
446
478
  this.#entryBodies = new Map(log.map(({ entryID, token, verified })=>[
447
479
  entryID,
@@ -450,9 +482,18 @@ export function mutexFor(handle) {
450
482
  verified
451
483
  }
452
484
  ]));
453
- const folded = foldLedgerControl(log, this.#anchor, this.groupID);
454
485
  this.#roster = folded.roster;
455
486
  this.#registry = folded.registry;
487
+ try {
488
+ await opts?.persist?.(this);
489
+ } catch (error) {
490
+ this.#state = previous.state;
491
+ this.#ledger = previous.ledger;
492
+ this.#entryBodies = previous.entryBodies;
493
+ this.#roster = previous.roster;
494
+ this.#registry = previous.registry;
495
+ throw error;
496
+ }
456
497
  // SURFACED HERE TOO, not only on the commit path. A heal is how a peer that missed commits
457
498
  // catches up — it rejoins, gathers the whole ledger, and lands here — so a bootstrap that
458
499
  // said nothing left a host consuming `onLedgerEntries` as an event stream permanently
@@ -461,8 +502,7 @@ export function mutexFor(handle) {
461
502
  //
462
503
  // Deduped against what this handle already held, so a peer bootstrapping over a partial
463
504
  // ledger is not re-notified of entries it has already seen.
464
- if (surfaced.length > 0) this.#onLedgerEntries?.(surfaced);
465
- this.emitControlEvents(enactedDevice);
505
+ this.#notifyAccepted(surfaced, enactedDevice);
466
506
  });
467
507
  }
468
508
  get memberCount() {
@@ -533,10 +573,10 @@ export function mutexFor(handle) {
533
573
  * The diff sees MEMBERSHIP, and only membership: an Add, a Remove, or both in
534
574
  * one commit (compare as a set — a count misses that last case). It does NOT
535
575
  * see an external-commit REJOIN by a member the group still holds. That member
536
- * keeps its id, so the id set is unchanged; and its leaf index is unchanged
537
- * too, because a resync blanks the member's old leaf and the new leaf then
538
- * takes the leftmost blank — the one just blanked (RFC 9420 §12.4.3.2). No
539
- * field of this result moves, and no before/after diff of it can be made to.
576
+ * keeps its id, so the id set is unchanged; the new leaf takes the leftmost blank, which is the
577
+ * just-vacated slot only when no earlier blank exists — otherwise the rejoiner's `leafIndex`
578
+ * moves. Only the id-set projection of this result is guaranteed unchanged across a rejoin;
579
+ * `leafIndex` is not, so a before/after diff on `leafIndex` cannot be relied on either.
540
580
  * A caller that must detect a rejoin reads the COMMIT instead — an external
541
581
  * commit is structurally one: a public message from a non-member carrying a
542
582
  * commit, recognizable from its own bytes before it is applied, and carrying
@@ -579,12 +619,17 @@ export function mutexFor(handle) {
579
619
  * {@link commitInvite}, {@link removeMember}, {@link commitLedgerEntries}) must not
580
620
  * be reused to send — it silently emits at the now-stale epoch. Adopt the commit's
581
621
  * `newGroup` and encrypt on that.
582
- */ async encrypt(plaintext) {
622
+ *
623
+ * `opts.aad` becomes the frame's MLS `authenticated_data` — bound into the AEAD but
624
+ * carried in the clear, so a caller reading it back (or comparing via `decrypt`'s
625
+ * `expectedAAD`) needs no key. Defaults to empty.
626
+ */ async encrypt(plaintext, opts) {
583
627
  return mutexFor(this).run(async ()=>{
584
628
  const { newState, message, consumed } = await createApplicationMessage({
585
629
  context: this.#context,
586
630
  state: this.#state,
587
- message: plaintext
631
+ message: plaintext,
632
+ authenticatedData: opts?.aad ?? new Uint8Array()
588
633
  });
589
634
  this.#state = newState;
590
635
  zeroAll(consumed);
@@ -595,12 +640,10 @@ export function mutexFor(handle) {
595
640
  * Open an application message sealed for the group and recover WHO SENT IT — the
596
641
  * counterpart to {@link encrypt}, and the read half of the group's application lane.
597
642
  *
598
- * Throws for bytes this handle cannot open, which for an application message means
599
- * ANY epoch but its own: MLS ratchets forward, so a frame sealed below this handle's
600
- * epoch is gone and one sealed above it has not arrived yet. That is ordinary control
601
- * flow for a caller walking a retained log full of frames from epochs it does not hold
602
- * — it is how a frame says "not mine" — and such a caller must not read the throw as
603
- * corruption. Use {@link readMessageEpoch} to tell those two cases apart before trying.
643
+ * Throws for bytes this handle cannot open. A future-epoch frame cannot open yet;
644
+ * ts-mls can open some past-epoch frames while their retained key material lasts.
645
+ * That window is bounded by epoch transitions. Use {@link readMessageEpoch} to
646
+ * distinguish an epoch mismatch from malformed bytes before trying.
604
647
  *
605
648
  * WHY THE SENDER IS AUTHENTICATED and not merely claimed: the leaf index comes from the
606
649
  * message's sender-data, encrypted under this epoch's sender-data secret, and the
@@ -614,12 +657,22 @@ export function mutexFor(handle) {
614
657
  *
615
658
  * ts-mls's own `processMessage` returns an application message's plaintext WITHOUT any
616
659
  * sender, which is why this exists rather than delegating.
617
- */ async decrypt(message) {
660
+ *
661
+ * `opts.expectedAAD`, when given, is compared against the frame's CLEARTEXT
662
+ * `authenticatedData` BEFORE `mlsProcessMessage` runs — a mismatch throws having consumed
663
+ * no ratchet generation, so a wrong-topic frame costs nothing to reject. The frame's AAD
664
+ * is always returned, whether or not `expectedAAD` was given.
665
+ */ async decrypt(message, opts) {
618
666
  const decoded = decode(mlsMessageDecoder, message);
619
667
  if (decoded == null) throw new Error('decrypt: failed to decode MLSMessage');
620
668
  return mutexFor(this).run(async ()=>{
621
669
  const pm = readPrivateFrame(decoded, contentTypes.application);
622
670
  if (pm == null) throw new Error('decrypt: not a PrivateMessage application frame');
671
+ // Pre-open: reject a wrong-topic frame from its CLEARTEXT authenticatedData before
672
+ // mlsProcessMessage consumes a ratchet generation. Same lane as the sender-leaf read below.
673
+ if (opts?.expectedAAD != null && !bytesEqual(pm.authenticatedData, opts.expectedAAD)) {
674
+ throw new Error('decrypt: frame authenticated data does not match expected AAD');
675
+ }
623
676
  // Read the sender BEFORE opening: the sender-data secret is epoch-level and this
624
677
  // consumes no ratchet key, so a frame that then fails to open has cost nothing.
625
678
  const leafIndex = await readSenderLeafIndex(this.#context, this.#state.keySchedule.senderDataSecret, pm);
@@ -636,6 +689,7 @@ export function mutexFor(handle) {
636
689
  const senderDID = leafIndex == null ? undefined : this.#didOfLeaf(leafIndex);
637
690
  return {
638
691
  payload: result.message,
692
+ aad: result.aad,
639
693
  ...senderDID != null && {
640
694
  senderDID
641
695
  }
@@ -643,6 +697,42 @@ export function mutexFor(handle) {
643
697
  });
644
698
  }
645
699
  /**
700
+ * Open an application frame, but make its post-open state durable before adopting it.
701
+ * The callback runs under this handle's mutex and must store `stagedState` as the
702
+ * group's handle state. It must not call this handle or the peer. If opening or
703
+ * persistence fails, the live state and its ratchet secrets remain untouched.
704
+ */ async decryptStaged(message, opts, persist) {
705
+ const decoded = decode(mlsMessageDecoder, message);
706
+ if (decoded == null) throw new Error('decryptStaged: failed to decode MLSMessage');
707
+ return mutexFor(this).run(async ()=>{
708
+ const pm = readPrivateFrame(decoded, contentTypes.application);
709
+ if (pm == null) throw new Error('decryptStaged: not a PrivateMessage application frame');
710
+ if (opts.expectedAAD != null && !bytesEqual(pm.authenticatedData, opts.expectedAAD)) {
711
+ throw new Error('decryptStaged: frame authenticated data does not match expected AAD');
712
+ }
713
+ const leafIndex = await readSenderLeafIndex(this.#context, this.#state.keySchedule.senderDataSecret, pm);
714
+ const result = await mlsProcessMessage({
715
+ context: this.#context,
716
+ state: this.#state,
717
+ message: decoded
718
+ });
719
+ if (result.kind !== 'applicationMessage') {
720
+ throw new Error('decryptStaged: frame was not an application message');
721
+ }
722
+ const senderDID = leafIndex == null ? undefined : this.#didOfLeaf(leafIndex);
723
+ if (senderDID == null) throw new Error('decryptStaged: unnamed sender');
724
+ const opened = {
725
+ payload: result.message,
726
+ senderDID,
727
+ aad: result.aad
728
+ };
729
+ await persist(encodeClientState(result.newState), opened);
730
+ this.#state = result.newState;
731
+ zeroAll(result.consumed);
732
+ return opened;
733
+ });
734
+ }
735
+ /**
646
736
  * The async pre-pass feeding the synchronous ts-mls commit callback, run before
647
737
  * mlsProcessMessage. For anything that is not a PrivateMessage commit it just
648
738
  * resolves the caller policy, wraps it for rejected-proposal capture, and applies
@@ -780,7 +870,7 @@ export function mutexFor(handle) {
780
870
  if (callerPolicy != null) return callerPolicy(incoming);
781
871
  return defaultCommitPolicy(incoming, context);
782
872
  };
783
- const applyOnAccept = ()=>{
873
+ const applyOnAccept = (notify = true)=>{
784
874
  // Appended, never deduped: the log records what this commit enacted, at the
785
875
  // position the head chained it.
786
876
  for (const { token, verified, entryID } of acceptedEntries){
@@ -796,8 +886,11 @@ export function mutexFor(handle) {
796
886
  }
797
887
  this.#roster = candidateRoster;
798
888
  this.#registry = candidateRegistry;
799
- if (surfaced.length > 0) this.#onLedgerEntries?.(surfaced);
800
- this.emitControlEvents(acceptedEntries.filter(({ verified })=>verified.entry.type === DEVICE_ENTRY_TYPE).map(({ verified })=>verified));
889
+ const emit = ()=>{
890
+ this.#notifyAccepted(surfaced, acceptedEntries.filter(({ verified })=>verified.entry.type === DEVICE_ENTRY_TYPE).map(({ verified })=>verified));
891
+ };
892
+ if (notify) emit();
893
+ return emit;
801
894
  };
802
895
  return {
803
896
  callback: wrapCommitPolicy(combined, capture),
@@ -938,10 +1031,10 @@ export function mutexFor(handle) {
938
1031
  //
939
1032
  // `external: true` is reported, not just consumed to find the committer: a resync rejoin
940
1033
  // is invisible to every before/after diff a caller could run — it changes no member DID
941
- // (the roster already held it) and no occupied leaf index (the new leaf lands on the
942
- // leftmost blank, which is the one the resync just blanked). A caller that must know the
943
- // group's membership shifted has no other way to see it, so the fact is surfaced here
944
- // rather than discarded. Absent means a member commit.
1034
+ // (the roster already held it); its leaf lands on the leftmost blank and may shift, but
1035
+ // the DID set is unchanged. A caller that must know the group's membership shifted has no
1036
+ // other way to see it, so the fact is surfaced here rather than discarded. Absent means a
1037
+ // member commit.
945
1038
  const external = readExternalCommit(decoded);
946
1039
  if (external != null) {
947
1040
  // It IS a commit, so it gets a header even when the leaf credential will not parse to a
@@ -986,8 +1079,11 @@ export function mutexFor(handle) {
986
1079
  /**
987
1080
  * Process a received MLS message (Commit, Proposal, or application). Accepts
988
1081
  * wire-form bytes (preferred, e.g. from commitInvite/removeMember) or a pre-decoded
989
- * ts-mls object (legacy). Param widens to `unknown` because `Uint8Array | unknown`
990
- * collapses to `unknown`; the runtime `instanceof` selects the decode path.
1082
+ * ts-mls framed message (legacy). The runtime `instanceof` selects the decode path.
1083
+ * `persist` covers accepted commits and proposals, not application messages or their
1084
+ * receive ratchet. It runs under this handle's mutex and must not call back into it.
1085
+ * It must write atomically: rejection means nothing was stored. Host callbacks run
1086
+ * after successful persist; a callback throw does not undo an advance.
991
1087
  */ async processMessage(message, opts) {
992
1088
  let decoded = message;
993
1089
  if (message instanceof Uint8Array) {
@@ -999,6 +1095,7 @@ export function mutexFor(handle) {
999
1095
  }
1000
1096
  return mutexFor(this).run(async ()=>{
1001
1097
  const { callback, capture, applyOnAccept } = await this.#prepareCommitPipeline(decoded, opts);
1098
+ const previousState = this.#state;
1002
1099
  const result = await mlsProcessMessage({
1003
1100
  context: this.#context,
1004
1101
  state: this.#state,
@@ -1008,14 +1105,42 @@ export function mutexFor(handle) {
1008
1105
  }
1009
1106
  });
1010
1107
  this.#state = result.newState;
1011
- zeroAll(result.consumed);
1012
1108
  if (result.kind === 'newState' && result.actionTaken === 'reject') {
1109
+ zeroAll(result.consumed);
1013
1110
  throw new CommitRejectedError(capture.rejected?.proposals ?? [], capture.rejected?.senderLeafIndex);
1014
1111
  }
1015
1112
  if (result.kind === 'applicationMessage') {
1113
+ zeroAll(result.consumed);
1016
1114
  return result.message;
1017
1115
  }
1018
- applyOnAccept();
1116
+ if (opts?.persist != null) {
1117
+ const previousLedger = this.#ledger;
1118
+ const previousEntryBodies = this.#entryBodies;
1119
+ const previousRoster = this.#roster;
1120
+ const previousRegistry = this.#registry;
1121
+ // The accept callback appends to these collections. Give the tentative
1122
+ // state its own copies so rollback restores the exact old objects.
1123
+ this.#ledger = [
1124
+ ...previousLedger
1125
+ ];
1126
+ this.#entryBodies = new Map(previousEntryBodies);
1127
+ const notify = applyOnAccept(false);
1128
+ try {
1129
+ await opts.persist(this);
1130
+ } catch (error) {
1131
+ this.#state = previousState;
1132
+ this.#ledger = previousLedger;
1133
+ this.#entryBodies = previousEntryBodies;
1134
+ this.#roster = previousRoster;
1135
+ this.#registry = previousRegistry;
1136
+ throw error;
1137
+ }
1138
+ zeroAll(result.consumed);
1139
+ notify();
1140
+ } else {
1141
+ zeroAll(result.consumed);
1142
+ applyOnAccept();
1143
+ }
1019
1144
  return null;
1020
1145
  });
1021
1146
  }
@@ -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
@@ -1,4 +1,5 @@
1
1
  import { type OwnIdentity } from '@kokuin/token';
2
+ import { type Welcome } from 'ts-mls';
2
3
  import type { MemberCredential } from './credential.js';
3
4
  import { GroupHandle } from './group-handle.js';
4
5
  import type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
@@ -10,9 +11,8 @@ export type ProcessWelcomeParams = {
10
11
  identity: OwnIdentity;
11
12
  invite: Invite;
12
13
  /** Wire-form framed MLSMessage(Welcome) bytes (preferred), or a pre-decoded
13
- * ts-mls Welcome object (legacy). `Uint8Array | unknown` collapses to
14
- * `unknown` in TypeScript; the runtime `instanceof` check selects the path. */
15
- welcome: Uint8Array | unknown;
14
+ * ts-mls Welcome object (legacy). */
15
+ welcome: Uint8Array | Welcome;
16
16
  keyPackageBundle: KeyPackageBundle;
17
17
  ratchetTree?: unknown;
18
18
  options?: GroupOptions;
package/lib/group.d.ts CHANGED
@@ -3,6 +3,6 @@ export { type CreateGroupResult, createGroup, type RestoreGroupParams, restoreGr
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
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';
6
+ export { type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, type GroupInfoBinding, type InspectGroupInfoResult, inspectGroupInfo, readCommitEntryIDs, readGroupInfoBinding, readMessageAAD, readMessageEpoch, } from './group-info.js';
7
7
  export { type RemoveMemberResult, removeMember } from './group-membership.js';
8
8
  export { type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, type ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, } from './group-welcome.js';
package/lib/group.js CHANGED
@@ -3,6 +3,6 @@ export { createGroup, 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, labelDevice, registerDevice, revokeDevice } from './group-device.js';
5
5
  export { CommitRejectedError, GroupHandle } from './group-handle.js';
6
- export { exportGroupInfo, inspectGroupInfo, readGroupInfoBinding, readMessageEpoch } from './group-info.js';
6
+ export { exportGroupInfo, inspectGroupInfo, readCommitEntryIDs, readGroupInfoBinding, readMessageAAD, readMessageEpoch } from './group-info.js';
7
7
  export { removeMember } from './group-membership.js';
8
8
  export { joinGroupExternal, processWelcome, processWelcomeOnce } from './group-welcome.js';
package/lib/index.d.ts CHANGED
@@ -10,7 +10,7 @@ export type { LeafBinding } from './device-proof.js';
10
10
  export { CONTROL_ENVELOPE_VERSION, type ControlEnvelope, type DecodeResult, decodeControlEnvelope, encodeControlEnvelope, } from './envelope.js';
11
11
  export { type EnvelopeFoldResult, foldEnvelope } from './envelope-fold.js';
12
12
  export { type FoldDrop, type FoldInput, foldLedger, type LedgerReducer, } from './fold.js';
13
- export { addDevice, announceControllerBeacon, type CommitInviteResult, type CommitLedgerEntriesResult, CommitRejectedError, type CreateGroupResult, type CreateInviteParams, type CreateInviteResult, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, type DeviceWriteResult, type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, GroupHandle, type GroupHandleEvents, type GroupHandleParams, type HeldLedgerEntry, type InspectGroupInfoResult, InviteRecipientMismatchError, type InviteRecipientMismatchErrorParams, inspectGroupInfo, type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, type LedgerLogEntry, labelDevice, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, type ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, type RemoveMemberResult, type RestoreGroupParams, readMessageEpoch, registerDevice, removeMember, restoreGroup, revokeDevice, } from './group.js';
13
+ export { addDevice, announceControllerBeacon, type CommitInviteResult, type CommitLedgerEntriesResult, CommitRejectedError, type CreateGroupResult, type CreateInviteParams, type CreateInviteResult, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, type DeviceWriteResult, type ExportGroupInfoParams, type ExportGroupInfoResult, exportGroupInfo, GroupHandle, type GroupHandleEvents, type GroupHandleParams, type HeldLedgerEntry, type InspectGroupInfoResult, InviteRecipientMismatchError, type InviteRecipientMismatchErrorParams, inspectGroupInfo, type JoinGroupExternalParams, type JoinGroupExternalResult, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, type LedgerLogEntry, labelDevice, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, type ProcessWelcomeOnceParams, type ProcessWelcomeParams, type ProcessWelcomeResult, processWelcome, processWelcomeOnce, type RemoveMemberResult, type RestoreGroupParams, readCommitEntryIDs, readMessageAAD, readMessageEpoch, registerDevice, removeMember, restoreGroup, revokeDevice, } from './group.js';
14
14
  export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, type LedgerHead, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension, } from './head.js';
15
15
  export { decodeKeyPackage, decodePrivateKeyPackage, encodeKeyPackage, encodePrivateKeyPackage, keyPackageRef, } from './key-package-codec.js';
16
16
  export { type LedgerEntry, ledgerEntryDigest, signLedgerEntry, type VerifiedLedgerEntry, verifyLedgerEntry, } from './ledger.js';
package/lib/index.js CHANGED
@@ -7,7 +7,7 @@ export { createNobleCryptoProvider, nobleCryptoProvider } from './crypto.js';
7
7
  export { CONTROL_ENVELOPE_VERSION, decodeControlEnvelope, encodeControlEnvelope } from './envelope.js';
8
8
  export { foldEnvelope } from './envelope-fold.js';
9
9
  export { foldLedger } from './fold.js';
10
- export { addDevice, announceControllerBeacon, CommitRejectedError, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, exportGroupInfo, GroupHandle, InviteRecipientMismatchError, inspectGroupInfo, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, labelDevice, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, processWelcome, processWelcomeOnce, readMessageEpoch, registerDevice, removeMember, restoreGroup, revokeDevice } from './group.js';
10
+ export { addDevice, announceControllerBeacon, CommitRejectedError, commitInvite, commitLedgerEntries, createGroup, createInvite, createKeyPackageBundle, createLastResortKeyPackageBundle, exportGroupInfo, GroupHandle, InviteRecipientMismatchError, inspectGroupInfo, joinGroupExternal, LAST_RESORT_EXTENSION_TYPE, LAST_RESORT_LIFETIME_DAYS, labelDevice, makeMLSCredential, ORDINARY_KEY_PACKAGE_LIFETIME_DAYS, processWelcome, processWelcomeOnce, readCommitEntryIDs, readMessageAAD, readMessageEpoch, registerDevice, removeMember, restoreGroup, revokeDevice } from './group.js';
11
11
  export { assertHeadMatches, buildLedgerHeadExtension, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, genesisHead, headsMatch, LEDGER_HEAD_VERSION, LedgerIncompleteError, readLedgerHead, readLedgerHeadExtension } from './head.js';
12
12
  export { decodeKeyPackage, decodePrivateKeyPackage, encodeKeyPackage, encodePrivateKeyPackage, keyPackageRef } from './key-package-codec.js';
13
13
  export { ledgerEntryDigest, signLedgerEntry, verifyLedgerEntry } from './ledger.js';
package/lib/policy.js CHANGED
@@ -76,6 +76,7 @@ function bytesEqual(a, b) {
76
76
  for(let i = 0; i < expected.length; i++){
77
77
  const got = candidate[i];
78
78
  const want = expected[i];
79
+ if (got === undefined || want === undefined) return 'reject';
79
80
  if (got.extensionType !== want.extensionType) return 'reject';
80
81
  // Both sides must be raw bytes to compare. ts-mls's extensionsEqual isn't re-exported, so
81
82
  // this hand-rolled compare only handles Uint8Array data; a decoded-object extension (e.g.
@@ -15,6 +15,7 @@ export type PrivateCommitFrame = {
15
15
  contentType: number;
16
16
  encryptedSenderData: Uint8Array;
17
17
  ciphertext: Uint8Array;
18
+ authenticatedData: Uint8Array;
18
19
  };
19
20
  /**
20
21
  * Decrypt a PrivateMessage's sender-data and return the committer's leaf index, or `null`
@@ -1,3 +1,4 @@
1
+ import { type Welcome } from 'ts-mls';
1
2
  /**
2
3
  * The KeyPackageRefs a Welcome names, base64 — one per set of encrypted group secrets it carries.
3
4
  *
@@ -7,4 +8,4 @@
7
8
  * Accepts framed `MLSMessage(Welcome)` bytes or a pre-decoded ts-mls Welcome, exactly as
8
9
  * `processWelcome` does — the same value reaches both.
9
10
  */
10
- export declare function welcomeKeyPackageRefs(welcome: Uint8Array | unknown): Array<string>;
11
+ export declare function welcomeKeyPackageRefs(welcome: Uint8Array | Welcome): Array<string>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/mls",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "E2EE group identity and membership for Enkaku using MLS",
5
5
  "keywords": [
6
6
  "mls",
@@ -42,8 +42,8 @@
42
42
  "scripts": {
43
43
  "build": "pnpm run build:clean && pnpm run build:js && pnpm run build:types",
44
44
  "build:clean": "del lib",
45
- "build:js": "swc src -d ./lib --config-file ../../node_modules/@kigu/dev/swc.json --strip-leading-paths",
46
- "build:types": "tsc --emitDeclarationOnly --skipLibCheck",
45
+ "build:js": "del 'lib/**/*.js' && swc src -d ./lib --config-file ../../node_modules/@kigu/dev/swc.json --strip-leading-paths",
46
+ "build:types": "del 'lib/**/*.d.ts' 'lib/**/*.d.ts.map' && tsc --emitDeclarationOnly --skipLibCheck",
47
47
  "test": "pnpm run test:types && pnpm run test:unit",
48
48
  "test:types": "tsc --noEmit --skipLibCheck -p tsconfig.test.json",
49
49
  "test:unit": "vitest run"