@kumiai/mls 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,7 +7,7 @@ Credential-aware MLS (RFC 9420) group lifecycle for enkaku. Wraps [`ts-mls`](htt
7
7
  - `createGroup` — creator opens a new group as its sole member and first admin
8
8
  - `createInvite` + `commitInvite` — an admin signs the invitee's role entry and produces the MLS Commit + Welcome
9
9
  - `processWelcome` — invitee joins after folding the ledger the invite carries and checking its head
10
- - `commitLedgerEntries` — an admin promotes or demotes by committing signed `group.role` entries
10
+ - `commitLedgerEntries` — an admin promotes or demotes by committing signed `kumiai.role` entries
11
11
  - `removeMember` — an admin evicts a leaf and rotates keys
12
12
  - `restoreGroup` — rehydrate a `GroupHandle` from persisted `ClientState` and the stored ledger tokens
13
13
  - `exportGroupInfo` + `joinGroupExternal` — stale-device self-rejoin (see below)
@@ -16,7 +16,7 @@ Credential-aware MLS (RFC 9420) group lifecycle for enkaku. Wraps [`ts-mls`](htt
16
16
 
17
17
  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.
18
18
 
19
- - **The ledger is an ordered log of enactments.** Each entry is a token signed by its issuer (a `group.role` entry names a subject DID and grants `admin` or `member`). 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.
19
+ - **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.
20
20
  - **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.
21
21
  - **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.
22
22
  - **`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.
@@ -67,7 +67,7 @@ An external commit is enforced as a **resync of an existing roster member**, nev
67
67
 
68
68
  ### ⚠️ Security: removal is not revocation
69
69
 
70
- MLS has no cryptographic member revocation. `removeMember` evicts a leaf; it does not erase the removed DID's `group.role` grant, 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:
70
+ 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:
71
71
 
72
72
  - Rotate the group: create a new group, migrate non-removed members via fresh invites, abandon the old group.
73
73
  - Enforce access control outside MLS: block the removed device at the transport layer (e.g. hub auth).
package/lib/anchor.d.ts CHANGED
@@ -1,87 +1,73 @@
1
1
  import type { Capabilities, GroupContextExtension } from 'ts-mls';
2
2
  import type { GroupHandle } from './group.js';
3
3
  /**
4
- * MLS GroupContext extension type carrying the genesis anchor. A uint16 outside
5
- * the MLS default extension types (1–5) and clear of every reserved GREASE
6
- * value, so it can never collide with a ts-mls built-in or a probing extension.
4
+ * MLS GroupContext extension type for the genesis anchor. A uint16 outside the MLS default
5
+ * range (1–5) and clear of GREASE values, so it never collides with a built-in or a probe.
7
6
  */
8
7
  export declare const GROUP_ANCHOR_EXTENSION_TYPE = 61696;
9
8
  /**
10
- * MLS GroupContext extension type carrying the control-ledger head. Its update
11
- * logic arrives in a later step, but its type is reserved and advertised from
12
- * the outset (see {@link controlCapabilities}) so an anchored group can later
13
- * grow a head without every member's leaf being rejected.
9
+ * MLS GroupContext extension type for the control-ledger head. Update logic lands in a later
10
+ * step; the type is reserved and advertised now (see {@link controlCapabilities}) so member
11
+ * leaves don't need to be rejected once it grows data.
14
12
  */
15
13
  export declare const LEDGER_HEAD_EXTENSION_TYPE = 61697;
16
14
  /**
17
- * Genesis anchor baked into the MLS GroupContext at group creation: the creator
18
- * DID is the epoch-0 admin. It survives every epoch and is authenticated by the
19
- * GroupInfo signature, so every joiner reads the same value. Treated as
20
- * immutable for the lifetime of the group.
15
+ * Reserved for a future control extension; carries no data today. Reserved and advertised now
16
+ * for the same reason as {@link LEDGER_HEAD_EXTENSION_TYPE}: RFC 9420 requires every member
17
+ * leaf to advertise each custom GroupContext extension type it can carry, and leaves cannot be
18
+ * rewritten — a type introduced after members join can never be installed without re-admitting
19
+ * everyone.
20
+ */
21
+ export declare const RESERVED_EXTENSION_TYPE = 61698;
22
+ /**
23
+ * Genesis anchor baked into the MLS GroupContext at creation: the creator DID is the epoch-0
24
+ * admin. Survives every epoch, authenticated by the GroupInfo signature, treated as immutable.
21
25
  */
22
26
  export type GroupAnchor = {
23
27
  creatorDID: string;
24
28
  version: number;
25
29
  /**
26
- * Opaque consumer payload, written once at group creation. `@kumiai/mls`
27
- * never reads or interprets it — it is any JSON value the consumer chooses. A
28
- * consumer holding raw bytes encodes them to a JSON-safe form (e.g. base64)
29
- * itself; the anchor container is already JSON, so it does not double-encode.
30
- * Kubun stores its recovery seed here.
30
+ * Opaque consumer payload written once at creation; `@kumiai/mls` never reads or interprets
31
+ * it. A consumer holding raw bytes must JSON-safe-encode them (e.g. base64) itself. Kubun
32
+ * stores its recovery seed here.
31
33
  */
32
34
  app?: unknown;
33
35
  };
34
- /** Serialize an anchor to its GroupContext extension bytes. */
35
36
  export declare function encodeGroupAnchor(anchor: GroupAnchor): Uint8Array;
36
37
  /**
37
- * Tolerant decode: returns null on malformed bytes or wrong shape, never
38
- * throws. `creatorDID` must be a string and `version` a number; `app` is
39
- * optional and any JSON value, so an anchor without it is valid, not malformed.
40
- * (A consumer that requires a specific `app` shape enforces that in its own
41
- * decode of `app`, not here.)
38
+ * Tolerant decode: null on malformed bytes or wrong shape, never throws. `creatorDID` must be a
39
+ * string and `version` a number; `app` is optional, so its absence isn't malformed. A consumer
40
+ * needing a specific `app` shape validates that itself.
42
41
  */
43
42
  export declare function decodeGroupAnchor(bytes: Uint8Array): GroupAnchor | null;
44
- /** Build the genesis-anchor GroupContext extension for an anchor value. */
45
43
  export declare function buildGroupAnchorExtension(anchor: GroupAnchor): GroupContextExtension;
46
44
  /** Build the anchor extension for a freshly created group at the current version. */
47
45
  export declare function buildCurrentGroupAnchorExtension(creatorDID: string, app?: unknown): GroupContextExtension;
48
46
  /**
49
- * Leaf-node capabilities advertising both control GroupContext extension types
50
- * (genesis anchor and ledger head). RFC 9420 requires every member leaf to
51
- * advertise each custom GroupContext extension type, or `commitInvite` rejects
52
- * the added leaf. Both types are advertised from the outset — even before the
53
- * ledger head carries data — so an anchored group can later grow a head without
54
- * re-admitting members. Pass these at both `createGroup` (creator leaf) and
55
- * `createKeyPackageBundle` (invitee leaf) so a control group can be joined.
47
+ * Leaf capabilities advertising all three control GroupContext extension types (genesis
48
+ * anchor, ledger head, reserved). RFC 9420 requires every leaf to advertise each custom
49
+ * extension type or `commitInvite` rejects it; all three are advertised now, before the latter
50
+ * two carry data, so they can be grown later without re-admitting members. Pass at both
51
+ * `createGroup` (creator leaf) and `createKeyPackageBundle` (invitee leaf).
56
52
  *
57
- * Idempotent: each type appears exactly once even if the defaults already carry
58
- * it.
53
+ * Idempotent: each type appears once even if the defaults already carry it.
59
54
  */
60
55
  export declare function controlCapabilities(): Capabilities;
61
56
  /**
62
- * The anchor's raw GroupContext extension, exactly as it sits in the group, or
63
- * null when genuinely absent. Unlike {@link readGroupAnchor} this does not
64
- * decode — it is the source of the verbatim bytes a future group-context-
65
- * extensions (GCE) proposal must copy.
66
- *
67
- * A GCE proposal replaces the *entire* GroupContext extension list, so every
68
- * ledger-head update must re-include the anchor unchanged, and the receiving
69
- * commit policy byte-compares the proposed anchor's `extensionData` against its
70
- * own. Re-encoding a decoded {@link GroupAnchor} instead of copying these bytes
71
- * can make that comparison fail on identical content (JSON key order, number
72
- * formatting, dropped `undefined` keys) — an intermittent failure that looks
73
- * exactly like an anchor-tampering attack. The decoded anchor is for reading;
74
- * these bytes are for round-tripping.
57
+ * The anchor's raw extension bytes, exactly as stored, or null if absent. Unlike
58
+ * {@link readGroupAnchor} this doesn't decode — a GCE (group-context-extensions) proposal must
59
+ * copy these verbatim, since it replaces the *entire* extension list and the commit policy
60
+ * byte-compares the proposed anchor's `extensionData` against this. Re-encoding a decoded
61
+ * {@link GroupAnchor} instead can fail that comparison on identical content (JSON key order,
62
+ * number formatting, dropped `undefined` keys) — indistinguishable from tampering. Use these
63
+ * bytes for round-tripping; the decoded anchor is for reading only.
75
64
  */
76
65
  export declare function readGroupAnchorExtension(handle: GroupHandle): GroupContextExtension | null;
77
66
  /**
78
- * Read and decode the genesis anchor from a group handle. Returns null only
79
- * when the anchor extension is genuinely absent. A present-but-undecodable
80
- * extension is corruption, not absence, and throws — so a control gate reads it
81
- * as "anchor unreadable" and fails closed rather than silently downgrading. (The
82
- * anchor is written once at creation and authenticated by the GroupInfo
83
- * signature, so this is a corruption guard, not a forgery path.) For bytes to
84
- * copy into a proposal, use {@link readGroupAnchorExtension}, never a re-encode
85
- * of this result.
67
+ * Read and decode the genesis anchor. Null only when genuinely absent; a present-but-
68
+ * undecodable extension is corruption and throws, so a control gate fails closed instead of
69
+ * silently downgrading (the anchor is authenticated by the GroupInfo signature, so this guards
70
+ * corruption, not forgery). Use {@link readGroupAnchorExtension} for bytes to copy into a
71
+ * proposal — never a re-encode of this result.
86
72
  */
87
73
  export declare function readGroupAnchor(handle: GroupHandle): GroupAnchor | null;
package/lib/anchor.js CHANGED
@@ -1,27 +1,30 @@
1
1
  import { defaultCapabilities, makeCustomExtension } from 'ts-mls';
2
2
  /**
3
- * MLS GroupContext extension type carrying the genesis anchor. A uint16 outside
4
- * the MLS default extension types (1–5) and clear of every reserved GREASE
5
- * value, so it can never collide with a ts-mls built-in or a probing extension.
3
+ * MLS GroupContext extension type for the genesis anchor. A uint16 outside the MLS default
4
+ * range (1–5) and clear of GREASE values, so it never collides with a built-in or a probe.
6
5
  */ export const GROUP_ANCHOR_EXTENSION_TYPE = 0xf100;
7
6
  /**
8
- * MLS GroupContext extension type carrying the control-ledger head. Its update
9
- * logic arrives in a later step, but its type is reserved and advertised from
10
- * the outset (see {@link controlCapabilities}) so an anchored group can later
11
- * grow a head without every member's leaf being rejected.
7
+ * MLS GroupContext extension type for the control-ledger head. Update logic lands in a later
8
+ * step; the type is reserved and advertised now (see {@link controlCapabilities}) so member
9
+ * leaves don't need to be rejected once it grows data.
12
10
  */ export const LEDGER_HEAD_EXTENSION_TYPE = 0xf101;
11
+ /**
12
+ * Reserved for a future control extension; carries no data today. Reserved and advertised now
13
+ * for the same reason as {@link LEDGER_HEAD_EXTENSION_TYPE}: RFC 9420 requires every member
14
+ * leaf to advertise each custom GroupContext extension type it can carry, and leaves cannot be
15
+ * rewritten — a type introduced after members join can never be installed without re-admitting
16
+ * everyone.
17
+ */ export const RESERVED_EXTENSION_TYPE = 0xf102;
13
18
  const CURRENT_VERSION = 1;
14
19
  const encoder = new TextEncoder();
15
20
  const decoder = new TextDecoder();
16
- /** Serialize an anchor to its GroupContext extension bytes. */ export function encodeGroupAnchor(anchor) {
21
+ export function encodeGroupAnchor(anchor) {
17
22
  return encoder.encode(JSON.stringify(anchor));
18
23
  }
19
24
  /**
20
- * Tolerant decode: returns null on malformed bytes or wrong shape, never
21
- * throws. `creatorDID` must be a string and `version` a number; `app` is
22
- * optional and any JSON value, so an anchor without it is valid, not malformed.
23
- * (A consumer that requires a specific `app` shape enforces that in its own
24
- * decode of `app`, not here.)
25
+ * Tolerant decode: null on malformed bytes or wrong shape, never throws. `creatorDID` must be a
26
+ * string and `version` a number; `app` is optional, so its absence isn't malformed. A consumer
27
+ * needing a specific `app` shape validates that itself.
25
28
  */ export function decodeGroupAnchor(bytes) {
26
29
  let parsed;
27
30
  try {
@@ -45,7 +48,7 @@ const decoder = new TextDecoder();
45
48
  }
46
49
  return anchor;
47
50
  }
48
- /** Build the genesis-anchor GroupContext extension for an anchor value. */ export function buildGroupAnchorExtension(anchor) {
51
+ export function buildGroupAnchorExtension(anchor) {
49
52
  return makeCustomExtension({
50
53
  extensionType: GROUP_ANCHOR_EXTENSION_TYPE,
51
54
  extensionData: encodeGroupAnchor(anchor)
@@ -59,21 +62,19 @@ const decoder = new TextDecoder();
59
62
  });
60
63
  }
61
64
  /**
62
- * Leaf-node capabilities advertising both control GroupContext extension types
63
- * (genesis anchor and ledger head). RFC 9420 requires every member leaf to
64
- * advertise each custom GroupContext extension type, or `commitInvite` rejects
65
- * the added leaf. Both types are advertised from the outset — even before the
66
- * ledger head carries data — so an anchored group can later grow a head without
67
- * re-admitting members. Pass these at both `createGroup` (creator leaf) and
68
- * `createKeyPackageBundle` (invitee leaf) so a control group can be joined.
65
+ * Leaf capabilities advertising all three control GroupContext extension types (genesis
66
+ * anchor, ledger head, reserved). RFC 9420 requires every leaf to advertise each custom
67
+ * extension type or `commitInvite` rejects it; all three are advertised now, before the latter
68
+ * two carry data, so they can be grown later without re-admitting members. Pass at both
69
+ * `createGroup` (creator leaf) and `createKeyPackageBundle` (invitee leaf).
69
70
  *
70
- * Idempotent: each type appears exactly once even if the defaults already carry
71
- * it.
71
+ * Idempotent: each type appears once even if the defaults already carry it.
72
72
  */ export function controlCapabilities() {
73
73
  const base = defaultCapabilities();
74
74
  const extensions = new Set(base.extensions);
75
75
  extensions.add(GROUP_ANCHOR_EXTENSION_TYPE);
76
76
  extensions.add(LEDGER_HEAD_EXTENSION_TYPE);
77
+ extensions.add(RESERVED_EXTENSION_TYPE);
77
78
  return {
78
79
  ...base,
79
80
  extensions: [
@@ -85,31 +86,22 @@ function findAnchorExtension(handle) {
85
86
  return handle.state.groupContext.extensions.find((ext)=>ext.extensionType === GROUP_ANCHOR_EXTENSION_TYPE);
86
87
  }
87
88
  /**
88
- * The anchor's raw GroupContext extension, exactly as it sits in the group, or
89
- * null when genuinely absent. Unlike {@link readGroupAnchor} this does not
90
- * decode — it is the source of the verbatim bytes a future group-context-
91
- * extensions (GCE) proposal must copy.
92
- *
93
- * A GCE proposal replaces the *entire* GroupContext extension list, so every
94
- * ledger-head update must re-include the anchor unchanged, and the receiving
95
- * commit policy byte-compares the proposed anchor's `extensionData` against its
96
- * own. Re-encoding a decoded {@link GroupAnchor} instead of copying these bytes
97
- * can make that comparison fail on identical content (JSON key order, number
98
- * formatting, dropped `undefined` keys) — an intermittent failure that looks
99
- * exactly like an anchor-tampering attack. The decoded anchor is for reading;
100
- * these bytes are for round-tripping.
89
+ * The anchor's raw extension bytes, exactly as stored, or null if absent. Unlike
90
+ * {@link readGroupAnchor} this doesn't decode — a GCE (group-context-extensions) proposal must
91
+ * copy these verbatim, since it replaces the *entire* extension list and the commit policy
92
+ * byte-compares the proposed anchor's `extensionData` against this. Re-encoding a decoded
93
+ * {@link GroupAnchor} instead can fail that comparison on identical content (JSON key order,
94
+ * number formatting, dropped `undefined` keys) — indistinguishable from tampering. Use these
95
+ * bytes for round-tripping; the decoded anchor is for reading only.
101
96
  */ export function readGroupAnchorExtension(handle) {
102
97
  return findAnchorExtension(handle) ?? null;
103
98
  }
104
99
  /**
105
- * Read and decode the genesis anchor from a group handle. Returns null only
106
- * when the anchor extension is genuinely absent. A present-but-undecodable
107
- * extension is corruption, not absence, and throws — so a control gate reads it
108
- * as "anchor unreadable" and fails closed rather than silently downgrading. (The
109
- * anchor is written once at creation and authenticated by the GroupInfo
110
- * signature, so this is a corruption guard, not a forgery path.) For bytes to
111
- * copy into a proposal, use {@link readGroupAnchorExtension}, never a re-encode
112
- * of this result.
100
+ * Read and decode the genesis anchor. Null only when genuinely absent; a present-but-
101
+ * undecodable extension is corruption and throws, so a control gate fails closed instead of
102
+ * silently downgrading (the anchor is authenticated by the GroupInfo signature, so this guards
103
+ * corruption, not forgery). Use {@link readGroupAnchorExtension} for bytes to copy into a
104
+ * proposal — never a re-encode of this result.
113
105
  */ export function readGroupAnchor(handle) {
114
106
  const extension = findAnchorExtension(handle);
115
107
  if (extension == null) {
package/lib/codec.js CHANGED
@@ -1,9 +1,42 @@
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.
14
+ */ const CLIENT_STATE_VERSION = 1;
2
15
  export function decodeClientState(encoded) {
3
- return decode(clientStateDecoder, encoded);
16
+ // Too short to hold the version byte is a TRUNCATED read, not a version this build does not
17
+ // speak, and the two are separate diagnoses — the same split `@kumiai/mls-rpc`'s `openEntries`
18
+ // makes ("not a sealed blob" before "unsupported blob version"). Without this guard `encoded[0]`
19
+ // is `undefined` on an empty buffer, which falls into the version branch below and reports
20
+ // "unsupported client-state version undefined": the loudest possible way to misdescribe an
21
+ // empty store as a format from the future. Truncated bytes return `undefined`, as every other
22
+ // truncated read here does.
23
+ if (encoded.length === 0) return undefined;
24
+ // Distinguishable on purpose. `decode()` below returns `undefined` for malformed or
25
+ // truncated bytes reaching `ts-mls`, and that stays `undefined` — but an unknown version
26
+ // byte is not that kind of failure, so it throws instead of returning the same `undefined`
27
+ // a decode failure would. Without this, a version mismatch and a corrupted store are the
28
+ // same value of the same type and a caller cannot tell them apart.
29
+ if (encoded[0] !== CLIENT_STATE_VERSION) {
30
+ throw new Error(`decodeClientState: unsupported client-state version ${encoded[0]}`);
31
+ }
32
+ return decode(clientStateDecoder, encoded.subarray(1));
4
33
  }
5
34
  export function encodeClientState(state) {
6
- return encode(clientStateEncoder, state);
35
+ const body = encode(clientStateEncoder, state);
36
+ const out = new Uint8Array(1 + body.length);
37
+ out[0] = CLIENT_STATE_VERSION;
38
+ out.set(body, 1);
39
+ return out;
7
40
  }
8
41
  export function sanitizeRatchetTree(tree) {
9
42
  return tree.map((node)=>node == null ? undefined : node);
@@ -14,8 +14,15 @@ export type MemberCredential = {
14
14
  * - did:key identities omit `longForm`.
15
15
  * - did:peer:4 identities MUST carry `longForm`; the auth service decodes it
16
16
  * inline and binds the MLS leaf signature key to a verification method.
17
+ *
18
+ * `v` is the format version. Unlike the client-state blob, this is baked into an MLS leaf and
19
+ * covered by its signature — leaves can never be rewritten. So an identity written before `v`
20
+ * existed lives in a leaf that will exist forever, and absent `v` MUST read as `1` permanently.
21
+ * That tolerance is not a courtesy owed to a transition; there is no version of this code that
22
+ * can stop honoring it without refusing leaves nothing is wrong with.
17
23
  */
18
24
  export type MLSCredentialIdentity = {
25
+ v?: 1;
19
26
  id: string;
20
27
  longForm?: string;
21
28
  };
package/lib/credential.js CHANGED
@@ -4,19 +4,30 @@ export function parseMLSCredentialIdentity(identity) {
4
4
  let parsed;
5
5
  try {
6
6
  parsed = JSON.parse(text);
7
- } catch {
8
- throw new Error('Invalid MLS credential: identity bytes are not valid JSON');
7
+ } catch (cause) {
8
+ throw new Error('Invalid MLS credential: identity bytes are not valid JSON', {
9
+ cause
10
+ });
9
11
  }
10
12
  if (parsed == null || typeof parsed !== 'object') {
11
13
  throw new Error('Invalid MLS credential: identity must be a JSON object');
12
14
  }
13
15
  const candidate = parsed;
16
+ // Absent `v` is v1, permanently — not a default that will one day stop applying. Leaves
17
+ // written before this field existed are signed and can never be rewritten to add it.
18
+ if ('v' in candidate && candidate.v !== 1) {
19
+ throw new Error(`Invalid MLS credential: unsupported identity version ${String(candidate.v)}`);
20
+ }
14
21
  if (typeof candidate.id !== 'string') {
15
22
  throw new Error('Invalid MLS credential: id must be a string');
16
23
  }
17
24
  if ('longForm' in candidate && typeof candidate.longForm !== 'string') {
18
25
  throw new Error('Invalid MLS credential: longForm must be a string when present');
19
26
  }
27
+ // `v` is not echoed back into the result. It is a wire concern — it tells this function how
28
+ // to read the bytes — not something a caller needs to act on; every parsed identity is
29
+ // already normalized to what v1 means by the time it gets here. Add it back only if a
30
+ // caller needs to distinguish a v1-tagged payload from an untagged one, which none do today.
20
31
  const result = {
21
32
  id: candidate.id
22
33
  };
package/lib/crypto.js CHANGED
@@ -183,6 +183,7 @@ function makeHpke(hpkeAlg) {
183
183
  ;
184
184
  const nSecret = 32 // SHA-256 output length
185
185
  ;
186
+ // AEAD parameters — dispatch on the suite's AEAD algorithm
186
187
  let aeadKeySize;
187
188
  let createAEADCipher;
188
189
  switch(hpkeAlg.aead){
@@ -3,7 +3,7 @@ import type { VerifiedLedgerEntry } from './ledger.js';
3
3
  import { type RosterState } from './roster.js';
4
4
  /**
5
5
  * The outcome of folding an envelope's control entries. On accept: the candidate
6
- * roster (base ∪ this envelope's group.role entries) and the non-group entries to
6
+ * roster (base ∪ this envelope's kumiai.role entries) and the non-group entries to
7
7
  * surface to the consumer, in envelope order. On reject: a reason and the offending
8
8
  * entry id. A rejection is a value — the caller turns it into a commit rejection.
9
9
  */
@@ -16,6 +16,7 @@ export type EnvelopeFoldResult = {
16
16
  reason: string;
17
17
  entryID: string;
18
18
  };
19
+ export declare const GROUP_TYPE_PREFIX = "kumiai.";
19
20
  /**
20
21
  * Fold an envelope's verified entries against a base roster, enforcing that every
21
22
  * entry is admin-authored in state-so-far. Pure, never throws.
@@ -27,9 +28,9 @@ export type EnvelopeFoldResult = {
27
28
  *
28
29
  * One pass, one rule. `baseRoster` is the state folded from the ledger the handle
29
30
  * already holds; this reasons only about *this* envelope's new entries, using it as
30
- * the starting state-so-far and mutating a copy as `group.role` entries apply. Every
31
+ * the starting state-so-far and mutating a copy as `kumiai.role` entries apply. Every
31
32
  * entry's issuer must be an admin at its own position — the universal invariant that
32
- * subsumes `group.role`'s own authority rule. State-so-far, not a pre-commit
33
+ * subsumes `kumiai.role`'s own authority rule. State-so-far, not a pre-commit
33
34
  * snapshot, so an envelope of `[promote Bob, entry-issued-by-Bob]` is accepted.
34
35
  */
35
36
  export declare function foldEnvelope(baseRoster: RosterState, entries: Array<FoldInput>, groupID: string): EnvelopeFoldResult;
@@ -1,5 +1,5 @@
1
1
  import { adminCount, ROLE_ENTRY_TYPE, roleReducer } from './roster.js';
2
- const GROUP_TYPE_PREFIX = 'group.';
2
+ export const GROUP_TYPE_PREFIX = 'kumiai.';
3
3
  function isRoleValue(value) {
4
4
  return value === 'admin' || value === 'member';
5
5
  }
@@ -14,9 +14,9 @@ function isRoleValue(value) {
14
14
  *
15
15
  * One pass, one rule. `baseRoster` is the state folded from the ledger the handle
16
16
  * already holds; this reasons only about *this* envelope's new entries, using it as
17
- * the starting state-so-far and mutating a copy as `group.role` entries apply. Every
17
+ * the starting state-so-far and mutating a copy as `kumiai.role` entries apply. Every
18
18
  * entry's issuer must be an admin at its own position — the universal invariant that
19
- * subsumes `group.role`'s own authority rule. State-so-far, not a pre-commit
19
+ * subsumes `kumiai.role`'s own authority rule. State-so-far, not a pre-commit
20
20
  * snapshot, so an envelope of `[promote Bob, entry-issued-by-Bob]` is accepted.
21
21
  */ export function foldEnvelope(baseRoster, entries, groupID) {
22
22
  let workingRoster = {
@@ -67,11 +67,11 @@ function isRoleValue(value) {
67
67
  }
68
68
  continue;
69
69
  }
70
- // `group.*` is reserved for @kumiai/mls; an unknown one fails closed.
70
+ // `kumiai.*` is reserved for @kumiai/mls; an unknown one fails closed.
71
71
  if (entry.type.startsWith(GROUP_TYPE_PREFIX)) {
72
72
  return {
73
73
  ok: false,
74
- reason: 'unknown group.* type',
74
+ reason: 'unknown kumiai.* type',
75
75
  entryID
76
76
  };
77
77
  }
@@ -9,6 +9,7 @@ export function makeMLSCredential(identity) {
9
9
  throw new Error('peer:4 identity is missing longForm; only identities from createIdentity can be used as MLS members');
10
10
  }
11
11
  const payload = {
12
+ v: 1,
12
13
  id
13
14
  };
14
15
  if (isPeer) {
@@ -43,7 +43,7 @@ export type GroupHandleParams = {
43
43
  commitPolicy?: IncomingMessageCallback;
44
44
  /** Fetch control-ledger entry bodies the local ledger lacks (commit pre-pass). */
45
45
  resolveLedgerEntries?: (ids: Array<string>) => Promise<Array<string>>;
46
- /** Surface an accepted commit's notarized non-`group.role` entries to the consumer. */
46
+ /** Surface an accepted commit's notarized non-`kumiai.role` entries to the consumer. */
47
47
  onLedgerEntries?: (entries: Array<VerifiedLedgerEntry>) => void;
48
48
  };
49
49
  /** Mutable wrapper around MLS group state + Enkaku credential. */
@@ -143,8 +143,46 @@ export declare class GroupHandle {
143
143
  * order. Leaves whose credential identity fails to parse are skipped (like
144
144
  * findMemberLeafIndex). Reflects current #state — call before and after
145
145
  * processMessage to diff a commit's membership change.
146
+ *
147
+ * The diff sees MEMBERSHIP, and only membership: an Add, a Remove, or both in
148
+ * one commit (compare as a set — a count misses that last case). It does NOT
149
+ * see an external-commit REJOIN by a member the group still holds. That member
150
+ * keeps its id, so the id set is unchanged; and its leaf index is unchanged
151
+ * too, because a resync blanks the member's old leaf and the new leaf then
152
+ * takes the leftmost blank — the one just blanked (RFC 9420 §12.4.3.2). No
153
+ * field of this result moves, and no before/after diff of it can be made to.
154
+ * A caller that must detect a rejoin reads the COMMIT instead — an external
155
+ * commit is structurally one: a public message from a non-member carrying a
156
+ * commit, recognizable from its own bytes before it is applied, and carrying
157
+ * its committer's id in its own UpdatePath leaf. That is the read
158
+ * {@link readCommitHeader} already makes internally to resolve such a
159
+ * committer, and it does not surface the fact today.
146
160
  */
147
161
  listMembers(): Array<GroupMember>;
162
+ /**
163
+ * The MLS exporter (RFC 9420 §8.5): a secret derived from THIS EPOCH's exporter secret,
164
+ * a label and a context. Every member at the epoch derives the same bytes; a member at
165
+ * any other epoch derives different ones, and cannot reach this epoch's from what it holds.
166
+ *
167
+ * That per-epoch property is the point, and it is the only thing that cuts a removed member
168
+ * off from anything keyed on it. A removed member keeps every exporter secret it ever held
169
+ * and every value it ever derived, and epoch numbers are a counter it can enumerate — so a
170
+ * consumer deriving a rotating name (an app-lane topic, say) must feed it from HERE and never
171
+ * from a lifelong group secret, which would rotate onto a name the removed member walks
172
+ * straight back onto.
173
+ *
174
+ * Non-mutating and consumes no ratchet key: the exporter secret is epoch-level. A handle a
175
+ * commit has superseded exports its own pre-commit epoch's secret, which is a feature — a
176
+ * reader opening a retained frame needs the secret of the epoch that frame was sealed at.
177
+ *
178
+ * DELIBERATELY NOT MUTEX-WRAPPED, unlike its neighbours, and two things depend on that. A
179
+ * consumer resolving a commit's ledger entries is called from INSIDE `processMessage`, which
180
+ * holds the mutex — so taking it here would deadlock every commit-apply. And `#state` is
181
+ * replaced only after resolution returns, so a read from in there sees the PRE-commit epoch's
182
+ * exporter secret, which is the epoch the blob being opened was sealed under. Both are silent
183
+ * consequences of this method's plainness; wrapping it "for consistency" breaks both.
184
+ */
185
+ exportSecret(label: string, context: Uint8Array, length?: number): Promise<Uint8Array>;
148
186
  /**
149
187
  * Encrypt an application message for the group at this handle's current epoch,
150
188
  * returning framed wire bytes. A handle a commit has already superseded (see
@@ -153,6 +191,74 @@ export declare class GroupHandle {
153
191
  * `newGroup` and encrypt on that.
154
192
  */
155
193
  encrypt(plaintext: Uint8Array): Promise<Uint8Array>;
194
+ /**
195
+ * Open an application message sealed for the group and recover WHO SENT IT — the
196
+ * counterpart to {@link encrypt}, and the read half of the group's application lane.
197
+ *
198
+ * Throws for bytes this handle cannot open, which for an application message means
199
+ * ANY epoch but its own: MLS ratchets forward, so a frame sealed below this handle's
200
+ * epoch is gone and one sealed above it has not arrived yet. That is ordinary control
201
+ * flow for a caller walking a retained log full of frames from epochs it does not hold
202
+ * — it is how a frame says "not mine" — and such a caller must not read the throw as
203
+ * corruption. Use {@link readMessageEpoch} to tell those two cases apart before trying.
204
+ *
205
+ * WHY THE SENDER IS AUTHENTICATED and not merely claimed: the leaf index comes from the
206
+ * message's sender-data, encrypted under this epoch's sender-data secret, and the
207
+ * message body then opens only under the ratchet key derived at THAT leaf. A frame
208
+ * naming a leaf it was not sealed at does not open, so a sender that survives to be
209
+ * returned is one the AEAD has vouched for. The leaf is resolved to a DID against this
210
+ * handle's own ratchet tree, never from anything the frame carries.
211
+ *
212
+ * `senderDID` is absent only when the authenticated leaf holds no parsable credential —
213
+ * absent means "I cannot name the author", never "there is no author".
214
+ *
215
+ * ts-mls's own `processMessage` returns an application message's plaintext WITHOUT any
216
+ * sender, which is why this exists rather than delegating.
217
+ */
218
+ decrypt(message: Uint8Array): Promise<{
219
+ payload: Uint8Array;
220
+ senderDID?: string;
221
+ }>;
222
+ /**
223
+ * Read what a Commit says about itself against this handle, WITHOUT advancing state.
224
+ *
225
+ * **`null` means "these bytes are not a Commit" and nothing else.** It does not mean "a
226
+ * Commit I could not read": callers file `null` as poison and step over it, so answering it
227
+ * for a Commit this handle merely cannot authenticate would make a reader treat every commit
228
+ * framed away from its own epoch as garbage — including the ones that say it fell behind.
229
+ *
230
+ * The two facts the header carries are NOT equally available, and the return type says so:
231
+ * - `epoch` is in the message's CLEARTEXT ({@link readMessageEpoch}). Keyless, so it is
232
+ * readable for a Commit framed at any epoch — and unauthenticated, so it is the
233
+ * publisher's word and may only be used to decide what to try.
234
+ * - `committerDID` needs the epoch's sender-data secret. A member commit (PrivateMessage)
235
+ * has its committer encrypted under it: decrypt to the sender leaf index and resolve that
236
+ * against this handle's ratchet tree — the same leaf->DID the commit policy sees as
237
+ * `didOfLeaf(senderLeafIndex)`. Both the secret and the tree are THIS epoch's, so the
238
+ * committer resolves only for a Commit framed where this handle stands, and is ABSENT
239
+ * otherwise. Absent is "I cannot vouch for the author", never "there is no author": a
240
+ * caller must not substitute an unauthenticated one.
241
+ *
242
+ * An external commit needs no epoch secret and no tree lookup — it is a public message and its
243
+ * committer's DID rides its own UpdatePath leaf (see {@link readExternalCommit}), which is also
244
+ * what makes it recognizable as external. It is NOT exempt from authentication. The credential
245
+ * carrying that DID is a plain field, so it is returned only once the commit's own self-signed
246
+ * signature verifies, and it is ABSENT otherwise — the same rule the member path follows, for
247
+ * the same reason. Verifiable only at this handle's own epoch, since MLS binds the GroupContext
248
+ * into what an external commit signs; a commit framed elsewhere reports no committer.
249
+ *
250
+ * `external: true` is reported either way: it is read from the wireformat and sender type, both
251
+ * cleartext, so it is as available as the epoch and says nothing about who authored the frame.
252
+ *
253
+ * Runs on the handle mutex so the epoch secret, tree, and epoch are one snapshot against a
254
+ * concurrent processMessage. Non-mutating: sender-data decrypt is epoch-level and consumes
255
+ * no per-message key. Async only because the KDF and AEAD are.
256
+ */
257
+ readCommitHeader(commit: Uint8Array): Promise<{
258
+ epoch: bigint;
259
+ committerDID?: string;
260
+ external?: boolean;
261
+ } | null>;
156
262
  /**
157
263
  * Process a received MLS message (Commit, Proposal, or application). Accepts
158
264
  * wire-form bytes (preferred, e.g. from commitInvite/removeMember) or a pre-decoded