@kumiai/mls 0.10.6 → 0.10.7

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
@@ -12,6 +12,23 @@ Serialise reserve, build and consume against the source handle. Adopt the derive
12
12
  Persistence must complete durably and leave storage unchanged on rejection.
13
13
  The `@kumiai/mls-rpc` adapter supplies both reservation hooks to the RPC peer.
14
14
 
15
+ ## Persisted client state
16
+
17
+ `encodeClientState` and `decodeClientState` support only format v2. Other versions throw an unsupported-version error.
18
+ Malformed or truncated v2 blobs return `undefined`, as does empty input.
19
+ There is no migration path from another client-state format.
20
+
21
+ The layout is a version byte (`2`), flags byte (`0` or `1`), optional reservation, body, and proposal references.
22
+ Flag `1` includes a uint64 epoch, uint32 generation, and consumed byte (`0` or `1`).
23
+ The ts-mls body has a uint32 byte length and a 64,000,000-byte decoding limit.
24
+ A uint32 count precedes UTF-8 references, each with a uint32 byte length.
25
+ References ascend strictly by JS string (UTF-16 code unit) ordering.
26
+ References preserve unapplied proposals whose sender is exactly leaf zero, working around ts-mls rc.13 dropping optional numeric zero.
27
+ All integers are big-endian. Invalid flags, consumed bytes, references, or trailing bytes make the blob malformed.
28
+ Decoding copies the body so ratcheting cannot zero secrets in stored bytes.
29
+ Decoding requires the body's canonical re-encoding to match its stored bytes before restoring leaf-zero senders.
30
+ `encodeClientState` throws `ClientStateReservationError` unless the reservation epoch is a uint64 bigint and its generation a uint32 integer.
31
+
15
32
  ## Capabilities
16
33
 
17
34
  - `createGroup` — creator opens a new group as its sole member and first admin
package/lib/codec.js CHANGED
@@ -1,56 +1,112 @@
1
- import { clientStateDecoder, clientStateEncoder, decode, encode } from 'ts-mls';
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.
6
- */ const CLIENT_STATE_VERSION = 1;
7
- const RESERVATION_STATE_VERSION = 3;
1
+ import { clientStateDecoder, clientStateEncoder, encode } from 'ts-mls';
2
+ import { ClientStateReservationError } from './errors.js';
3
+ /** v2: flags, optional reservation, length-prefixed ts-mls body, then sorted leaf-zero refs.
4
+ * Reservation fields are epoch (uint64), generation (uint32), consumed (uint8).
5
+ * Body length, ref count and UTF-8 ref lengths are uint32. All integers are big-endian.
6
+ * Refs ascend by JS string (UTF-16 code unit) ordering.
7
+ * This is the only supported client-state format.
8
+ */ const CLIENT_STATE_VERSION = 2;
8
9
  const RESERVATION_BYTES = 13;
10
+ // Match ts-mls decode()'s default input limit, even though we call the decoder directly.
11
+ const MAX_BODY_BYTES = 64_000_000;
9
12
  export function decodeClientState(encoded) {
10
- // Too short to hold the version byte is a TRUNCATED read, not a version this build does not
11
- // speak, and the two are separate diagnoses — the same split `@kumiai/mls-rpc`'s `openEntries`
12
- // makes ("not a sealed blob" before "unsupported blob version"). Without this guard `encoded[0]`
13
- // is `undefined` on an empty buffer, which falls into the version branch below and reports
14
- // "unsupported client-state version undefined": the loudest possible way to misdescribe an
15
- // empty store as a format from the future. Truncated bytes return `undefined`, as every other
16
- // truncated read here does.
17
13
  if (encoded.length === 0) return undefined;
18
- // Distinguishable on purpose. `decode()` below returns `undefined` for malformed or
19
- // truncated bytes reaching `ts-mls`, and that stays `undefined` — but an unknown version
20
- // byte is not that kind of failure, so it throws instead of returning the same `undefined`
21
- // a decode failure would. Without this, a version mismatch and a corrupted store are the
22
- // same value of the same type and a caller cannot tell them apart.
23
- if (encoded[0] !== CLIENT_STATE_VERSION && encoded[0] !== RESERVATION_STATE_VERSION) {
14
+ // Unsupported versions remain distinguishable from malformed storage.
15
+ if (encoded[0] !== CLIENT_STATE_VERSION) {
24
16
  throw new Error(`decodeClientState: unsupported client-state version ${encoded[0]}`);
25
17
  }
26
- // A copy: ts-mls decodes secrets as views, and ratcheting zeroes consumed ones in place.
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;
18
+ const flags = encoded[1];
19
+ if (flags !== 0 && flags !== 1) return undefined;
29
20
  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
- }
21
+ let offset = 2;
22
+ let reservation;
23
+ if (flags === 1) {
24
+ if (encoded.length < offset + RESERVATION_BYTES || encoded[14] !== 0 && encoded[14] !== 1) return undefined;
25
+ reservation = {
26
+ epoch: view.getBigUint64(offset),
27
+ generation: view.getUint32(offset + 8),
28
+ consumed: encoded[14] === 1
29
+ };
30
+ offset += RESERVATION_BYTES;
31
+ }
32
+ const readLength = ()=>{
33
+ if (encoded.length - offset < 4) return undefined;
34
+ const length = view.getUint32(offset);
35
+ offset += 4;
36
+ return length;
39
37
  };
38
+ const bodyLength = readLength();
39
+ if (bodyLength === undefined || bodyLength > MAX_BODY_BYTES || bodyLength > encoded.length - offset - 4) {
40
+ return undefined;
41
+ }
42
+ // ts-mls secrets are views. Even Buffer inputs must be copied before ratcheting zeroes them.
43
+ const bodyCopy = new Uint8Array(encoded.subarray(offset, offset + bodyLength));
44
+ offset += bodyLength;
45
+ const refCount = readLength();
46
+ if (refCount === undefined || refCount > Math.floor((encoded.length - offset) / 4)) {
47
+ return undefined;
48
+ }
49
+ try {
50
+ const result = clientStateDecoder(bodyCopy, 0);
51
+ if (result === undefined || result[1] !== bodyCopy.length) return undefined;
52
+ const state = result[0];
53
+ // rc.13 accepts invalid optional tags and elements extending past an inner vector boundary.
54
+ const canonicalBody = encode(clientStateEncoder, state);
55
+ if (canonicalBody.length !== bodyCopy.length || !canonicalBody.every((byte, index)=>byte === bodyCopy[index])) {
56
+ return undefined;
57
+ }
58
+ const textDecoder = new TextDecoder('utf-8', {
59
+ fatal: true,
60
+ ignoreBOM: true
61
+ });
62
+ let previousRef;
63
+ for(let index = 0; index < refCount; index++){
64
+ const refLength = readLength();
65
+ if (refLength === undefined || refLength > encoded.length - offset) return undefined;
66
+ const ref = textDecoder.decode(encoded.subarray(offset, offset + refLength));
67
+ offset += refLength;
68
+ if (previousRef !== undefined && ref <= previousRef) return undefined;
69
+ if (!Object.hasOwn(state.unappliedProposals, ref)) return undefined;
70
+ const proposal = state.unappliedProposals[ref];
71
+ if (proposal === undefined || proposal.senderLeafIndex !== undefined) return undefined;
72
+ proposal.senderLeafIndex = 0;
73
+ previousRef = ref;
74
+ }
75
+ if (offset !== encoded.length) return undefined;
76
+ if (reservation !== undefined) state.handshakeReservation = reservation;
77
+ return state;
78
+ } catch {
79
+ return undefined;
80
+ }
40
81
  }
41
82
  export function encodeClientState(state) {
42
- const body = encode(clientStateEncoder, state);
43
83
  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;
84
+ if (reservation != null && (typeof reservation.epoch !== 'bigint' || reservation.epoch < 0n || reservation.epoch > 0xffffffffffffffffn || !Number.isInteger(reservation.generation) || reservation.generation < 0 || reservation.generation > 0xffffffff)) {
85
+ throw new ClientStateReservationError();
86
+ }
87
+ const body = encode(clientStateEncoder, state);
88
+ // rc.13 optionalEncoder drops numeric zero. Preserve only exact zero senders separately.
89
+ const textEncoder = new TextEncoder();
90
+ const refs = Object.keys(state.unappliedProposals).filter((ref)=>state.unappliedProposals[ref]?.senderLeafIndex === 0).sort().map((ref)=>textEncoder.encode(ref));
91
+ const header = reservation == null ? 2 : 2 + RESERVATION_BYTES;
92
+ const out = new Uint8Array(header + 8 + body.length + refs.reduce((length, ref)=>length + 4 + ref.length, 0));
93
+ const view = new DataView(out.buffer);
94
+ out[0] = CLIENT_STATE_VERSION;
95
+ out[1] = reservation == null ? 0 : 1;
47
96
  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;
97
+ view.setBigUint64(2, reservation.epoch);
98
+ view.setUint32(10, reservation.generation);
99
+ out[14] = reservation.consumed ? 1 : 0;
100
+ }
101
+ view.setUint32(header, body.length);
102
+ out.set(body, header + 4);
103
+ view.setUint32(header + 4 + body.length, refs.length);
104
+ let offset = header + 8 + body.length;
105
+ for (const ref of refs){
106
+ view.setUint32(offset, ref.length);
107
+ out.set(ref, offset + 4);
108
+ offset += 4 + ref.length;
52
109
  }
53
- out.set(body, header);
54
110
  return out;
55
111
  }
56
112
  export function sanitizeRatchetTree(tree) {
package/lib/errors.d.ts CHANGED
@@ -26,3 +26,6 @@ export declare class HandshakeWindowConfigError extends Error {
26
26
  export declare class HandshakeReservationError extends Error {
27
27
  constructor();
28
28
  }
29
+ export declare class ClientStateReservationError extends Error {
30
+ constructor();
31
+ }
package/lib/errors.js CHANGED
@@ -49,3 +49,9 @@ export class HandshakeReservationError extends Error {
49
49
  this.name = 'HandshakeReservationError';
50
50
  }
51
51
  }
52
+ export class ClientStateReservationError extends Error {
53
+ constructor(){
54
+ super('Handshake reservation epoch must be a uint64 bigint and generation a uint32 integer');
55
+ this.name = 'ClientStateReservationError';
56
+ }
57
+ }
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 { HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, type LeafBindingReason, LeafLapsedError, type LeafLapsedReason, RevokeProofError, type RevokeProofReason, } from './errors.js';
13
+ export { ClientStateReservationError, 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 { HandshakeReservationError, HandshakeWindowConfigError, HandshakeWindowError, LeafBindingError, LeafLapsedError, RevokeProofError } from './errors.js';
10
+ export { ClientStateReservationError, 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';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/mls",
3
- "version": "0.10.6",
3
+ "version": "0.10.7",
4
4
  "description": "E2EE group identity and membership for Enkaku using MLS",
5
5
  "keywords": [
6
6
  "mls",