@kumiai/mls 0.2.0 → 0.3.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.
@@ -0,0 +1,85 @@
1
+ import { createGroupInfoWithExternalPubAndRatchetTree, decode, encode, mlsMessageDecoder, mlsMessageEncoder, protocolVersions, wireformats } from 'ts-mls';
2
+ import { GROUP_ANCHOR_EXTENSION_TYPE } from './anchor.js';
3
+ /**
4
+ * Read the MLS epoch from a framed message's cleartext header without decrypting.
5
+ * Advisory only — the header epoch is unauthenticated; use it to drop stale / buffer
6
+ * future messages before the authenticated processMessage. Returns undefined for
7
+ * non-message or undecodable bytes.
8
+ *
9
+ * Total by contract (a safe pre-filter over untrusted Delivery Service bytes): never
10
+ * throws. ts-mls `decode` throws on some malformed inputs (e.g. oversized); that is
11
+ * caught and treated as "not a message".
12
+ */ export function readMessageEpoch(bytes) {
13
+ const message = (()=>{
14
+ try {
15
+ return decode(mlsMessageDecoder, bytes);
16
+ } catch {
17
+ return undefined;
18
+ }
19
+ })();
20
+ if (message == null) return undefined;
21
+ if (message.wireformat === wireformats.mls_private_message) {
22
+ return message.privateMessage.epoch;
23
+ }
24
+ if (message.wireformat === wireformats.mls_public_message) {
25
+ return message.publicMessage.content.epoch;
26
+ }
27
+ return undefined;
28
+ }
29
+ /**
30
+ * Read a framed MLSMessage(GroupInfo)'s epoch and ratchet-tree hash without joining
31
+ * or mutating state. Used to confirm an external-resync Commit was canonically
32
+ * accepted: compare the returned (epoch, treeHash) against the rejoiner's own
33
+ * post-commit state. Equal ⟹ this device's Commit won the epoch; unequal ⟹ another
34
+ * won and the rejoin must retry.
35
+ *
36
+ * Structural read only — does NOT verify the GroupInfo signature; the caller obtains
37
+ * the bytes over the group's authorized channel. Unlike readMessageEpoch, this THROWS
38
+ * on malformed input: an already-trusted malformed GroupInfo is a programming error.
39
+ */ export function inspectGroupInfo(groupInfoBytes) {
40
+ const message = decode(mlsMessageDecoder, groupInfoBytes);
41
+ if (message == null) {
42
+ throw new Error('Invalid groupInfo: failed to decode MLSMessage');
43
+ }
44
+ if (message.wireformat !== wireformats.mls_group_info) {
45
+ throw new Error(`Invalid groupInfo: expected wireformat mls_group_info, got ${String(message.wireformat)}`);
46
+ }
47
+ const { groupContext } = message.groupInfo;
48
+ return {
49
+ epoch: groupContext.epoch,
50
+ treeHash: groupContext.treeHash
51
+ };
52
+ }
53
+ /**
54
+ * Read a framed MLSMessage(GroupInfo)'s group-identifying bindings without joining:
55
+ * the group id its GroupContext names and the raw genesis-anchor extension bytes. A
56
+ * recovering peer compares both against the group it believes it is healing, so a
57
+ * GroupInfo for another group or with a different anchor is refused before it can
58
+ * steer an external join. Structural read only; does not verify the signature. Throws
59
+ * on malformed input, like {@link inspectGroupInfo}.
60
+ */ export function readGroupInfoBinding(groupInfoBytes) {
61
+ const message = decode(mlsMessageDecoder, groupInfoBytes);
62
+ if (message == null) {
63
+ throw new Error('Invalid groupInfo: failed to decode MLSMessage');
64
+ }
65
+ if (message.wireformat !== wireformats.mls_group_info) {
66
+ throw new Error(`Invalid groupInfo: expected wireformat mls_group_info, got ${String(message.wireformat)}`);
67
+ }
68
+ const { groupContext } = message.groupInfo;
69
+ const anchor = groupContext.extensions.find((ext)=>ext.extensionType === GROUP_ANCHOR_EXTENSION_TYPE);
70
+ return {
71
+ groupID: new TextDecoder().decode(groupContext.groupId),
72
+ anchorExtensionData: anchor?.extensionData instanceof Uint8Array ? anchor.extensionData : null
73
+ };
74
+ }
75
+ export async function exportGroupInfo(params) {
76
+ const groupInfo = await createGroupInfoWithExternalPubAndRatchetTree(params.group.state, [], params.group.context.cipherSuite);
77
+ const framed = {
78
+ version: protocolVersions.mls10,
79
+ wireformat: wireformats.mls_group_info,
80
+ groupInfo
81
+ };
82
+ return {
83
+ groupInfo: encode(mlsMessageEncoder, framed)
84
+ };
85
+ }
@@ -0,0 +1,25 @@
1
+ import { type GroupHandle } from './group-handle.js';
2
+ export type RemoveMemberResult = {
3
+ /** Framed MLSMessage bytes. Broadcast to existing members via the DS. */
4
+ commitMessage: Uint8Array;
5
+ newGroup: GroupHandle;
6
+ /** Post-commit epoch (== newGroup.epoch). NOT the commit's wire-header epoch: a
7
+ * commit is framed at the sender's pre-commit epoch (== epoch - 1n), which is what
8
+ * receivers compare against their own handle.epoch for ordering (see
9
+ * readMessageEpoch). */
10
+ epoch: bigint;
11
+ };
12
+ /**
13
+ * Remove a member. Advances the epoch and rotates keys.
14
+ *
15
+ * Removal must demote: a receiver rejects a Remove whose target is still `admin` in
16
+ * the folded roster. So removing an admin means riding the demotion entry on the same
17
+ * commit — pass it as `ledgerEntries`. The caller signs the entry; this only carries it.
18
+ *
19
+ * Reads `group` and returns a NEW derived handle (`newGroup`); it never advances
20
+ * `group`. The caller MUST adopt `newGroup` — never reuse `group` — before the next
21
+ * commit: two commits from the same source handle both frame at its epoch and diverge.
22
+ * The mutex only serializes concurrent calls against one handle; it does not make a
23
+ * second commit from a superseded handle safe.
24
+ */
25
+ export declare function removeMember(group: GroupHandle, leafIndex: number, ledgerEntries?: Array<string>): Promise<RemoveMemberResult>;
@@ -0,0 +1,36 @@
1
+ import { defaultProposalTypes, encode, mlsMessageEncoder } from 'ts-mls';
2
+ import { commitWithEntries } from './group-commit.js';
3
+ import { deriveGroup, mutexFor } from './group-handle.js';
4
+ /**
5
+ * Remove a member. Advances the epoch and rotates keys.
6
+ *
7
+ * Removal must demote: a receiver rejects a Remove whose target is still `admin` in
8
+ * the folded roster. So removing an admin means riding the demotion entry on the same
9
+ * commit — pass it as `ledgerEntries`. The caller signs the entry; this only carries it.
10
+ *
11
+ * Reads `group` and returns a NEW derived handle (`newGroup`); it never advances
12
+ * `group`. The caller MUST adopt `newGroup` — never reuse `group` — before the next
13
+ * commit: two commits from the same source handle both frame at its epoch and diverge.
14
+ * The mutex only serializes concurrent calls against one handle; it does not make a
15
+ * second commit from a superseded handle safe.
16
+ */ export async function removeMember(group, leafIndex, ledgerEntries) {
17
+ return mutexFor(group).run(async ()=>{
18
+ const removeProposal = {
19
+ proposalType: defaultProposalTypes.remove,
20
+ remove: {
21
+ removed: leafIndex
22
+ }
23
+ };
24
+ const enacted = ledgerEntries ?? [];
25
+ const result = await commitWithEntries(group, [
26
+ removeProposal
27
+ ], enacted);
28
+ const newGroup = deriveGroup(group, result.newState);
29
+ await newGroup.applyLedgerEntries(enacted);
30
+ return {
31
+ commitMessage: encode(mlsMessageEncoder, result.commit),
32
+ newGroup,
33
+ epoch: newGroup.epoch
34
+ };
35
+ });
36
+ }
@@ -0,0 +1,67 @@
1
+ import { type OwnIdentity } from '@kokuin/token';
2
+ import type { MemberCredential } from './credential.js';
3
+ import { GroupHandle } from './group-handle.js';
4
+ import type { GroupOptions, Invite, KeyPackageBundle } from './types.js';
5
+ export type ProcessWelcomeResult = {
6
+ group: GroupHandle;
7
+ credential: MemberCredential;
8
+ };
9
+ export type ProcessWelcomeParams = {
10
+ identity: OwnIdentity;
11
+ invite: Invite;
12
+ /** Wire-form framed MLSMessage(Welcome) bytes (preferred), or a pre-decoded
13
+ * ts-mls Welcome object (legacy). `Uint8Array | unknown` collapses to
14
+ * `unknown` in TypeScript; the runtime `instanceof` check selects the path. */
15
+ welcome: Uint8Array | unknown;
16
+ keyPackageBundle: KeyPackageBundle;
17
+ ratchetTree?: unknown;
18
+ options?: GroupOptions;
19
+ };
20
+ /**
21
+ * Process a Welcome message to join a group.
22
+ */
23
+ export declare function processWelcome(params: ProcessWelcomeParams): Promise<ProcessWelcomeResult>;
24
+ export type ProcessWelcomeOnceParams = ProcessWelcomeParams & {
25
+ /** The group ids this member already holds a handle for. */
26
+ joined: Iterable<string>;
27
+ };
28
+ /**
29
+ * Join from a Welcome, unless this member already joined that group — then return
30
+ * `null` and keep the existing handle.
31
+ *
32
+ * A Welcome is delivered AT LEAST ONCE by design (a sender re-delivers on a crash
33
+ * between journaling its commit and delivering, or it would strand an invitee never
34
+ * told it was added), so the receiver must absorb the repeat. {@link processWelcome}
35
+ * does NOT — it is a pure function with no registry of joined groups, so a repeat
36
+ * succeeds silently and hands back a second handle frozen at the join epoch.
37
+ * **Adopting that handle rolls the member back: every member added since is gone from
38
+ * its roster, it can no longer read traffic, and nothing raises an error.** This
39
+ * function exists to remove that hazard.
40
+ *
41
+ * The check cannot be hoisted above `processWelcome`: a Welcome's group id is
42
+ * encrypted to the joiner's key, so there is nothing to check until the handle exists.
43
+ * So this joins, compares the resulting group id against `joined`, and drops the stale
44
+ * handle (a local falling out of scope — nothing zeroizes its key material) rather than
45
+ * returning it. Dedup keys on the group id alone; a Welcome for an id absent from
46
+ * `joined` is an ordinary first join.
47
+ */
48
+ export declare function processWelcomeOnce(params: ProcessWelcomeOnceParams): Promise<ProcessWelcomeResult | null>;
49
+ export type JoinGroupExternalParams = {
50
+ identity: OwnIdentity;
51
+ /** Framed MLSMessage(GroupInfo) bytes from exportGroupInfo. */
52
+ groupInfo: Uint8Array;
53
+ /** Caller's cached credential (from prior processWelcome). Reused as-is,
54
+ * not re-validated. */
55
+ credential: MemberCredential;
56
+ /** Stale-recovery only: atomically removes prior leaf for same identity. */
57
+ resync: true;
58
+ options?: GroupOptions;
59
+ authenticatedData?: Uint8Array;
60
+ };
61
+ export type JoinGroupExternalResult = {
62
+ /** Framed MLSMessage(PublicMessage) bytes. Broadcast to existing members. */
63
+ commitMessage: Uint8Array;
64
+ /** New GroupHandle at post-commit epoch. */
65
+ group: GroupHandle;
66
+ };
67
+ export declare function joinGroupExternal(params: JoinGroupExternalParams): Promise<JoinGroupExternalResult>;
@@ -0,0 +1,178 @@
1
+ import { createInMemoryDIDCache, normalizeDID } from '@kokuin/token';
2
+ import { decode, encode, generateKeyPackageWithKey, joinGroup as mlsJoinGroup, joinGroupExternal as mlsJoinGroupExternal, mlsMessageDecoder, mlsMessageEncoder, protocolVersions, wireformats } from 'ts-mls';
3
+ import { sanitizeRatchetTree } from './codec.js';
4
+ import { buildLeafCapabilities, resolveMlsContext } from './group-context.js';
5
+ import { makeMLSCredential } from './group-credential.js';
6
+ import { GroupHandle } from './group-handle.js';
7
+ import { assertHeadMatches, computeHead, readLedgerHead } from './head.js';
8
+ import { ledgerEntryDigest, verifyLedgerEntry } from './ledger.js';
9
+ import { ROLE_ENTRY_TYPE } from './roster.js';
10
+ /**
11
+ * Process a Welcome message to join a group.
12
+ */ export async function processWelcome(params) {
13
+ const { identity, invite, welcome, keyPackageBundle, ratchetTree, options } = params;
14
+ const cache = options?.cache ?? createInMemoryDIDCache();
15
+ const context = await resolveMlsContext(options);
16
+ // A Welcome is only this member's when the invite carries a role entry naming
17
+ // them: an invite minted for someone else is not an invitation to join.
18
+ const selfDID = normalizeDID(identity.id);
19
+ let namesSelf = false;
20
+ for (const token of invite.ledgerEntries){
21
+ const verified = await verifyLedgerEntry(token);
22
+ if (verified != null && verified.entry.type === ROLE_ENTRY_TYPE && verified.entry.groupID === invite.groupID && normalizeDID(verified.entry.subject) === selfDID) {
23
+ namesSelf = true;
24
+ break;
25
+ }
26
+ }
27
+ if (!namesSelf) {
28
+ throw new Error('processWelcome: the invite carries no role entry naming this identity');
29
+ }
30
+ let resolvedWelcome = welcome;
31
+ if (welcome instanceof Uint8Array) {
32
+ const decoded = decode(mlsMessageDecoder, welcome);
33
+ if (decoded == null || decoded.wireformat !== wireformats.mls_welcome) {
34
+ throw new Error('processWelcome: expected a framed MLSMessage(Welcome)');
35
+ }
36
+ resolvedWelcome = decoded.welcome;
37
+ }
38
+ const sanitizedTree = Array.isArray(ratchetTree) ? sanitizeRatchetTree(ratchetTree) : ratchetTree;
39
+ const state = await mlsJoinGroup({
40
+ context,
41
+ welcome: resolvedWelcome,
42
+ keyPackage: keyPackageBundle.publicPackage,
43
+ privateKeys: keyPackageBundle.privatePackage,
44
+ ...sanitizedTree != null && {
45
+ ratchetTree: sanitizedTree
46
+ }
47
+ });
48
+ const credential = {
49
+ id: identity.id,
50
+ groupID: invite.groupID
51
+ };
52
+ const group = new GroupHandle({
53
+ state,
54
+ credential,
55
+ context,
56
+ cache,
57
+ resolver: options?.resolver,
58
+ commitPolicy: options?.commitPolicy,
59
+ resolveLedgerEntries: options?.resolveLedgerEntries,
60
+ onLedgerEntries: options?.onLedgerEntries
61
+ });
62
+ // The head authenticated in the joined GroupContext is the fold from genesis over the
63
+ // group's entries, in order. Recompute it over the inviter's supplied entries: an
64
+ // omitted, reordered, or truncated list cannot reproduce it. Checked before folding,
65
+ // so an incomplete ledger never reaches the roster.
66
+ const authenticated = readLedgerHead(group);
67
+ if (authenticated == null) {
68
+ throw new Error('processWelcome: the group has no ledger head extension');
69
+ }
70
+ assertHeadMatches(authenticated.head, computeHead(invite.groupID, invite.ledgerEntries.map(ledgerEntryDigest)));
71
+ // Fold the invite's entries: the roster is seeded from the anchor and the fold grants
72
+ // authority only to an admin-so-far, so a member-signed entry cannot promote anyone
73
+ // even though applyLedgerEntries itself is the permissive primitive.
74
+ await group.applyLedgerEntries(invite.ledgerEntries);
75
+ return {
76
+ group,
77
+ credential
78
+ };
79
+ }
80
+ /**
81
+ * Join from a Welcome, unless this member already joined that group — then return
82
+ * `null` and keep the existing handle.
83
+ *
84
+ * A Welcome is delivered AT LEAST ONCE by design (a sender re-delivers on a crash
85
+ * between journaling its commit and delivering, or it would strand an invitee never
86
+ * told it was added), so the receiver must absorb the repeat. {@link processWelcome}
87
+ * does NOT — it is a pure function with no registry of joined groups, so a repeat
88
+ * succeeds silently and hands back a second handle frozen at the join epoch.
89
+ * **Adopting that handle rolls the member back: every member added since is gone from
90
+ * its roster, it can no longer read traffic, and nothing raises an error.** This
91
+ * function exists to remove that hazard.
92
+ *
93
+ * The check cannot be hoisted above `processWelcome`: a Welcome's group id is
94
+ * encrypted to the joiner's key, so there is nothing to check until the handle exists.
95
+ * So this joins, compares the resulting group id against `joined`, and drops the stale
96
+ * handle (a local falling out of scope — nothing zeroizes its key material) rather than
97
+ * returning it. Dedup keys on the group id alone; a Welcome for an id absent from
98
+ * `joined` is an ordinary first join.
99
+ */ export async function processWelcomeOnce(params) {
100
+ const { joined, ...welcomeParams } = params;
101
+ const held = new Set(joined);
102
+ const result = await processWelcome(welcomeParams);
103
+ if (held.has(result.group.groupID)) {
104
+ return null;
105
+ }
106
+ return result;
107
+ }
108
+ export async function joinGroupExternal(params) {
109
+ const { identity, groupInfo: groupInfoBytes, credential, resync, options, authenticatedData } = params;
110
+ // Resync replaces the caller's own prior leaf, so the rejoining identity must match
111
+ // the presented credential. A friendly precheck, not the security boundary: on a
112
+ // mismatch ts-mls rejects the external commit downstream anyway. Eviction
113
+ // completeness rests on ts-mls requiring a matching prior leaf in the resynced tree,
114
+ // which a removed member no longer has.
115
+ if (normalizeDID(identity.id) !== normalizeDID(credential.id)) {
116
+ throw new Error(`joinGroupExternal: identity.id (${identity.id}) must match credential.id (${credential.id}) for resync`);
117
+ }
118
+ const cache = options?.cache ?? createInMemoryDIDCache();
119
+ const context = await resolveMlsContext(options);
120
+ const message = decode(mlsMessageDecoder, groupInfoBytes);
121
+ if (message == null) {
122
+ throw new Error('Invalid groupInfo: failed to decode MLSMessage');
123
+ }
124
+ if (message.wireformat !== wireformats.mls_group_info) {
125
+ throw new Error(`Invalid groupInfo: expected wireformat mls_group_info, got ${String(message.wireformat)}`);
126
+ }
127
+ // Discriminated-union narrow via the literal wireformat tag — no cast needed.
128
+ const { groupInfo } = message;
129
+ // A resync must target the group this credential names. The returned handle reports
130
+ // `credential.groupID` whatever group it joins, so without this a caller steered onto
131
+ // a GroupInfo for another group would hold a handle that lies about its identity.
132
+ const offeredGroupID = new TextDecoder().decode(groupInfo.groupContext.groupId);
133
+ if (offeredGroupID !== credential.groupID) {
134
+ throw new Error(`joinGroupExternal: groupInfo names group ${offeredGroupID}, not credential.groupID (${credential.groupID})`);
135
+ }
136
+ // The rejoining leaf must advertise every GroupContext extension the group uses, or
137
+ // ts-mls rejects the external join. Derive them from the GroupInfo being resynced
138
+ // against, honoring an explicit capabilities override.
139
+ const keyPackage = await generateKeyPackageWithKey({
140
+ credential: makeMLSCredential(identity),
141
+ signatureKeyPair: {
142
+ signKey: identity.privateKey,
143
+ publicKey: identity.publicKey
144
+ },
145
+ cipherSuite: context.cipherSuite,
146
+ capabilities: buildLeafCapabilities(groupInfo.groupContext.extensions, options?.capabilities)
147
+ });
148
+ const { publicMessage, newState } = await mlsJoinGroupExternal({
149
+ context,
150
+ groupInfo,
151
+ keyPackage: keyPackage.publicPackage,
152
+ privateKeys: keyPackage.privatePackage,
153
+ resync,
154
+ ...authenticatedData != null && {
155
+ authenticatedData
156
+ }
157
+ });
158
+ const framedCommit = {
159
+ version: protocolVersions.mls10,
160
+ wireformat: wireformats.mls_public_message,
161
+ publicMessage
162
+ };
163
+ const commitMessage = encode(mlsMessageEncoder, framedCommit);
164
+ const group = new GroupHandle({
165
+ state: newState,
166
+ credential,
167
+ context,
168
+ cache,
169
+ resolver: options?.resolver,
170
+ commitPolicy: options?.commitPolicy,
171
+ resolveLedgerEntries: options?.resolveLedgerEntries,
172
+ onLedgerEntries: options?.onLedgerEntries
173
+ });
174
+ return {
175
+ commitMessage,
176
+ group
177
+ };
178
+ }