@kumiai/mls 0.10.4 → 0.10.6

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
@@ -2,6 +2,16 @@
2
2
 
3
3
  Credential-aware MLS (RFC 9420) group lifecycle for enkaku. Wraps [`ts-mls`](https://github.com/LukaJCB/ts-mls) with DID-based identity and a signed control ledger, giving every member a `MemberCredential` that ties their MLS leaf to their DID, and a group-wide roster that decides who may add, remove, and rotate.
4
4
 
5
+ ## Publishing commits directly
6
+
7
+ Commit builders return a derived handle without advancing the source handle's epoch.
8
+ Call `group.reserveHandshakeGeneration(persist)` before each build.
9
+ After the build returns, call `group.consumeHandshakeReservation(persist)` before any journalling or publication.
10
+ Reserve alone reuses an unconsumed generation, including after restart.
11
+ Serialise reserve, build and consume against the source handle. Adopt the derived handle only after acceptance.
12
+ Persistence must complete durably and leave storage unchanged on rejection.
13
+ The `@kumiai/mls-rpc` adapter supplies both reservation hooks to the RPC peer.
14
+
5
15
  ## Capabilities
6
16
 
7
17
  - `createGroup` — creator opens a new group as its sole member and first admin
@@ -41,11 +51,10 @@ may be held while awaiting a handle or peer operation. The real `@kumiai/mls-rpc
41
51
  ## Authority model
42
52
 
43
53
  Authority is a **roster**, folded from a signed **control ledger** and rooted at a genesis anchor installed in the GroupContext when the group is created. There is no capability chain: a member's right to act is decided by the roster every peer computes independently, not by a token the member carries.
44
-
45
54
  - **The ledger is an ordered log of enactments.** Each entry is a token signed by its issuer (a `kumiai.role` entry names a subject DID and grants it `admin` or `member` of the group). The log is replayable and position-dependent: the same claim recurring later is meaningful — a demotion back to a previously-held role is exactly that.
46
- - **The roster is the fold.** `foldRoster` applies each entry only if its issuer was an admin *in the state so far, at that entry's own position*. A token signed by a since-demoted admin is dead paper whoever carries it. The fold starts from the anchor (`{creator: 'admin'}`), so no one can promote themselves by padding an invite.
55
+ - **The roster is the fold.** `foldRoster` applies each entry only if its issuer was an admin _in the state so far, at that entry's own position_. A token signed by a since-demoted admin is dead paper whoever carries it. The fold starts from the anchor (`{creator: 'admin'}`), so no one can promote themselves by padding an invite.
47
56
  - **Enactment is admin-only, structurally.** Entries reach the group inside a commit, and a commit that enacts entries must extend the GroupContext ledger-head extension by exactly those ids, in order. Moving the head needs a `group_context_extensions` proposal, which needs admin. A plain member's only permitted proposal is `update`; attaching an envelope to it fails for want of a head move. The write path runs the receivers' own fold before authoring, so it never builds a commit the group would reject.
48
- - **`GroupPermission` is `'admin' | 'member'` — there is no read-only tier.** It cannot exist: a group member holds the epoch secrets, which is what membership *is* in MLS. A `read` member derives the same application keys as any other member and can decrypt everything. Read-only observers do not belong in the group; gate them outside MLS, at the transport or storage layer.
57
+ - **`GroupPermission` is `'admin' | 'member'` — there is no read-only tier.** It cannot exist: a group member holds the epoch secrets, which is what membership _is_ in MLS. A `read` member derives the same application keys as any other member and can decrypt everything. Read-only observers do not belong in the group; gate them outside MLS, at the transport or storage layer.
49
58
 
50
59
  The invite carries the full ordered ledger plus the invitee's new role entry last, so a joiner folds the same roster the group holds and cannot fork from a role change made before it joined.
51
60
 
@@ -64,9 +73,9 @@ const { groupInfo } = await exportGroupInfo({ group: aliceGroup })
64
73
  // On the stale device:
65
74
  import { joinGroupExternal } from '@kumiai/mls'
66
75
  const { commitMessage, group } = await joinGroupExternal({
67
- identity: bob, // OwnIdentity from @kokuin/token
68
- groupInfo, // bytes received from the healthy member
69
- credential: bobStoredCredential, // cached from the original processWelcome
76
+ identity: bob, // OwnIdentity from @kokuin/token
77
+ groupInfo, // bytes received from the healthy member
78
+ credential: bobStoredCredential, // cached from the original processWelcome
70
79
  resync: true,
71
80
  })
72
81
  // Broadcast commitMessage (Uint8Array) to the other members; each decodes and calls
@@ -93,8 +102,7 @@ An external commit is enforced as a **resync of an existing roster member**, nev
93
102
 
94
103
  ### ⚠️ Security: removal is not revocation
95
104
 
96
- MLS has no cryptographic member revocation. `removeMember` evicts a leaf; it does not erase the removed DID's `kumiai.role` grant — its role in the group — which lives in the roster independently of MLS membership. So a device that retains its `MemberCredential` can rejoin via `joinGroupExternal` **even after being removed** — its DID is still a roster member, so the external-commit policy admits the resync — provided it can still obtain a fresh `GroupInfo`. (The policy stops *strangers*, who are in no roster; it does not stop a removed member.) Consumers must assume a removed member can rejoin until role revocation lands in a follow-up spec. Mitigations available today:
97
-
105
+ MLS has no cryptographic member revocation. `removeMember` evicts a leaf; it does not erase the removed DID's `kumiai.role` grant — its role in the group — which lives in the roster independently of MLS membership. So a device that retains its `MemberCredential` can rejoin via `joinGroupExternal` **even after being removed** — its DID is still a roster member, so the external-commit policy admits the resync — provided it can still obtain a fresh `GroupInfo`. (The policy stops _strangers_, who are in no roster; it does not stop a removed member.) Consumers must assume a removed member can rejoin until role revocation lands in a follow-up spec. Mitigations available today:
98
106
  - Rotate the group: create a new group, migrate non-removed members via fresh invites, abandon the old group.
99
107
  - Enforce access control outside MLS: block the removed device at the transport layer (e.g. hub auth).
100
108
 
@@ -106,6 +114,6 @@ The follow-up revocation work will introduce a ledger entry that removes a DID's
106
114
 
107
115
  ### ⚠️ Security: rotate the last-resort bundle before it expires
108
116
 
109
- A last-resort key package carries an MLS lifetime of `LAST_RESORT_LIFETIME_DAYS` (90). The inviter validates that lifetime when building the Add, so an expired package is refused at the far end with `Current time not within Lifetime` — and refused *no matter what the hub does*, because the hub stores opaque bytes and cannot see the expiry.
117
+ A last-resort key package carries an MLS lifetime of `LAST_RESORT_LIFETIME_DAYS` (90). The inviter validates that lifetime when building the Add, so an expired package is refused at the far end with `Current time not within Lifetime` — and refused _no matter what the hub does_, because the hub stores opaque bytes and cannot see the expiry.
110
118
 
111
119
  That makes the failure worse than an empty slot: the hub goes on reporting the slot as full and serving the dead package, so the availability floor looks healthy while every join through it fails. A host must generate and upload a fresh last-resort bundle before the window elapses, and keep the new private half. Uploading once at enrolment buys 90 days, not forever.
package/lib/codec.d.ts CHANGED
@@ -1,5 +1,12 @@
1
- import { type ClientState, type RatchetTree } from 'ts-mls';
2
- export type { ClientState };
1
+ import { type ClientState as MLSClientState, type RatchetTree } from 'ts-mls';
2
+ /** Local reservation evidence travels with every durable MLS checkpoint. */
3
+ export type ClientState = MLSClientState & {
4
+ handshakeReservation?: {
5
+ epoch: bigint;
6
+ generation: number;
7
+ consumed: boolean;
8
+ };
9
+ };
3
10
  export declare function decodeClientState(encoded: Uint8Array): ClientState | undefined;
4
11
  export declare function encodeClientState(state: ClientState): Uint8Array;
5
12
  export declare function sanitizeRatchetTree(tree: ReadonlyArray<unknown>): RatchetTree;
package/lib/codec.js CHANGED
@@ -1,17 +1,11 @@
1
1
  import { clientStateDecoder, clientStateEncoder, decode, encode } from 'ts-mls';
2
- /**
3
- * The client-state blob's format version, first byte.
4
- *
5
- * This code is the only reader this blob ever has: `encodeClientState` and `decodeClientState`
6
- * are one process serializing its own state to itself (to disk, to storage, wherever), never a
7
- * wire format another peer or another build reads. So there is no peer to stay compatible with —
8
- * an unknown version is refused outright, not migrated.
9
- *
10
- * It buys diagnosis, not compatibility. There is no version of this a v1 build can read, and a
11
- * format change is a flag day whatever this byte says. What it changes is that the failure reads
12
- * as "this blob is v2 and I speak v1" rather than an opaque decode failure indistinguishable from
13
- * truncated bytes or a corrupted store.
2
+ /** v1 stores bare ts-mls state. v3 prefixes epoch (uint64), generation (uint32),
3
+ * and consumed (uint8) before that state. v1 has no evidence permitting reuse.
4
+ * v2 belongs to an incompatible layout and is refused, as are unknown versions.
5
+ * Older readers refuse v3.
14
6
  */ const CLIENT_STATE_VERSION = 1;
7
+ const RESERVATION_STATE_VERSION = 3;
8
+ const RESERVATION_BYTES = 13;
15
9
  export function decodeClientState(encoded) {
16
10
  // Too short to hold the version byte is a TRUNCATED read, not a version this build does not
17
11
  // speak, and the two are separate diagnoses — the same split `@kumiai/mls-rpc`'s `openEntries`
@@ -26,17 +20,37 @@ export function decodeClientState(encoded) {
26
20
  // byte is not that kind of failure, so it throws instead of returning the same `undefined`
27
21
  // a decode failure would. Without this, a version mismatch and a corrupted store are the
28
22
  // same value of the same type and a caller cannot tell them apart.
29
- if (encoded[0] !== CLIENT_STATE_VERSION) {
23
+ if (encoded[0] !== CLIENT_STATE_VERSION && encoded[0] !== RESERVATION_STATE_VERSION) {
30
24
  throw new Error(`decodeClientState: unsupported client-state version ${encoded[0]}`);
31
25
  }
32
26
  // A copy: ts-mls decodes secrets as views, and ratcheting zeroes consumed ones in place.
33
- return decode(clientStateDecoder, encoded.slice(1));
27
+ if (encoded[0] === CLIENT_STATE_VERSION) return decode(clientStateDecoder, encoded.slice(1));
28
+ if (encoded.length < 1 + RESERVATION_BYTES || encoded[13] !== 0 && encoded[13] !== 1) return undefined;
29
+ const view = new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength);
30
+ const state = decode(clientStateDecoder, encoded.slice(1 + RESERVATION_BYTES));
31
+ if (state == null) return undefined;
32
+ return {
33
+ ...state,
34
+ handshakeReservation: {
35
+ epoch: view.getBigUint64(1),
36
+ generation: view.getUint32(9),
37
+ consumed: encoded[13] === 1
38
+ }
39
+ };
34
40
  }
35
41
  export function encodeClientState(state) {
36
42
  const body = encode(clientStateEncoder, state);
37
- const out = new Uint8Array(1 + body.length);
38
- out[0] = CLIENT_STATE_VERSION;
39
- out.set(body, 1);
43
+ const reservation = state.handshakeReservation;
44
+ const header = reservation == null ? 1 : 1 + RESERVATION_BYTES;
45
+ const out = new Uint8Array(header + body.length);
46
+ out[0] = reservation == null ? CLIENT_STATE_VERSION : RESERVATION_STATE_VERSION;
47
+ if (reservation != null) {
48
+ const view = new DataView(out.buffer);
49
+ view.setBigUint64(1, reservation.epoch);
50
+ view.setUint32(9, reservation.generation);
51
+ out[13] = reservation.consumed ? 1 : 0;
52
+ }
53
+ out.set(body, header);
40
54
  return out;
41
55
  }
42
56
  export function sanitizeRatchetTree(tree) {
package/lib/errors.d.ts CHANGED
@@ -16,3 +16,13 @@ export declare class RevokeProofError extends Error {
16
16
  constructor(reason: RevokeProofReason);
17
17
  get reason(): RevokeProofReason;
18
18
  }
19
+ /** The sender must wait for an epoch advance before building another private commit. */
20
+ export declare class HandshakeWindowError extends Error {
21
+ constructor();
22
+ }
23
+ export declare class HandshakeWindowConfigError extends Error {
24
+ constructor();
25
+ }
26
+ export declare class HandshakeReservationError extends Error {
27
+ constructor();
28
+ }
package/lib/errors.js CHANGED
@@ -31,3 +31,21 @@ export class RevokeProofError extends Error {
31
31
  return this.#reason;
32
32
  }
33
33
  }
34
+ /** The sender must wait for an epoch advance before building another private commit. */ export class HandshakeWindowError extends Error {
35
+ constructor(){
36
+ super('Handshake sender generation reached the safe receiver window for this epoch');
37
+ this.name = 'HandshakeWindowError';
38
+ }
39
+ }
40
+ export class HandshakeWindowConfigError extends Error {
41
+ constructor(){
42
+ super('Handshake receiver window must be at least 2');
43
+ this.name = 'HandshakeWindowConfigError';
44
+ }
45
+ }
46
+ export class HandshakeReservationError extends Error {
47
+ constructor(){
48
+ super('No matching handshake reservation for the current epoch and generation');
49
+ this.name = 'HandshakeReservationError';
50
+ }
51
+ }
@@ -84,10 +84,13 @@ export type CommitLedgerEntriesResult = {
84
84
  * empty `tokens` list.
85
85
  *
86
86
  * Reads `group` and returns a NEW derived handle (`newGroup`); it never advances
87
- * `group`. The caller MUST adopt `newGroup` — never reuse `group` — before the next
88
- * commit: two commits from the same source handle both frame at its epoch and diverge.
89
- * The mutex only serializes concurrent calls against one handle; it does not make a
90
- * second commit from a superseded handle safe.
87
+ * `group`'s epoch. Adopt `newGroup` only after publication is accepted.
88
+ * Before each build, call `group.reserveHandshakeGeneration(persist)`.
89
+ * After the build returns, call `group.consumeHandshakeReservation(persist)` before
90
+ * any journalling or publication. Reserve alone reuses an unconsumed generation.
91
+ * Serialise reserve, build and consume against the source handle.
92
+ * The mutex only serializes concurrent calls against one handle. A source whose commit
93
+ * was accepted is superseded and must never be reused.
91
94
  */
92
95
  export declare function commitLedgerEntries(group: GroupHandle, tokens: Array<string>): Promise<CommitLedgerEntriesResult>;
93
96
  export type CommitInviteResult = {
@@ -270,10 +270,13 @@ import { ROLE_ENTRY_TYPE } from './roster.js';
270
270
  * empty `tokens` list.
271
271
  *
272
272
  * Reads `group` and returns a NEW derived handle (`newGroup`); it never advances
273
- * `group`. The caller MUST adopt `newGroup` — never reuse `group` — before the next
274
- * commit: two commits from the same source handle both frame at its epoch and diverge.
275
- * The mutex only serializes concurrent calls against one handle; it does not make a
276
- * second commit from a superseded handle safe.
273
+ * `group`'s epoch. Adopt `newGroup` only after publication is accepted.
274
+ * Before each build, call `group.reserveHandshakeGeneration(persist)`.
275
+ * After the build returns, call `group.consumeHandshakeReservation(persist)` before
276
+ * any journalling or publication. Reserve alone reuses an unconsumed generation.
277
+ * Serialise reserve, build and consume against the source handle.
278
+ * The mutex only serializes concurrent calls against one handle. A source whose commit
279
+ * was accepted is superseded and must never be reused.
277
280
  */ export async function commitLedgerEntries(group, tokens) {
278
281
  return mutexFor(group).run(async ()=>{
279
282
  if (tokens.length === 0) {
@@ -1,6 +1,7 @@
1
1
  import { EventEmitter, type EventsSource } from '@sozai/event';
2
- import { type ClientState, type IncomingMessageCallback, type MlsContext, type MlsFramedMessage, type ProposalWithSender } from 'ts-mls';
2
+ import { type IncomingMessageCallback, type MlsContext, type MlsFramedMessage, type ProposalWithSender } from 'ts-mls';
3
3
  import { type GroupAnchor } from './anchor.js';
4
+ import { type ClientState } from './codec.js';
4
5
  import { type GroupMember, type MemberCredential } from './credential.js';
5
6
  import { type LeafBinding } from './device-proof.js';
6
7
  import { type VerifiedLedgerEntry } from './ledger.js';
@@ -104,9 +105,8 @@ export declare class GroupHandle {
104
105
  get ledger(): ReadonlyArray<LedgerLogEntry>;
105
106
  /** The ordered signed tokens this handle holds, repeats included — the ledger's
106
107
  * canonical persistent/wire form, and the list the authenticated head folds over.
107
- * Feeds createInvite, restoreGroup, and host persistence. The verified entries are
108
- * a derived cache with no export form: the only way in is applyLedgerEntries,
109
- * which re-verifies. */
108
+ * Feeds createInvite, restoreGroup, and host persistence. In-process clones inherit
109
+ * verification through the returned array; serialised tokens must verify afresh. */
110
110
  get ledgerTokens(): Array<string>;
111
111
  /** The control roster folded from the anchor and every applied ledger entry. */
112
112
  get roster(): RosterState;
@@ -142,8 +142,8 @@ export declare class GroupHandle {
142
142
  * Verify signed ledger tokens, append the valid ones in the order given, and
143
143
  * refold the roster. Tokens that fail verification or whose groupID mismatches are
144
144
  * dropped (defensive — the strict admin-issuer enforcement is the commit pre-pass).
145
- * Every token is re-verified on the way in: no entry enters a ledger unverified,
146
- * whatever the import path.
145
+ * Exact token bytes can reuse verification on the same array or a handle's export.
146
+ * did:key and embedded peer:4 keys are immutable; time claims still check on reuse.
147
147
  *
148
148
  * A token the log already holds is appended again, not skipped: the log records
149
149
  * what each commit enacted, not a set of claims, and a repeat is the only way to
@@ -279,6 +279,43 @@ export declare class GroupHandle {
279
279
  encrypt(plaintext: Uint8Array, opts?: {
280
280
  aad?: Uint8Array;
281
281
  }): Promise<Uint8Array>;
282
+ /**
283
+ * Move this member's own application ratchet forward so the next {@link encrypt} uses
284
+ * generation `target` — the generation read from
285
+ * `state.secretTree.leafNodes[2 * leafIndex].application.generation` (0 before the leaf
286
+ * secret is derived). The resulting state is the one `target - current` empty encrypts
287
+ * would leave, with no frame produced: the retired chain secrets are zeroed, and the
288
+ * epoch and every other member's ratchet are untouched. A target at or below the current
289
+ * generation is a no-op; the ratchet never moves back.
290
+ *
291
+ * For a host that restores a persisted state and must not reuse a generation it may have
292
+ * sent from before a crash. Each skipped generation costs one KDF step, not an encrypt.
293
+ * Receivers must still cross the gap: ts-mls refuses a jump beyond its forward-ratchet
294
+ * window (`maximumForwardRatchetSteps`, 200 by default).
295
+ *
296
+ * No cap by default: a host catching up a stored high-water mark may legitimately step
297
+ * far past any receiver's position (a receiver's window counts from the last generation
298
+ * it processed, not from this state). With `opts.maxSteps`, an advance whose
299
+ * `target - current` exceeds it throws a `RangeError` before any step.
300
+ *
301
+ * Refuses exactly as {@link encrypt} would: a lapsed leaf, unapplied proposals, a
302
+ * removed or suspended member. `target` must be below 0xffffffff, the last generation.
303
+ * On any throw the handle state is unchanged and the secrets derived so far are zeroed.
304
+ */
305
+ advanceSenderGeneration(target: number, opts?: {
306
+ maxSteps?: number;
307
+ }): Promise<void>;
308
+ /**
309
+ * Reserve a handshake generation before building a commit from this handle.
310
+ * Reuse only a persisted, unconsumed reservation at the current epoch and generation.
311
+ * The epoch, application ratchet, ledger and pending proposals remain unchanged.
312
+ * `persist` runs under the handle mutex and must not re-enter this handle.
313
+ * A failed persist restores the source and wipes newly derived secrets.
314
+ * Consume the reservation durably before journalling any returned commit for publication.
315
+ */
316
+ reserveHandshakeGeneration(persist: (handle: GroupHandle) => Promise<void> | void): Promise<void>;
317
+ /** Persist consumption before any commit journal can permit publication. */
318
+ consumeHandshakeReservation(persist: (handle: GroupHandle) => Promise<void> | void): Promise<void>;
282
319
  /**
283
320
  * Open an application message sealed for the group and recover WHO SENT IT — the
284
321
  * counterpart to {@link encrypt}, and the read half of the group's application lane.
@@ -1,6 +1,6 @@
1
- import { normalizeDID } from '@kokuin/token';
1
+ import { assertTimeClaimsValid, decodeSignedToken, normalizeDID } from '@kokuin/token';
2
2
  import { EventEmitter } from '@sozai/event';
3
- import { contentTypes, createApplicationMessage, createProposal, decode, defaultCredentialTypes, defaultProposalTypes, encode, isDefaultCredential, mlsExporter, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, wireformats } from 'ts-mls';
3
+ import { contentTypes, createApplicationMessage, createProposal, decode, defaultCredentialTypes, defaultKeyRetentionConfig, defaultProposalTypes, encode, isDefaultCredential, mlsExporter, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, UsageError, wireformats } from 'ts-mls';
4
4
  import { readGroupAnchor } from './anchor.js';
5
5
  import { verifyLeafCredential } from './authentication.js';
6
6
  import { encodeClientState } from './codec.js';
@@ -8,7 +8,7 @@ import { didFromCredential, parseMLSCredentialIdentity } from './credential.js';
8
8
  import { verifyDeviceEntry } from './device-proof.js';
9
9
  import { decodeControlEnvelope } from './envelope.js';
10
10
  import { foldEnvelope, GROUP_TYPE_PREFIX } from './envelope-fold.js';
11
- import { LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
11
+ import { HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
12
12
  import { createMlsContext, deviceDenyHolderFor } from './group-context.js';
13
13
  import { readMessageEpoch } from './group-info.js';
14
14
  import { assertHeadMatches, computeHead, decodeLedgerHead, encodeLedgerHead, extendHead, headsMatch, readLedgerHead, readLedgerHeadExtension } from './head.js';
@@ -17,10 +17,12 @@ import { assertSenderNotLapsed, isLapsed, isUnchangedLeaf, leafAt, prepareLifecy
17
17
  import { createMutex } from './mutex.js';
18
18
  import { defaultCommitPolicy, MissingLedgerEntriesError } from './policy.js';
19
19
  import { beaconOf, controllerOf, DEVICE_ENTRY_TYPE, denySetOf, foldControl, isDeviceValue, mayReadmitResetDevice, revocationOf } from './registry.js';
20
+ import { advanceSendingRatchet } from './secret-tree.js';
20
21
  import { readSenderLeafIndex } from './sender-data.js';
21
22
  /** One serializer per live handle, so its state-mutating operations run one at a
22
23
  * time in issue order. Keyed weakly: the entry is collected with the handle, and
23
24
  * the handle carries no reference back to it. */ const MUTEXES = new WeakMap();
25
+ /** Leave half the configured receiver window unused. */ const HANDSHAKE_WINDOW_DIVISOR = 2;
24
26
  export function mutexFor(handle) {
25
27
  let mutex = MUTEXES.get(handle);
26
28
  if (mutex === undefined) {
@@ -41,6 +43,36 @@ export function mutexFor(handle) {
41
43
  * material does not linger in the heap after the state that used it is replaced. */ function zeroAll(buffers) {
42
44
  for (const buffer of buffers)buffer.fill(0);
43
45
  }
46
+ /** Zero the secrets `next` holds that `prior` does not: what a discarded derivation produced. */ function zeroFreshSecrets(prior, next, consumed = []) {
47
+ const held = new Set();
48
+ for (const secret of Object.values(prior.intermediateNodes))held.add(secret);
49
+ for (const leaf of Object.values(prior.leafNodes)){
50
+ held.add(leaf.application.secret);
51
+ held.add(leaf.handshake.secret);
52
+ for (const secret of Object.values(leaf.application.unusedGenerations))held.add(secret);
53
+ for (const secret of Object.values(leaf.handshake.unusedGenerations))held.add(secret);
54
+ }
55
+ const fresh = [
56
+ ...Object.values(next.intermediateNodes),
57
+ ...consumed
58
+ ];
59
+ for (const leaf of Object.values(next.leafNodes)){
60
+ fresh.push(leaf.application.secret, leaf.handshake.secret);
61
+ }
62
+ for (const secret of fresh)if (!held.has(secret)) secret.fill(0);
63
+ }
64
+ /** ts-mls's guard ahead of every application send, which its index does not export.
65
+ * Same checks, same errors, so a ratchet-only advance refuses exactly as encrypt does. */ function checkCanSendApplicationMessages(state) {
66
+ if (Object.keys(state.unappliedProposals).length !== 0) {
67
+ throw new UsageError('Cannot send application message with unapplied proposals');
68
+ }
69
+ if (state.groupActiveState.kind === 'suspendedPendingReinit') {
70
+ throw new UsageError('Cannot send messages while Group is suspended pending reinit');
71
+ }
72
+ if (state.groupActiveState.kind === 'removedFromGroup') {
73
+ throw new UsageError('Cannot send messages after being removed from group');
74
+ }
75
+ }
44
76
  /** AAD is not secret, so a length/byte compare is enough — no constant-time need. */ function bytesEqual(a, b) {
45
77
  if (a.length !== b.length) return false;
46
78
  for(let i = 0; i < a.length; i++)if (a[i] !== b[i]) return false;
@@ -171,6 +203,21 @@ export function mutexFor(handle) {
171
203
  };
172
204
  }
173
205
  }
206
+ const VERIFIED_LEDGER_ENTRIES = new WeakMap();
207
+ const VERIFIED_LEDGER_TOKENS = new WeakMap();
208
+ // Record provenance before exposing claims; re-enactments keep the original snapshot.
209
+ function ledgerLogEntry(entryID, token, verified) {
210
+ const held = {
211
+ entryID,
212
+ token,
213
+ verified
214
+ };
215
+ VERIFIED_LEDGER_ENTRIES.set(verified, {
216
+ token,
217
+ verified: structuredClone(verified)
218
+ });
219
+ return held;
220
+ }
174
221
  /** Project lifecycle tree re-admissions from the full ledger fold, never a previous projection.
175
222
  * A lapsed re-admitted leaf and a leaf inserted after expiry are indistinguishable here;
176
223
  * a genuine expired post-reset package can activate a leaf for a Welcome joiner or an
@@ -329,10 +376,11 @@ export function mutexFor(handle) {
329
376
  }
330
377
  /** The ordered signed tokens this handle holds, repeats included — the ledger's
331
378
  * canonical persistent/wire form, and the list the authenticated head folds over.
332
- * Feeds createInvite, restoreGroup, and host persistence. The verified entries are
333
- * a derived cache with no export form: the only way in is applyLedgerEntries,
334
- * which re-verifies. */ get ledgerTokens() {
335
- return this.#ledger.map(({ token })=>token);
379
+ * Feeds createInvite, restoreGroup, and host persistence. In-process clones inherit
380
+ * verification through the returned array; serialised tokens must verify afresh. */ get ledgerTokens() {
381
+ const tokens = this.#ledger.map(({ token })=>token);
382
+ VERIFIED_LEDGER_TOKENS.set(tokens, this.#ledger.map(({ verified })=>VERIFIED_LEDGER_ENTRIES.get(verified)));
383
+ return tokens;
336
384
  }
337
385
  /** The control roster folded from the anchor and every applied ledger entry. */ get roster() {
338
386
  return this.#roster;
@@ -430,8 +478,8 @@ export function mutexFor(handle) {
430
478
  * Verify signed ledger tokens, append the valid ones in the order given, and
431
479
  * refold the roster. Tokens that fail verification or whose groupID mismatches are
432
480
  * dropped (defensive — the strict admin-issuer enforcement is the commit pre-pass).
433
- * Every token is re-verified on the way in: no entry enters a ledger unverified,
434
- * whatever the import path.
481
+ * Exact token bytes can reuse verification on the same array or a handle's export.
482
+ * did:key and embedded peer:4 keys are immutable; time claims still check on reuse.
435
483
  *
436
484
  * A token the log already holds is appended again, not skipped: the log records
437
485
  * what each commit enacted, not a set of claims, and a repeat is the only way to
@@ -441,21 +489,33 @@ export function mutexFor(handle) {
441
489
  */ async applyLedgerEntries(tokens) {
442
490
  return mutexFor(this).run(async ()=>{
443
491
  const appended = [];
444
- for (const token of tokens){
445
- const verified = await verifyLedgerEntry(token);
492
+ const memo = VERIFIED_LEDGER_TOKENS.get(tokens);
493
+ const nextMemo = [];
494
+ for (const [index, token] of tokens.entries()){
495
+ const held = memo?.[index];
496
+ let verified;
497
+ if (held?.token === token) {
498
+ try {
499
+ assertTimeClaimsValid(decodeSignedToken(token).payload);
500
+ } catch {
501
+ continue;
502
+ }
503
+ verified = structuredClone(held.verified);
504
+ } else {
505
+ verified = await verifyLedgerEntry(token);
506
+ }
446
507
  if (verified == null || verified.entry.groupID !== this.groupID) continue;
447
508
  const entryID = ledgerEntryDigest(token);
448
- this.#ledger.push({
449
- entryID,
450
- token,
451
- verified
452
- });
509
+ const entry = ledgerLogEntry(entryID, token, verified);
510
+ this.#ledger.push(entry);
511
+ nextMemo[index] = VERIFIED_LEDGER_ENTRIES.get(verified);
453
512
  this.#entryBodies.set(entryID, {
454
513
  token,
455
514
  verified
456
515
  });
457
516
  appended.push(verified);
458
517
  }
518
+ VERIFIED_LEDGER_TOKENS.set(tokens, nextMemo);
459
519
  const folded = foldLedgerControl(this.#ledger, this.#anchor, this.groupID);
460
520
  this.#roster = folded.roster;
461
521
  this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor);
@@ -540,11 +600,7 @@ export function mutexFor(handle) {
540
600
  // covers. Fails closed anyway.
541
601
  throw new Error('bootstrapLedger: the gathered ledger holds an unverifiable or cross-group entry');
542
602
  }
543
- log.push({
544
- entryID: entryIDs[index],
545
- token,
546
- verified
547
- });
603
+ log.push(ledgerLogEntry(entryIDs[index], token, verified));
548
604
  }
549
605
  // What this bootstrap ADDS, in log order, minus the reserved `kumiai.*` types the fold
550
606
  // consumes itself — the same rule the commit path surfaces by.
@@ -772,6 +828,194 @@ export function mutexFor(handle) {
772
828
  });
773
829
  }
774
830
  /**
831
+ * Move this member's own application ratchet forward so the next {@link encrypt} uses
832
+ * generation `target` — the generation read from
833
+ * `state.secretTree.leafNodes[2 * leafIndex].application.generation` (0 before the leaf
834
+ * secret is derived). The resulting state is the one `target - current` empty encrypts
835
+ * would leave, with no frame produced: the retired chain secrets are zeroed, and the
836
+ * epoch and every other member's ratchet are untouched. A target at or below the current
837
+ * generation is a no-op; the ratchet never moves back.
838
+ *
839
+ * For a host that restores a persisted state and must not reuse a generation it may have
840
+ * sent from before a crash. Each skipped generation costs one KDF step, not an encrypt.
841
+ * Receivers must still cross the gap: ts-mls refuses a jump beyond its forward-ratchet
842
+ * window (`maximumForwardRatchetSteps`, 200 by default).
843
+ *
844
+ * No cap by default: a host catching up a stored high-water mark may legitimately step
845
+ * far past any receiver's position (a receiver's window counts from the last generation
846
+ * it processed, not from this state). With `opts.maxSteps`, an advance whose
847
+ * `target - current` exceeds it throws a `RangeError` before any step.
848
+ *
849
+ * Refuses exactly as {@link encrypt} would: a lapsed leaf, unapplied proposals, a
850
+ * removed or suspended member. `target` must be below 0xffffffff, the last generation.
851
+ * On any throw the handle state is unchanged and the secrets derived so far are zeroed.
852
+ */ async advanceSenderGeneration(target, opts) {
853
+ // 0xffffffff is the last uint32 generation: no frame could follow it.
854
+ if (!Number.isInteger(target) || target < 0 || target >= 0xffffffff) {
855
+ throw new RangeError(`advanceSenderGeneration: ${target} is not a sendable uint32 generation`);
856
+ }
857
+ const maxSteps = opts?.maxSteps;
858
+ if (maxSteps != null && (!Number.isInteger(maxSteps) || maxSteps < 0)) {
859
+ throw new RangeError(`advanceSenderGeneration: maxSteps ${maxSteps} is not a step count`);
860
+ }
861
+ return mutexFor(this).run(async ()=>{
862
+ const own = leafAt(this.#state.ratchetTree, this.#state.privatePath.leafIndex);
863
+ if (own != null && isLapsed(this, own)) throw new LeafLapsedError('lapsed');
864
+ checkCanSendApplicationMessages(this.#state);
865
+ const node = Number(this.#state.privatePath.leafIndex) * 2;
866
+ const current = this.#state.secretTree.leafNodes[node]?.application.generation ?? 0;
867
+ if (target <= current) return;
868
+ if (maxSteps != null && target - current > maxSteps) {
869
+ throw new RangeError(`advanceSenderGeneration: ${target - current} steps exceed maxSteps ${maxSteps}`);
870
+ }
871
+ const prior = this.#state;
872
+ let base = prior;
873
+ let retired = [];
874
+ if (prior.secretTree.leafNodes[node] == null) {
875
+ // The leaf secret is still folded into an ancestor. Deriving it walks the tree
876
+ // (and seeds the handshake ratchet), so let ts-mls do it the one way it does:
877
+ // one empty encrypt, whose frame is discarded unsent. It consumes generation 0.
878
+ // Its retired secrets are still referenced by `prior`, so they are zeroed only
879
+ // once the advanced state is adopted.
880
+ const { newState, consumed } = await createApplicationMessage({
881
+ context: this.#context,
882
+ state: prior,
883
+ message: new Uint8Array(),
884
+ authenticatedData: new Uint8Array()
885
+ });
886
+ base = newState;
887
+ retired = consumed;
888
+ }
889
+ const secretTree = base.secretTree;
890
+ const leaf = secretTree.leafNodes[node];
891
+ if (leaf == null) throw new Error('unreachable: an encrypt derives the sender leaf');
892
+ let advanced;
893
+ try {
894
+ advanced = await advanceSendingRatchet(this.#context, leaf.application, target);
895
+ } catch (error) {
896
+ if (base !== prior) zeroFreshSecrets(prior.secretTree, secretTree);
897
+ throw error;
898
+ }
899
+ this.#state = {
900
+ ...base,
901
+ secretTree: {
902
+ ...secretTree,
903
+ leafNodes: {
904
+ ...secretTree.leafNodes,
905
+ [node]: {
906
+ ...leaf,
907
+ application: advanced.ratchet
908
+ }
909
+ }
910
+ }
911
+ };
912
+ zeroAll(retired);
913
+ zeroAll(advanced.consumed);
914
+ });
915
+ }
916
+ /**
917
+ * Reserve a handshake generation before building a commit from this handle.
918
+ * Reuse only a persisted, unconsumed reservation at the current epoch and generation.
919
+ * The epoch, application ratchet, ledger and pending proposals remain unchanged.
920
+ * `persist` runs under the handle mutex and must not re-enter this handle.
921
+ * A failed persist restores the source and wipes newly derived secrets.
922
+ * Consume the reservation durably before journalling any returned commit for publication.
923
+ */ async reserveHandshakeGeneration(persist) {
924
+ return mutexFor(this).run(async ()=>{
925
+ const prior = this.#state;
926
+ if (prior.groupActiveState.kind === 'suspendedPendingReinit') {
927
+ throw new UsageError('Cannot send messages while Group is suspended pending reinit');
928
+ }
929
+ if (prior.groupActiveState.kind === 'removedFromGroup') {
930
+ throw new UsageError('Cannot send messages after being removed from group');
931
+ }
932
+ const node = Number(prior.privatePath.leafIndex) * 2;
933
+ const leaf = prior.secretTree.leafNodes[node];
934
+ const current = leaf?.handshake.generation ?? 0;
935
+ const reservation = prior.handshakeReservation;
936
+ if (reservation?.epoch === this.epoch && reservation.generation === current && !reservation.consumed) {
937
+ await persist(this);
938
+ return;
939
+ }
940
+ // Every accepted MLS handshake commit moves the epoch. Epoch start is therefore a
941
+ // conservative baseline, even when a receiver refused or missed earlier frames.
942
+ // rc.13: MlsContext.clientConfig.keyRetentionConfig.maximumForwardRatchetSteps
943
+ // defaults to defaultKeyRetentionConfig.maximumForwardRatchetSteps (200).
944
+ const window = this.#context.clientConfig?.keyRetentionConfig?.maximumForwardRatchetSteps ?? defaultKeyRetentionConfig.maximumForwardRatchetSteps;
945
+ const limit = Math.floor(Math.min(window, defaultKeyRetentionConfig.maximumForwardRatchetSteps) / HANDSHAKE_WINDOW_DIVISOR);
946
+ if (limit < 1) throw new HandshakeWindowConfigError();
947
+ if (current + 1 > limit) throw new HandshakeWindowError();
948
+ if (current >= 0xfffffffe) throw new RangeError('handshake sender generation exhausted');
949
+ let tree;
950
+ let consumed;
951
+ if (leaf == null) {
952
+ // ts-mls does not export leaf derivation. Discard an unsent proposal and retain
953
+ // only its advanced tree, without adding the proposal to the source state.
954
+ const result = await createProposal({
955
+ context: this.#context,
956
+ state: prior,
957
+ proposal: {
958
+ proposalType: defaultProposalTypes.remove,
959
+ remove: {
960
+ removed: prior.privatePath.leafIndex
961
+ }
962
+ }
963
+ });
964
+ tree = result.newState.secretTree;
965
+ consumed = result.consumed;
966
+ } else {
967
+ const advanced = await advanceSendingRatchet(this.#context, leaf.handshake, current + 1);
968
+ tree = {
969
+ ...prior.secretTree,
970
+ leafNodes: {
971
+ ...prior.secretTree.leafNodes,
972
+ [node]: {
973
+ ...leaf,
974
+ handshake: advanced.ratchet
975
+ }
976
+ }
977
+ };
978
+ consumed = advanced.consumed;
979
+ }
980
+ this.#state = {
981
+ ...prior,
982
+ secretTree: tree,
983
+ handshakeReservation: {
984
+ epoch: this.epoch,
985
+ generation: current + 1,
986
+ consumed: false
987
+ }
988
+ };
989
+ try {
990
+ await persist(this);
991
+ } catch (error) {
992
+ this.#state = prior;
993
+ zeroFreshSecrets(prior.secretTree, tree, consumed);
994
+ throw error;
995
+ }
996
+ zeroAll(consumed);
997
+ });
998
+ }
999
+ /** Persist consumption before any commit journal can permit publication. */ async consumeHandshakeReservation(persist) {
1000
+ return mutexFor(this).run(async ()=>{
1001
+ const prior = this.#state;
1002
+ const reservation = prior.handshakeReservation;
1003
+ const current = prior.secretTree.leafNodes[Number(prior.privatePath.leafIndex) * 2]?.handshake.generation;
1004
+ if (reservation == null || reservation.epoch !== this.epoch || reservation.generation !== current) {
1005
+ throw new HandshakeReservationError();
1006
+ }
1007
+ this.#state = {
1008
+ ...prior,
1009
+ handshakeReservation: {
1010
+ ...reservation,
1011
+ consumed: true
1012
+ }
1013
+ };
1014
+ // Keep consumed evidence in memory on failure. No journal write can follow rejection.
1015
+ await persist(this);
1016
+ });
1017
+ }
1018
+ /**
775
1019
  * Open an application message sealed for the group and recover WHO SENT IT — the
776
1020
  * counterpart to {@link encrypt}, and the read half of the group's application lane.
777
1021
  *
@@ -948,11 +1192,7 @@ export function mutexFor(handle) {
948
1192
  if (resolved.has(id) || !missing.includes(id)) continue;
949
1193
  const verified = await verifyLedgerEntry(token);
950
1194
  if (verified == null) continue;
951
- resolved.set(id, {
952
- token,
953
- verified,
954
- entryID: id
955
- });
1195
+ resolved.set(id, ledgerLogEntry(id, token, verified));
956
1196
  }
957
1197
  const stillMissing = missing.filter((id)=>!resolved.has(id));
958
1198
  if (stillMissing.length > 0) {
package/lib/index.d.ts CHANGED
@@ -10,7 +10,7 @@ export { createNobleCryptoProvider, type NobleCryptoProviderOptions, nobleCrypto
10
10
  export type { LeafBinding } from './device-proof.js';
11
11
  export { CONTROL_ENVELOPE_VERSION, type ControlEnvelope, type DecodeResult, decodeControlEnvelope, encodeControlEnvelope, } from './envelope.js';
12
12
  export { type EnvelopeFoldResult, type FoldEnvelopeContext, type FoldEnvelopeParams, foldEnvelope, } from './envelope-fold.js';
13
- export { LeafBindingError, type LeafBindingReason, LeafLapsedError, type LeafLapsedReason, RevokeProofError, type RevokeProofReason, } from './errors.js';
13
+ export { HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, type LeafBindingReason, LeafLapsedError, type LeafLapsedReason, RevokeProofError, type RevokeProofReason, } from './errors.js';
14
14
  export { type FoldDrop, type FoldInput, foldLedger, type LedgerReducer, } from './fold.js';
15
15
  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, type SendAdmission, } from './group.js';
16
16
  export { type CommitResult, commitSelfRemovals, proposeSelfRemoval, type RemoveLapsedLeavesResult, type RevokeBuildResult, type RevokeWithProofParams, removeLapsedLeaves, renewLeaf, revokeWithProof, } from './group-lifecycle.js';
package/lib/index.js CHANGED
@@ -7,7 +7,7 @@ export { didFromCredential, parseMLSCredentialIdentity } from './credential.js';
7
7
  export { createNobleCryptoProvider, nobleCryptoProvider } from './crypto.js';
8
8
  export { CONTROL_ENVELOPE_VERSION, decodeControlEnvelope, encodeControlEnvelope } from './envelope.js';
9
9
  export { foldEnvelope } from './envelope-fold.js';
10
- export { LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
10
+ export { HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
11
11
  export { foldLedger } from './fold.js';
12
12
  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';
13
13
  export { commitSelfRemovals, proposeSelfRemoval, removeLapsedLeaves, renewLeaf, revokeWithProof } from './group-lifecycle.js';
@@ -1,3 +1,15 @@
1
- import type { SecretTree } from 'ts-mls';
1
+ import type { GenerationSecret, MlsContext, SecretTree } from 'ts-mls';
2
2
  /** Merge same-epoch trees without mutating inputs. The result takes `leafWidth` from `target`. */
3
3
  export declare function mergeReceiveSecretTree(target: SecretTree, source: SecretTree): SecretTree;
4
+ /**
5
+ * Step a member's OWN sending ratchet forward to `target`, the generation its next frame
6
+ * uses, without encrypting anything. Each step is the one ts-mls's `consumeRatchet` takes
7
+ * per sent frame: the secret advances, the generation increments, and `unusedGenerations`
8
+ * is untouched (a sender keeps no skipped keys for itself). Non-mutating; the returned
9
+ * `consumed` are the retired chain secrets, for the caller to zero once it adopts the result.
10
+ * On a throw, the secrets derived so far are zeroed and the input ratchet is left intact.
11
+ */
12
+ export declare function advanceSendingRatchet(context: MlsContext, ratchet: GenerationSecret, target: number): Promise<{
13
+ ratchet: GenerationSecret;
14
+ consumed: Array<Uint8Array>;
15
+ }>;
@@ -1,3 +1,4 @@
1
+ import { expandWithLabel } from './sender-data.js';
1
2
  /** Combine two same-epoch ratchets, retaining a skipped key only if neither side spent it. */ function mergeGenerationSecrets(a, b) {
2
3
  const [ahead, behind] = a.generation >= b.generation ? [
3
4
  a,
@@ -58,3 +59,44 @@
58
59
  leafNodes
59
60
  };
60
61
  }
62
+ /** RFC 9420 `DeriveTreeSecret(secret, "secret", generation, KDF.Nh)`: one sender-ratchet step. */ function nextRatchetSecret(context, secret, generation) {
63
+ const encodedGeneration = new Uint8Array(4);
64
+ new DataView(encodedGeneration.buffer).setUint32(0, generation);
65
+ return expandWithLabel(context, secret, 'secret', encodedGeneration, context.cipherSuite.kdf.size);
66
+ }
67
+ /**
68
+ * Step a member's OWN sending ratchet forward to `target`, the generation its next frame
69
+ * uses, without encrypting anything. Each step is the one ts-mls's `consumeRatchet` takes
70
+ * per sent frame: the secret advances, the generation increments, and `unusedGenerations`
71
+ * is untouched (a sender keeps no skipped keys for itself). Non-mutating; the returned
72
+ * `consumed` are the retired chain secrets, for the caller to zero once it adopts the result.
73
+ * On a throw, the secrets derived so far are zeroed and the input ratchet is left intact.
74
+ */ export async function advanceSendingRatchet(context, ratchet, target) {
75
+ const consumed = [];
76
+ let { secret, generation } = ratchet;
77
+ try {
78
+ while(generation < target){
79
+ consumed.push(secret);
80
+ secret = await nextRatchetSecret(context, secret, generation);
81
+ generation++;
82
+ }
83
+ } catch (error) {
84
+ // The input chain secret still belongs to the caller's state; everything derived from
85
+ // it is unreachable once this throws, so wipe it rather than leave it for GC.
86
+ for (const derived of [
87
+ ...consumed.slice(1),
88
+ secret
89
+ ]){
90
+ if (derived !== ratchet.secret) derived.fill(0);
91
+ }
92
+ throw error;
93
+ }
94
+ return {
95
+ ratchet: {
96
+ ...ratchet,
97
+ secret,
98
+ generation
99
+ },
100
+ consumed
101
+ };
102
+ }
@@ -17,6 +17,12 @@ export type PrivateCommitFrame = {
17
17
  ciphertext: Uint8Array;
18
18
  authenticatedData: Uint8Array;
19
19
  };
20
+ /**
21
+ * MLS `ExpandWithLabel(Secret, Label, Context, Length)`: `KDF.Expand` over the KDFLabel
22
+ * struct `{ uint16 length; opaque label<V> = "MLS 1.0 " + Label; opaque context<V> }`.
23
+ * Shared with the sender ratchet advance in `secret-tree.ts`.
24
+ */
25
+ export declare function expandWithLabel(context: MlsContext, secret: Uint8Array, label: string, labelContext: Uint8Array, length: number): Promise<Uint8Array>;
20
26
  /**
21
27
  * Decrypt a PrivateMessage's sender-data and return the committer's leaf index, or `null`
22
28
  * if the AEAD refuses the bytes or the plaintext is malformed. Non-mutating: the
@@ -55,7 +55,8 @@ function uint64(n) {
55
55
  /**
56
56
  * MLS `ExpandWithLabel(Secret, Label, Context, Length)`: `KDF.Expand` over the KDFLabel
57
57
  * struct `{ uint16 length; opaque label<V> = "MLS 1.0 " + Label; opaque context<V> }`.
58
- */ function expandWithLabel(context, secret, label, labelContext, length) {
58
+ * Shared with the sender ratchet advance in `secret-tree.ts`.
59
+ */ export function expandWithLabel(context, secret, label, labelContext, length) {
59
60
  const kdfLabel = concat([
60
61
  uint16(length),
61
62
  varLen(concat([
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/mls",
3
- "version": "0.10.4",
3
+ "version": "0.10.6",
4
4
  "description": "E2EE group identity and membership for Enkaku using MLS",
5
5
  "keywords": [
6
6
  "mls",
@@ -25,14 +25,14 @@
25
25
  "lib/*"
26
26
  ],
27
27
  "dependencies": {
28
- "@kokuin/capability": "^0.4.1",
28
+ "@kokuin/capability": "^0.4.2",
29
29
  "@kokuin/controller": "^0.1.0",
30
30
  "@kokuin/token": "^0.5.1",
31
31
  "@noble/ciphers": "^2.4.0",
32
32
  "@noble/curves": "^2.4.0",
33
33
  "@noble/hashes": "^2.4.0",
34
- "@sozai/codec": "^0.4.2",
35
- "@sozai/event": "^0.1.5",
34
+ "@sozai/codec": "^0.4.3",
35
+ "@sozai/event": "^0.1.6",
36
36
  "@sozai/runtime": "^0.1.0",
37
37
  "ts-mls": "2.0.0-rc.13"
38
38
  },