@kumiai/mls 0.10.3 → 0.10.5

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.
@@ -279,6 +279,32 @@ 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>;
282
308
  /**
283
309
  * Open an application message sealed for the group and recover WHO SENT IT — the
284
310
  * counterpart to {@link encrypt}, and the read half of the group's application lane.
@@ -1,6 +1,6 @@
1
1
  import { 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, 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';
@@ -17,6 +17,7 @@ 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
@@ -41,6 +42,33 @@ export function mutexFor(handle) {
41
42
  * material does not linger in the heap after the state that used it is replaced. */ function zeroAll(buffers) {
42
43
  for (const buffer of buffers)buffer.fill(0);
43
44
  }
45
+ /** Zero the secrets `next` holds that `prior` does not: what a discarded derivation produced. */ function zeroFreshSecrets(prior, next) {
46
+ const held = new Set();
47
+ for (const secret of Object.values(prior.intermediateNodes))held.add(secret);
48
+ for (const leaf of Object.values(prior.leafNodes)){
49
+ held.add(leaf.application.secret);
50
+ held.add(leaf.handshake.secret);
51
+ }
52
+ const fresh = [
53
+ ...Object.values(next.intermediateNodes)
54
+ ];
55
+ for (const leaf of Object.values(next.leafNodes)){
56
+ fresh.push(leaf.application.secret, leaf.handshake.secret);
57
+ }
58
+ for (const secret of fresh)if (!held.has(secret)) secret.fill(0);
59
+ }
60
+ /** ts-mls's guard ahead of every application send, which its index does not export.
61
+ * Same checks, same errors, so a ratchet-only advance refuses exactly as encrypt does. */ function checkCanSendApplicationMessages(state) {
62
+ if (Object.keys(state.unappliedProposals).length !== 0) {
63
+ throw new UsageError('Cannot send application message with unapplied proposals');
64
+ }
65
+ if (state.groupActiveState.kind === 'suspendedPendingReinit') {
66
+ throw new UsageError('Cannot send messages while Group is suspended pending reinit');
67
+ }
68
+ if (state.groupActiveState.kind === 'removedFromGroup') {
69
+ throw new UsageError('Cannot send messages after being removed from group');
70
+ }
71
+ }
44
72
  /** AAD is not secret, so a length/byte compare is enough — no constant-time need. */ function bytesEqual(a, b) {
45
73
  if (a.length !== b.length) return false;
46
74
  for(let i = 0; i < a.length; i++)if (a[i] !== b[i]) return false;
@@ -171,16 +199,22 @@ export function mutexFor(handle) {
171
199
  };
172
200
  }
173
201
  }
174
- /** Project tree re-admissions from the full ledger fold, never a previous projection.
202
+ /** Project lifecycle tree re-admissions from the full ledger fold, never a previous projection.
175
203
  * A lapsed re-admitted leaf and a leaf inserted after expiry are indistinguishable here;
176
204
  * a genuine expired post-reset package can activate a leaf for a Welcome joiner or an
177
205
  * external rejoiner adopting a fork existing members reject. Ordinary commit admission
178
206
  * still enforces expiry.
179
- */ function registryWithTreeBindings(registry, tree) {
207
+ */ function registryWithTreeBindings(registry, tree, anchor) {
208
+ if (anchor.controller == null) return registry;
180
209
  const devices = new Map(registry.devices);
181
210
  for (const node of tree){
182
211
  if (node?.nodeType !== nodeTypes.leaf || !isDefaultCredential(node.leaf.credential) || node.leaf.credential.credentialType !== defaultCredentialTypes.basic) continue;
183
- const parsed = parseMLSCredentialIdentity(node.leaf.credential.identity);
212
+ let parsed;
213
+ try {
214
+ parsed = parseMLSCredentialIdentity(node.leaf.credential.identity);
215
+ } catch {
216
+ continue;
217
+ }
184
218
  if (!mayReadmitResetDevice(registry, parsed)) continue;
185
219
  const did = normalizeDID(parsed.id);
186
220
  const record = devices.get(did);
@@ -253,7 +287,7 @@ export function mutexFor(handle) {
253
287
  ]));
254
288
  const folded = foldLedgerControl(this.#ledger, anchor, this.groupID);
255
289
  this.#roster = folded.roster;
256
- this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree);
290
+ this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor);
257
291
  // Authentication reads only this handle's registry and lifetime limits.
258
292
  const denyHolder = deviceDenyHolderFor(this.#context);
259
293
  if (denyHolder != null) {
@@ -452,7 +486,7 @@ export function mutexFor(handle) {
452
486
  }
453
487
  const folded = foldLedgerControl(this.#ledger, this.#anchor, this.groupID);
454
488
  this.#roster = folded.roster;
455
- this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree);
489
+ this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor);
456
490
  this.#admission = this.#computeAdmission();
457
491
  if (this.#pendingControlEvents != null) {
458
492
  this.emitControlEvents(appended.filter(({ entry })=>entry.type === DEVICE_ENTRY_TYPE));
@@ -564,7 +598,7 @@ export function mutexFor(handle) {
564
598
  }
565
599
  ]));
566
600
  this.#roster = folded.roster;
567
- this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree);
601
+ this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor);
568
602
  this.#admission = this.#computeAdmission();
569
603
  try {
570
604
  await opts?.persist?.(this);
@@ -766,6 +800,92 @@ export function mutexFor(handle) {
766
800
  });
767
801
  }
768
802
  /**
803
+ * Move this member's own application ratchet forward so the next {@link encrypt} uses
804
+ * generation `target` — the generation read from
805
+ * `state.secretTree.leafNodes[2 * leafIndex].application.generation` (0 before the leaf
806
+ * secret is derived). The resulting state is the one `target - current` empty encrypts
807
+ * would leave, with no frame produced: the retired chain secrets are zeroed, and the
808
+ * epoch and every other member's ratchet are untouched. A target at or below the current
809
+ * generation is a no-op; the ratchet never moves back.
810
+ *
811
+ * For a host that restores a persisted state and must not reuse a generation it may have
812
+ * sent from before a crash. Each skipped generation costs one KDF step, not an encrypt.
813
+ * Receivers must still cross the gap: ts-mls refuses a jump beyond its forward-ratchet
814
+ * window (`maximumForwardRatchetSteps`, 200 by default).
815
+ *
816
+ * No cap by default: a host catching up a stored high-water mark may legitimately step
817
+ * far past any receiver's position (a receiver's window counts from the last generation
818
+ * it processed, not from this state). With `opts.maxSteps`, an advance whose
819
+ * `target - current` exceeds it throws a `RangeError` before any step.
820
+ *
821
+ * Refuses exactly as {@link encrypt} would: a lapsed leaf, unapplied proposals, a
822
+ * removed or suspended member. `target` must be below 0xffffffff, the last generation.
823
+ * On any throw the handle state is unchanged and the secrets derived so far are zeroed.
824
+ */ async advanceSenderGeneration(target, opts) {
825
+ // 0xffffffff is the last uint32 generation: no frame could follow it.
826
+ if (!Number.isInteger(target) || target < 0 || target >= 0xffffffff) {
827
+ throw new RangeError(`advanceSenderGeneration: ${target} is not a sendable uint32 generation`);
828
+ }
829
+ const maxSteps = opts?.maxSteps;
830
+ if (maxSteps != null && (!Number.isInteger(maxSteps) || maxSteps < 0)) {
831
+ throw new RangeError(`advanceSenderGeneration: maxSteps ${maxSteps} is not a step count`);
832
+ }
833
+ return mutexFor(this).run(async ()=>{
834
+ const own = leafAt(this.#state.ratchetTree, this.#state.privatePath.leafIndex);
835
+ if (own != null && isLapsed(this, own)) throw new LeafLapsedError('lapsed');
836
+ checkCanSendApplicationMessages(this.#state);
837
+ const node = Number(this.#state.privatePath.leafIndex) * 2;
838
+ const current = this.#state.secretTree.leafNodes[node]?.application.generation ?? 0;
839
+ if (target <= current) return;
840
+ if (maxSteps != null && target - current > maxSteps) {
841
+ throw new RangeError(`advanceSenderGeneration: ${target - current} steps exceed maxSteps ${maxSteps}`);
842
+ }
843
+ const prior = this.#state;
844
+ let base = prior;
845
+ let retired = [];
846
+ if (prior.secretTree.leafNodes[node] == null) {
847
+ // The leaf secret is still folded into an ancestor. Deriving it walks the tree
848
+ // (and seeds the handshake ratchet), so let ts-mls do it the one way it does:
849
+ // one empty encrypt, whose frame is discarded unsent. It consumes generation 0.
850
+ // Its retired secrets are still referenced by `prior`, so they are zeroed only
851
+ // once the advanced state is adopted.
852
+ const { newState, consumed } = await createApplicationMessage({
853
+ context: this.#context,
854
+ state: prior,
855
+ message: new Uint8Array(),
856
+ authenticatedData: new Uint8Array()
857
+ });
858
+ base = newState;
859
+ retired = consumed;
860
+ }
861
+ const secretTree = base.secretTree;
862
+ const leaf = secretTree.leafNodes[node];
863
+ if (leaf == null) throw new Error('unreachable: an encrypt derives the sender leaf');
864
+ let advanced;
865
+ try {
866
+ advanced = await advanceSendingRatchet(this.#context, leaf.application, target);
867
+ } catch (error) {
868
+ if (base !== prior) zeroFreshSecrets(prior.secretTree, secretTree);
869
+ throw error;
870
+ }
871
+ this.#state = {
872
+ ...base,
873
+ secretTree: {
874
+ ...secretTree,
875
+ leafNodes: {
876
+ ...secretTree.leafNodes,
877
+ [node]: {
878
+ ...leaf,
879
+ application: advanced.ratchet
880
+ }
881
+ }
882
+ }
883
+ };
884
+ zeroAll(retired);
885
+ zeroAll(advanced.consumed);
886
+ });
887
+ }
888
+ /**
769
889
  * Open an application message sealed for the group and recover WHO SENT IT — the
770
890
  * counterpart to {@link encrypt}, and the read half of the group's application lane.
771
891
  *
@@ -1061,7 +1181,7 @@ export function mutexFor(handle) {
1061
1181
  }
1062
1182
  this.#roster = candidateRoster;
1063
1183
  const folded = foldLedgerControl(this.#ledger, this.#anchor, this.groupID);
1064
- this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree);
1184
+ this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor);
1065
1185
  this.#admission = this.#computeAdmission();
1066
1186
  const emit = ()=>{
1067
1187
  this.#notifyAccepted(surfaced, acceptedEntries.filter(({ verified })=>verified.entry.type === DEVICE_ENTRY_TYPE).map(({ verified })=>verified));
@@ -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.3",
3
+ "version": "0.10.5",
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
  },