@kumiai/mls 0.12.1 → 0.12.3

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.
@@ -70,6 +70,7 @@ export type HeldLedgerEntry = {
70
70
  export type LedgerLogEntry = HeldLedgerEntry & {
71
71
  entryID: string;
72
72
  };
73
+ export declare const VERIFIED_LEDGER_TOKEN_CACHE_SIZE = 4096;
73
74
  export type GroupHandleParams = {
74
75
  state: ClientState;
75
76
  credential: MemberCredential;
@@ -93,6 +94,12 @@ export type GroupHandleParams = {
93
94
  export declare class GroupHandle {
94
95
  #private;
95
96
  constructor(params: GroupHandleParams);
97
+ /** Copy the current checkpoint without replaying ledger tokens or sharing mutable state.
98
+ * Pending adoption notifications belong to the source; the copy starts non-speculative. */
99
+ clone(options?: {
100
+ resolveLedgerEntries?: (ids: Array<string>) => Promise<Array<string>>;
101
+ onLedgerEntries?: (entries: Array<VerifiedLedgerEntry>) => void;
102
+ }): GroupHandle;
96
103
  sendAdmission(): SendAdmission;
97
104
  confirmAdopted(): void;
98
105
  get groupID(): string;
@@ -1,4 +1,5 @@
1
1
  import { assertTimeClaimsValid, decodeSignedToken, normalizeDID } from '@kokuin/token';
2
+ import { maybeYield } from '@sozai/async';
2
3
  import { toB64 } from '@sozai/codec';
3
4
  import { EventEmitter } from '@sozai/event';
4
5
  import { contentTypes, createApplicationMessage, createProposal, decode, defaultCredentialTypes, defaultKeyRetentionConfig, defaultProposalTypes, encode, isDefaultCredential, isDefaultProposal, leafNodeSources, mlsExporter, mlsMessageDecoder, mlsMessageEncoder, processMessage as mlsProcessMessage, nodeTypes, senderTypes, UsageError, wireformats } from 'ts-mls';
@@ -24,6 +25,8 @@ import { readSenderLeafIndex } from './sender-data.js';
24
25
  /** One serializer per live handle, so its state-mutating operations run one at a
25
26
  * time in issue order. Keyed weakly: the entry is collected with the handle, and
26
27
  * the handle carries no reference back to it. */ const MUTEXES = new WeakMap();
28
+ // Module-private construction path: only clone can supply an already-folded snapshot.
29
+ const CLONE_SOURCE = Symbol('cloneSource');
27
30
  const HISTORICAL_REGISTRIES = new WeakMap();
28
31
  export function registryAt(group, head) {
29
32
  let cache = HISTORICAL_REGISTRIES.get(group);
@@ -235,6 +238,35 @@ export function mutexFor(handle) {
235
238
  }
236
239
  const VERIFIED_LEDGER_ENTRIES = new WeakMap();
237
240
  const VERIFIED_LEDGER_TOKENS = new WeakMap();
241
+ export const VERIFIED_LEDGER_TOKEN_CACHE_SIZE = 4096;
242
+ const VERIFIED_LEDGER_TOKEN_CACHE = new Map();
243
+ function cachedLedgerEntry(token) {
244
+ const verified = VERIFIED_LEDGER_TOKEN_CACHE.get(token);
245
+ if (verified == null) return undefined;
246
+ VERIFIED_LEDGER_TOKEN_CACHE.delete(token);
247
+ VERIFIED_LEDGER_TOKEN_CACHE.set(token, verified);
248
+ try {
249
+ assertTimeClaimsValid(decodeSignedToken(token).payload);
250
+ return structuredClone(verified);
251
+ } catch {
252
+ return null;
253
+ }
254
+ }
255
+ function cacheLedgerEntry(token, verified) {
256
+ VERIFIED_LEDGER_TOKEN_CACHE.delete(token);
257
+ VERIFIED_LEDGER_TOKEN_CACHE.set(token, structuredClone(verified));
258
+ if (VERIFIED_LEDGER_TOKEN_CACHE.size > VERIFIED_LEDGER_TOKEN_CACHE_SIZE) {
259
+ const oldest = VERIFIED_LEDGER_TOKEN_CACHE.keys().next().value;
260
+ if (oldest != null) VERIFIED_LEDGER_TOKEN_CACHE.delete(oldest);
261
+ }
262
+ }
263
+ async function verifyCachedLedgerEntry(token) {
264
+ const cached = cachedLedgerEntry(token);
265
+ if (cached !== undefined) return cached;
266
+ const verified = await verifyLedgerEntry(token);
267
+ if (verified != null) cacheLedgerEntry(token, verified);
268
+ return verified;
269
+ }
238
270
  // Record provenance before exposing claims; re-enactments keep the original snapshot.
239
271
  function ledgerLogEntry(entryID, token, verified) {
240
272
  const held = {
@@ -316,27 +348,55 @@ function ledgerLogEntry(entryID, token, verified) {
316
348
  this.#commitPolicy = params.commitPolicy;
317
349
  this.#resolveLedgerEntries = params.resolveLedgerEntries;
318
350
  this.#onLedgerEntries = params.onLedgerEntries;
319
- // Seed control state from the genesis anchor in the group's GroupContext. Reading
320
- // it here makes the constructor the single choke no anchorless handle slips
321
- // through: an absent anchor fails closed rather than installing a permissive roster.
322
- const anchor = readGroupAnchor(this);
323
- if (anchor == null) {
324
- throw new Error('group has no anchor extension; cannot seed a control roster');
325
- }
326
- this.#anchor = anchor;
327
- this.#ledger = [
328
- ...params.ledger ?? []
329
- ];
330
- this.#entryBodies = new Map(this.#ledger.map(({ entryID, token, verified })=>[
331
- entryID,
332
- {
333
- token,
334
- verified
351
+ const source = params[CLONE_SOURCE];
352
+ let admission;
353
+ if (source != null) {
354
+ const snapshot = structuredClone({
355
+ anchor: source.#anchor,
356
+ ledger: source.#ledger,
357
+ entryBodies: source.#entryBodies,
358
+ roster: source.#roster,
359
+ registry: source.#registry,
360
+ admission: source.#admission
361
+ });
362
+ this.#anchor = snapshot.anchor;
363
+ this.#ledger = snapshot.ledger;
364
+ this.#entryBodies = snapshot.entryBodies;
365
+ this.#roster = snapshot.roster;
366
+ this.#registry = snapshot.registry;
367
+ admission = Object.freeze(snapshot.admission);
368
+ // Preserve the trusted snapshot, never promote caller-mutated exposed claims.
369
+ for (const [index, held] of source.#ledger.entries()){
370
+ const copied = this.#ledger[index];
371
+ const verified = VERIFIED_LEDGER_ENTRIES.get(held.verified);
372
+ if (copied != null && verified != null) {
373
+ VERIFIED_LEDGER_ENTRIES.set(copied.verified, structuredClone(verified));
335
374
  }
336
- ]));
337
- const folded = foldLedgerControl(this.#ledger, anchor, this.groupID);
338
- this.#roster = folded.roster;
339
- this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor);
375
+ }
376
+ } else {
377
+ // Seed control state from the genesis anchor in the group's GroupContext. Reading
378
+ // it here makes the constructor the single choke no anchorless handle slips
379
+ // through: an absent anchor fails closed rather than installing a permissive roster.
380
+ const anchor = readGroupAnchor(this);
381
+ if (anchor == null) {
382
+ throw new Error('group has no anchor extension; cannot seed a control roster');
383
+ }
384
+ this.#anchor = anchor;
385
+ this.#ledger = [
386
+ ...params.ledger ?? []
387
+ ];
388
+ this.#entryBodies = new Map(this.#ledger.map(({ entryID, token, verified })=>[
389
+ entryID,
390
+ {
391
+ token,
392
+ verified
393
+ }
394
+ ]));
395
+ const folded = foldLedgerControl(this.#ledger, anchor, this.groupID);
396
+ this.#roster = folded.roster;
397
+ this.#registry = registryWithTreeBindings(folded.registry, this.#state.ratchetTree, this.#anchor);
398
+ }
399
+ const anchor = this.#anchor;
340
400
  // Authentication reads only this handle's registry and lifetime limits.
341
401
  const denyHolder = deviceDenyHolderFor(this.#context);
342
402
  if (denyHolder != null) {
@@ -351,7 +411,41 @@ function ledgerLogEntry(entryID, token, verified) {
351
411
  }
352
412
  EMITTERS.set(this, params.events ?? new EventEmitter());
353
413
  this.#pendingControlEvents = params.speculative ? [] : undefined;
354
- this.#admission = this.#computeAdmission();
414
+ this.#admission = admission ?? this.#computeAdmission();
415
+ }
416
+ /** Copy the current checkpoint without replaying ledger tokens or sharing mutable state.
417
+ * Pending adoption notifications belong to the source; the copy starts non-speculative. */ clone(options) {
418
+ const context = deviceDenyHolderFor(this.#context) == null ? {
419
+ ...this.#context,
420
+ // External authentication is caller-owned behaviour, like the cipher suite and callbacks.
421
+ authService: {
422
+ validateCredential: this.#context.authService.validateCredential.bind(this.#context.authService)
423
+ }
424
+ } : createMlsContext(this.#context.cipherSuite, this.#anchor);
425
+ const config = this.#context.clientConfig;
426
+ if (config != null) {
427
+ const equality = config.keyPackageEqualityConfig;
428
+ context.clientConfig = {
429
+ keyRetentionConfig: structuredClone(config.keyRetentionConfig),
430
+ lifetimeConfig: structuredClone(config.lifetimeConfig),
431
+ paddingConfig: structuredClone(config.paddingConfig),
432
+ keyPackageEqualityConfig: {
433
+ compareKeyPackages: equality.compareKeyPackages.bind(equality),
434
+ compareKeyPackageToLeafNode: equality.compareKeyPackageToLeafNode.bind(equality)
435
+ }
436
+ };
437
+ }
438
+ context.externalPsks = structuredClone(this.#context.externalPsks);
439
+ const params = {
440
+ [CLONE_SOURCE]: this,
441
+ state: structuredClone(this.#state),
442
+ credential: structuredClone(this.#credential),
443
+ context,
444
+ commitPolicy: this.#commitPolicy,
445
+ resolveLedgerEntries: options?.resolveLedgerEntries ?? this.#resolveLedgerEntries,
446
+ onLedgerEntries: options?.onLedgerEntries ?? this.#onLedgerEntries
447
+ };
448
+ return new GroupHandle(params);
355
449
  }
356
450
  #computeAdmission() {
357
451
  const leaf = leafAt(this.#state.ratchetTree, this.#state.privatePath.leafIndex);
@@ -552,6 +646,7 @@ function ledgerLogEntry(entryID, token, verified) {
552
646
  const memo = VERIFIED_LEDGER_TOKENS.get(tokens);
553
647
  const nextMemo = [];
554
648
  for (const [index, token] of tokens.entries()){
649
+ await maybeYield();
555
650
  const held = memo?.[index];
556
651
  let verified;
557
652
  if (held?.token === token) {
@@ -562,7 +657,7 @@ function ledgerLogEntry(entryID, token, verified) {
562
657
  }
563
658
  verified = structuredClone(held.verified);
564
659
  } else {
565
- verified = await verifyLedgerEntry(token);
660
+ verified = await verifyCachedLedgerEntry(token);
566
661
  }
567
662
  if (verified == null || verified.entry.groupID !== this.groupID) continue;
568
663
  const entryID = ledgerEntryDigest(token);
@@ -660,8 +755,9 @@ function ledgerLogEntry(entryID, token, verified) {
660
755
  assertHeadMatches(authenticated.head, computeHead(this.groupID, entryIDs));
661
756
  const log = [];
662
757
  for(let index = 0; index < tokens.length; index++){
758
+ await maybeYield();
663
759
  const token = tokens[index];
664
- const verified = await verifyLedgerEntry(token);
760
+ const verified = await verifyCachedLedgerEntry(token);
665
761
  if (verified == null || verified.entry.groupID !== this.groupID) {
666
762
  // Unreachable past the gate — the chain digests the token bytes, so an
667
763
  // unverifiable or cross-group token cannot sit at a position the head
@@ -1261,10 +1357,11 @@ function ledgerLogEntry(entryID, token, verified) {
1261
1357
  }
1262
1358
  const tokens = await this.#resolveLedgerEntries(missing);
1263
1359
  for (const token of tokens){
1360
+ await maybeYield();
1264
1361
  const id = ledgerEntryDigest(token);
1265
1362
  // Content-addressing binds the untrusted body to the requested id.
1266
1363
  if (resolved.has(id) || !missing.includes(id)) continue;
1267
- const verified = await verifyLedgerEntry(token);
1364
+ const verified = await verifyCachedLedgerEntry(token);
1268
1365
  if (verified == null) continue;
1269
1366
  resolved.set(id, ledgerLogEntry(id, token, verified));
1270
1367
  }
package/lib/ledger.d.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import { type SigningIdentity } from '@kokuin/token';
2
+ export declare const LEDGER_ENTRY_DIGEST_CACHE_SIZE = 4096;
3
+ /** @internal */
4
+ export declare function ledgerEntryDigestCacheSize(): number;
2
5
  /**
3
6
  * A control-ledger claim. The payload of a signed ledger token: `type` selects
4
7
  * the reducer, `groupID` binds the claim to a single group, `subject` is the
package/lib/ledger.js CHANGED
@@ -1,5 +1,10 @@
1
1
  import { encodeMultibase, isVerifiedToken, multihashSHA256, normalizeDID, stringifyToken, verifyToken } from '@kokuin/token';
2
2
  const textEncoder = new TextEncoder();
3
+ export const LEDGER_ENTRY_DIGEST_CACHE_SIZE = 4096;
4
+ const LEDGER_ENTRY_DIGEST_CACHE = new Map();
5
+ /** @internal */ export function ledgerEntryDigestCacheSize() {
6
+ return LEDGER_ENTRY_DIGEST_CACHE.size;
7
+ }
3
8
  /**
4
9
  * Sign a ledger entry. The signer fills `iss` with its DID, so the signature
5
10
  * covers every claim field — including `groupID` and `ord` — and binds the
@@ -63,5 +68,17 @@ const textEncoder = new TextEncoder();
63
68
  * Content-addressed digest of a signed ledger token, used as the append-only
64
69
  * store's dedup key. Multibase-encoded SHA-256 multihash over the token bytes.
65
70
  */ export function ledgerEntryDigest(signedToken) {
66
- return encodeMultibase(multihashSHA256(textEncoder.encode(signedToken)));
71
+ const cached = LEDGER_ENTRY_DIGEST_CACHE.get(signedToken);
72
+ if (cached != null) {
73
+ LEDGER_ENTRY_DIGEST_CACHE.delete(signedToken);
74
+ LEDGER_ENTRY_DIGEST_CACHE.set(signedToken, cached);
75
+ return cached;
76
+ }
77
+ const digest = encodeMultibase(multihashSHA256(textEncoder.encode(signedToken)));
78
+ LEDGER_ENTRY_DIGEST_CACHE.set(signedToken, digest);
79
+ if (LEDGER_ENTRY_DIGEST_CACHE.size > LEDGER_ENTRY_DIGEST_CACHE_SIZE) {
80
+ const oldest = LEDGER_ENTRY_DIGEST_CACHE.keys().next().value;
81
+ if (oldest != null) LEDGER_ENTRY_DIGEST_CACHE.delete(oldest);
82
+ }
83
+ return digest;
67
84
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/mls",
3
- "version": "0.12.1",
3
+ "version": "0.12.3",
4
4
  "description": "E2EE group identity and membership for Enkaku using MLS",
5
5
  "keywords": [
6
6
  "mls",
@@ -27,10 +27,11 @@
27
27
  "dependencies": {
28
28
  "@kokuin/capability": "^0.5.2",
29
29
  "@kokuin/controller": "^0.2.5",
30
- "@kokuin/token": "^0.6.2",
30
+ "@kokuin/token": "^0.6.4",
31
31
  "@noble/ciphers": "^2.4.0",
32
32
  "@noble/curves": "^2.4.0",
33
33
  "@noble/hashes": "^2.4.0",
34
+ "@sozai/async": "^0.4.3",
34
35
  "@sozai/codec": "^0.4.3",
35
36
  "@sozai/event": "^0.1.6",
36
37
  "@sozai/runtime": "^0.1.0",