@kumiai/mls-rpc 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 ADDED
@@ -0,0 +1,101 @@
1
+ # @kumiai/mls-rpc
2
+
3
+ The two consumer ports of `@kumiai/rpc` — `GroupCrypto` and `GroupMLS` — implemented over a live
4
+ `@kumiai/mls` `GroupHandle`. This is what a host wires when it wants group RPC over real MLS.
5
+
6
+ ## Why it is its own package
7
+
8
+ `@kumiai/rpc` does not depend on `@kumiai/mls` and must not: it owns transport and orchestration,
9
+ and the two ports exist precisely so the consumer supplies the crypto half. `@kumiai/mls` does not
10
+ depend on `@kumiai/rpc` either — a crypto core that imported an RPC package's types would invert
11
+ the stack. So the implementation of one package's ports over the other's handle belongs above both.
12
+
13
+ It is a real implementation, not a fixture. Until it existed, both ports had exactly one
14
+ implementation apiece — a test double — and nothing had ever run them against MLS. This is also the
15
+ only place a compiler checks the two contracts against each other, and the only package that may
16
+ depend on both.
17
+
18
+ ## Exports
19
+
20
+ - `createGroupCrypto({ handle, entryLabel? })` — `GroupCrypto` over a live handle.
21
+ - `createGroupMLS({ handle, adopt, identity, entrySlot, persist? })` — `GroupMLS` over the same.
22
+ - `createLedgerEntrySlot()` — the per-commit ledger-entry resolver seam (see below).
23
+ - `RECOVERY_LABEL` — the exporter label `exportRecoverySecret` derives under.
24
+
25
+ ## The handle is a function, not a value
26
+
27
+ Both factories take `handle: () => GroupHandle`, and that is not a convenience. A peer's handle is
28
+ replaced wholesale when it adopts a commit it authored, or rejoins by external commit; a port
29
+ closing over the handle it was constructed with would seal at a dead epoch forever. `createGroupMLS`
30
+ takes `adopt` as the one place that replacement happens.
31
+
32
+ For a *received* commit there is nothing to adopt: ts-mls's `processMessage` advances the handle in
33
+ place. A host that treated every commit as adopt-later would double-apply received ones.
34
+
35
+ ## `createLedgerEntrySlot` is mandatory, and must be installed where the handle is built
36
+
37
+ `GroupMLS.processCommit` is handed a `resolveLedgerEntries` scoped to **one** commit's frame — the
38
+ signed ledger-entry bodies ride that frame and nowhere else. But `GroupHandle` takes its resolver
39
+ once, in `GroupOptions`, and offers no way to change it afterwards. So the indirection has to be
40
+ installed when the group is *built*:
41
+
42
+ ```ts
43
+ import { createGroupCrypto, createGroupMLS, createLedgerEntrySlot } from '@kumiai/mls-rpc'
44
+
45
+ const entrySlot = createLedgerEntrySlot()
46
+ // Every construction site: createGroup / processWelcome / restoreGroup.
47
+ const { group } = await createGroup(identity, groupID, {
48
+ resolveLedgerEntries: entrySlot.resolve,
49
+ })
50
+
51
+ let handle = group
52
+ const crypto = createGroupCrypto({ handle: () => handle })
53
+ const mls = createGroupMLS({
54
+ handle: () => handle,
55
+ adopt: (next) => {
56
+ handle = next
57
+ },
58
+ identity,
59
+ entrySlot,
60
+ persist: async (current) => await store.save(current),
61
+ })
62
+ ```
63
+
64
+ Passing anything else means a commit resolves its entries against whatever resolver the handle
65
+ happened to be born with.
66
+
67
+ ## Two seals, one exporter
68
+
69
+ `wrap`/`unwrap` carry app traffic and are ratchet-backed: each open consumes a message key and
70
+ mutates the handle. `sealEntries`/`openEntries` carry a commit's ledger-entry blob under a key
71
+ exported from the epoch, so opening is **pure** and may run from inside the apply of the commit that
72
+ carries it — which is the only place it does run, and which the ratchet-backed pair cannot serve.
73
+ The two use different exporter labels deliberately: the topic secret names a topic and is handed to
74
+ anything that derives one, while the entry key opens the group's control-ledger bodies.
75
+
76
+ The sealed blob is `[ VERSION(1) | NONCE(24) | CIPHERTEXT ]`, XChaCha20-Poly1305. The version byte
77
+ sits inside the blob rather than in the frame header so that an unknown version fails the *open* —
78
+ survivable, the commit is filed as poison and stepped over — rather than the *decode*, which would
79
+ leave a peer stepping over frames without ever classifying one and never learning the group moved on.
80
+
81
+ ## Where this diverges from the doubles
82
+
83
+ Documented on the factories themselves; the conformance suite in `@kumiai/rpc-conformance` pins each
84
+ one. The ones a host is most likely to trip on:
85
+
86
+ - **`unwrap` opens a bounded window below the current epoch.** ts-mls retains a few epochs of key
87
+ material, so a frame sealed at epoch 3 opens against a handle carried to epoch 4, and the same read
88
+ six transitions later is refused. The window is spent by epoch *transitions*, not by time, so
89
+ nothing may depend on it — and `@kumiai/rpc` does not. An implementation opening strictly at the
90
+ current epoch is a correct implementation of the port.
91
+ - **`exportSecret` is one-way.** The fake XORs the epoch into a fixed base, so any member holding one
92
+ epoch's bytes computes every other's. This exports from the epoch's exporter secret, which a
93
+ removed member cannot reach forward from. That difference is the entire security property the
94
+ app-lane topic rests on, and it is real only here.
95
+ - **`wrap` mutates.** It consumes a per-message ratchet key, so sealing the same plaintext twice
96
+ gives different bytes.
97
+ - **`exportRecoverySecret` is derived from the group's genesis anchor, which is public.** MLS has no
98
+ lifelong group secret, so there is nothing confidential and epoch-independent to derive it from.
99
+ Anyone who has seen a `GroupInfo` for the group can compute the rendezvous topic. That is tolerable
100
+ for what the topic is for — a stranded peer, and a removed one, must both be able to name it — but
101
+ a host must put nothing on it that confidentiality depends on.
@@ -0,0 +1,49 @@
1
+ import type { GroupHandle } from '@kumiai/mls';
2
+ import type { GroupCrypto } from '@kumiai/rpc';
3
+ import { type Runtime } from '@sozai/runtime';
4
+ /**
5
+ * Label the ledger-entry seal key is exported under. Distinct from any label a caller passes to
6
+ * `exportSecret`: that names a topic secret handed to anything that derives one, while this key
7
+ * opens the group's control-ledger bodies — sharing one exported secret between the two would
8
+ * make every holder of the topic label a reader of the ledger. `exportSecret` refuses this label
9
+ * from a caller (see below).
10
+ */
11
+ export declare const ENTRY_SEAL_LABEL = "kumiai/ledger-entries/v1";
12
+ export type GroupCryptoParams = {
13
+ /**
14
+ * The peer's current handle. A function, not a value: the handle is replaced when the peer
15
+ * adopts its own commit, and closing over a fixed handle would silently seal at a dead epoch.
16
+ */
17
+ handle: () => GroupHandle;
18
+ /**
19
+ * Override the ledger-entry seal's exporter label. Members must agree on it, or they can't
20
+ * apply each other's commits.
21
+ */
22
+ entryLabel?: string;
23
+ /** Runtime providing platform primitives. Defaults to `createRuntime()`. */
24
+ runtime?: Runtime;
25
+ };
26
+ /**
27
+ * {@link GroupCrypto} over a live {@link GroupHandle} — the real port, against real MLS.
28
+ *
29
+ * ## Where this diverges from the fake in `@kumiai/rpc`'s test fixtures
30
+ *
31
+ * 1. `unwrap` refuses any epoch the handle hasn't REACHED, but opens a bounded window below it
32
+ * via ts-mls's retained key material (the fake refuses everything but its current epoch, so
33
+ * the fake is stricter — both are valid implementations of the port; group-rpc must not
34
+ * depend on the window, which is spent by epoch transitions, not time).
35
+ *
36
+ * 2. `exportSecret` is one-way; the fake's is not. The fake XORs epoch and label into a fixed
37
+ * base, so one epoch's bytes yield every other epoch's for that label. This exports from the
38
+ * MLS epoch's exporter secret, which a removed member cannot reach forward from — the entire
39
+ * security property the app-lane topic (and anything else a caller labels) rests on.
40
+ *
41
+ * 3. `wrap` mutates: it consumes a per-message ratchet key from the handle's sending chain, so
42
+ * sealing the same plaintext twice gives different bytes. The fake's `wrap` is pure — don't
43
+ * assert byte equality between two seals of the same message.
44
+ *
45
+ * 4. `frameEpoch` reads the cleartext epoch field every MLSMessage carries — the same field for
46
+ * a sealed app frame and a commit — returning `null` (never throwing) for anything ts-mls
47
+ * won't decode. The fake answers only for its own two encodings.
48
+ */
49
+ export declare function createGroupCrypto(params: GroupCryptoParams): GroupCrypto;
package/lib/crypto.js ADDED
@@ -0,0 +1,117 @@
1
+ import { readMessageEpoch } from '@kumiai/mls';
2
+ import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
3
+ import { createRuntime } from '@sozai/runtime';
4
+ /**
5
+ * Label the ledger-entry seal key is exported under. Distinct from any label a caller passes to
6
+ * `exportSecret`: that names a topic secret handed to anything that derives one, while this key
7
+ * opens the group's control-ledger bodies — sharing one exported secret between the two would
8
+ * make every holder of the topic label a reader of the ledger. `exportSecret` refuses this label
9
+ * from a caller (see below).
10
+ */ export const ENTRY_SEAL_LABEL = 'kumiai/ledger-entries/v1';
11
+ /** The exporter context. Fixed: the label already separates each consumer. */ const EXPORT_CONTEXT = new Uint8Array();
12
+ /**
13
+ * Exporter output length: 32 bytes, since XChaCha20-Poly1305 takes a 256-bit key — not the
14
+ * ciphersuite's KDF length. RFC 9420 §8.5's exporter is HKDF-Expand with a caller-chosen output
15
+ * length bound into the info field, so 32 bytes come back under any suite; deriving this from
16
+ * the suite instead would return 48 on SHA-384 and break every seal.
17
+ */ const SECRET_LENGTH = 32;
18
+ /** XChaCha20-Poly1305's nonce, carried in the clear ahead of the ciphertext. */ const ENTRY_NONCE_BYTES = 24;
19
+ /**
20
+ * Sealed blob format version, first byte, in the clear: [ VERSION(1) | NONCE(24) | CIPHERTEXT ]
21
+ *
22
+ * Inside the blob, not the frame header: an unknown blob version fails only the OPEN, which a
23
+ * peer survives (commit filed as poison, stepped over). An unknown FRAME version would fail the
24
+ * decode before the frame is ever classified, so the peer never learns the group moved past it.
25
+ * See `rpc/src/handshake.ts`.
26
+ *
27
+ * Unauthenticated by necessity — read to decide how to open, so it can't be under the seal; a
28
+ * hub that rewrites it only changes which error is reported. Buys diagnosis, not compatibility:
29
+ * no v1 peer can read a v2 blob regardless, but the failure reads as "unsupported version"
30
+ * rather than an AEAD refusal indistinguishable from a wrong epoch or a tampered frame.
31
+ */ const ENTRY_VERSION = 1;
32
+ /**
33
+ * {@link GroupCrypto} over a live {@link GroupHandle} — the real port, against real MLS.
34
+ *
35
+ * ## Where this diverges from the fake in `@kumiai/rpc`'s test fixtures
36
+ *
37
+ * 1. `unwrap` refuses any epoch the handle hasn't REACHED, but opens a bounded window below it
38
+ * via ts-mls's retained key material (the fake refuses everything but its current epoch, so
39
+ * the fake is stricter — both are valid implementations of the port; group-rpc must not
40
+ * depend on the window, which is spent by epoch transitions, not time).
41
+ *
42
+ * 2. `exportSecret` is one-way; the fake's is not. The fake XORs epoch and label into a fixed
43
+ * base, so one epoch's bytes yield every other epoch's for that label. This exports from the
44
+ * MLS epoch's exporter secret, which a removed member cannot reach forward from — the entire
45
+ * security property the app-lane topic (and anything else a caller labels) rests on.
46
+ *
47
+ * 3. `wrap` mutates: it consumes a per-message ratchet key from the handle's sending chain, so
48
+ * sealing the same plaintext twice gives different bytes. The fake's `wrap` is pure — don't
49
+ * assert byte equality between two seals of the same message.
50
+ *
51
+ * 4. `frameEpoch` reads the cleartext epoch field every MLSMessage carries — the same field for
52
+ * a sealed app frame and a commit — returning `null` (never throwing) for anything ts-mls
53
+ * won't decode. The fake answers only for its own two encodings.
54
+ */ export function createGroupCrypto(params) {
55
+ const { handle, entryLabel = ENTRY_SEAL_LABEL, runtime = createRuntime() } = params;
56
+ return {
57
+ epoch: ()=>Number(handle().epoch),
58
+ // Passed straight through to the handle's exporter, except `entryLabel`: reusing it would
59
+ // not be an independent export — it's the exact exporter call `sealEntries`/`openEntries`
60
+ // make below (same context, same `SECRET_LENGTH`), so it would hand back the ledger-entry
61
+ // seal key under another name. Refused here, loudly, rather than left to the doc alone.
62
+ exportSecret: (label, length = SECRET_LENGTH)=>{
63
+ if (label === entryLabel) {
64
+ throw new Error(`exportSecret: label '${label}' is reserved for the ledger-entry seal`);
65
+ }
66
+ return handle().exportSecret(label, EXPORT_CONTEXT, length);
67
+ },
68
+ wrap: (bytes)=>handle().encrypt(bytes),
69
+ sealEntries: async (bytes)=>{
70
+ const key = await handle().exportSecret(entryLabel, EXPORT_CONTEXT, SECRET_LENGTH);
71
+ // Random per seal: two members can frame a commit at the same epoch, and a repeated nonce
72
+ // under one key is a break. 24 bytes makes a collision unreachable without a counter.
73
+ const nonce = runtime.getRandomValues(new Uint8Array(ENTRY_NONCE_BYTES));
74
+ const ciphertext = xchacha20poly1305(key, nonce).encrypt(bytes);
75
+ const sealed = new Uint8Array(1 + nonce.length + ciphertext.length);
76
+ sealed[0] = ENTRY_VERSION;
77
+ sealed.set(nonce, 1);
78
+ sealed.set(ciphertext, 1 + nonce.length);
79
+ return sealed;
80
+ },
81
+ openEntries: async (sealed)=>{
82
+ if (sealed.length <= 1 + ENTRY_NONCE_BYTES) throw new Error('openEntries: not a sealed blob');
83
+ if (sealed[0] !== ENTRY_VERSION) {
84
+ // Distinguishable on purpose: every other failure here is an opaque AEAD refusal, and
85
+ // this lets an operator tell "unsupported version" from a wrong epoch or a tampered
86
+ // frame — the lane treats all three the same way (poison, advance, heal) regardless.
87
+ throw new Error(`openEntries: unsupported blob version ${sealed[0]}`);
88
+ }
89
+ // Pure: exporting is epoch-level and touches no handle state, so this may be called from
90
+ // inside the apply of the very commit whose blob it opens — the only place it's called from.
91
+ const key = await handle().exportSecret(entryLabel, EXPORT_CONTEXT, SECRET_LENGTH);
92
+ return xchacha20poly1305(key, sealed.subarray(1, 1 + ENTRY_NONCE_BYTES)).decrypt(sealed.subarray(1 + ENTRY_NONCE_BYTES));
93
+ },
94
+ unwrap: async (bytes)=>{
95
+ // Throws for any epoch but this handle's — ordinary control flow; the caller drops it.
96
+ const { payload, senderDID } = await handle().decrypt(bytes);
97
+ // `unwrap` requires a sender; `GroupHandle.decrypt` doesn't guarantee one — it can come
98
+ // back absent if the sender-data AEAD open fails or is malformed, no member is found at
99
+ // the authenticated leaf index, or the leaf's credential fails to parse
100
+ // (`group-handle.ts:677,867-872,536-537`, `sender-data.ts:120,123`). `@kumiai/mls` treats
101
+ // all three as "cannot name the author", never "no author" — a shape this port has no case
102
+ // for, so it's refused here rather than passed up with the field missing.
103
+ if (senderDID == null) {
104
+ throw new Error('unwrap: opened frame has no authenticated sender');
105
+ }
106
+ return {
107
+ payload,
108
+ senderDID
109
+ };
110
+ },
111
+ frameEpoch: (bytes)=>{
112
+ // Total by contract: readMessageEpoch never throws and answers without a key.
113
+ const epoch = readMessageEpoch(bytes);
114
+ return epoch == null ? null : Number(epoch);
115
+ }
116
+ };
117
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The `@kumiai/rpc` consumer ports implemented over `@kumiai/mls`.
3
+ *
4
+ * ## Why this is its own package
5
+ *
6
+ * `@kumiai/rpc` does not depend on `@kumiai/mls` and must not: it owns transport and
7
+ * orchestration, and its whole design rests on never importing MLS — `GroupCrypto` and
8
+ * `GroupMLS` exist precisely so the consumer supplies that half. `@kumiai/mls` in turn does
9
+ * not depend on `@kumiai/rpc`: it is the crypto core, and a group library that imported an
10
+ * RPC package's types would invert the stack.
11
+ *
12
+ * So the implementation of one package's ports over the other's handle belongs above both,
13
+ * and it is a real implementation rather than a fixture: it is what a host wires, and it is
14
+ * the only place where the two contracts are checked against each other by a compiler. Living
15
+ * in `rpc/src` as a default would give rpc an MLS dependency; living in `mls/src` would mean
16
+ * writing the port shape from memory with nothing to verify it against, which is the exact
17
+ * failure mode the seam already has.
18
+ *
19
+ * @module mls-rpc
20
+ */
21
+ export { createGroupCrypto, ENTRY_SEAL_LABEL, type GroupCryptoParams } from './crypto.js';
22
+ export { createGroupMLS, createLedgerEntrySlot, type GroupMLSParams, type LedgerEntrySlot, RECOVERY_LABEL, } from './mls.js';
package/lib/index.js ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The `@kumiai/rpc` consumer ports implemented over `@kumiai/mls`.
3
+ *
4
+ * ## Why this is its own package
5
+ *
6
+ * `@kumiai/rpc` does not depend on `@kumiai/mls` and must not: it owns transport and
7
+ * orchestration, and its whole design rests on never importing MLS — `GroupCrypto` and
8
+ * `GroupMLS` exist precisely so the consumer supplies that half. `@kumiai/mls` in turn does
9
+ * not depend on `@kumiai/rpc`: it is the crypto core, and a group library that imported an
10
+ * RPC package's types would invert the stack.
11
+ *
12
+ * So the implementation of one package's ports over the other's handle belongs above both,
13
+ * and it is a real implementation rather than a fixture: it is what a host wires, and it is
14
+ * the only place where the two contracts are checked against each other by a compiler. Living
15
+ * in `rpc/src` as a default would give rpc an MLS dependency; living in `mls/src` would mean
16
+ * writing the port shape from memory with nothing to verify it against, which is the exact
17
+ * failure mode the seam already has.
18
+ *
19
+ * @module mls-rpc
20
+ */ export { createGroupCrypto, ENTRY_SEAL_LABEL } from './crypto.js';
21
+ export { createGroupMLS, createLedgerEntrySlot, RECOVERY_LABEL } from './mls.js';
package/lib/mls.d.ts ADDED
@@ -0,0 +1,76 @@
1
+ import type { OwnIdentity } from '@kokuin/token';
2
+ import { type GroupHandle } from '@kumiai/mls';
3
+ import type { GroupMLS } from '@kumiai/rpc';
4
+ /**
5
+ * The label the non-rotating recovery secret is derived under. This secret is the root of
6
+ * BOTH the commit topic and the rendezvous topic — everything downstream of it depends on
7
+ * this one label.
8
+ *
9
+ * **This secret is NOT epoch-bound and must never be used for anything that a removed
10
+ * member has to be cut off from.** The port asks for exactly that — a value stable for the
11
+ * group's whole life, so a peer stranded at any epoch can still name the topic it heals on —
12
+ * and a removed member keeps it for life by design.
13
+ */
14
+ export declare const RECOVERY_LABEL = "kumiai/recovery/v1";
15
+ /**
16
+ * A per-commit ledger-entry resolver, installed at handle-construction time and swapped
17
+ * per commit.
18
+ *
19
+ * WHY THIS EXISTS, and it is a seam rather than a nicety: {@link GroupMLS.processCommit}
20
+ * is handed a `resolveLedgerEntries` scoped to ONE commit's frame — the bodies ride that
21
+ * frame and nowhere else — but `@kumiai/mls`'s `GroupHandle` takes its resolver once, in
22
+ * `GroupOptions`, and offers no way to change it afterwards. So a host cannot honour the
23
+ * per-commit contract with a plain handle: it must install this indirection when it BUILDS
24
+ * the group (createGroup / processWelcome / restoreGroup) and hand the same slot to the
25
+ * ports. Passing anything else means a commit resolves entries against whatever resolver
26
+ * the handle happened to be born with.
27
+ */
28
+ export type LedgerEntrySlot = {
29
+ /** Pass as `GroupOptions.resolveLedgerEntries` wherever the handle is built. */
30
+ resolve: (ids: Array<string>) => Promise<Array<string>>;
31
+ /** Install the resolver riding one commit's frame, for that commit's duration. */
32
+ install: (resolver: ((ids: Array<string>) => Promise<Array<string>>) | undefined) => void;
33
+ };
34
+ export declare function createLedgerEntrySlot(): LedgerEntrySlot;
35
+ export type GroupMLSParams = {
36
+ /** The handle the peer is at right now. See {@link GroupCryptoParams.handle}. */
37
+ handle: () => GroupHandle;
38
+ /** Replace the handle — the ONLY way the peer's MLS state is swapped wholesale. */
39
+ adopt: (handle: GroupHandle) => void | Promise<void>;
40
+ /** This member's signing identity: recovery requests and attestations are signed with it. */
41
+ identity: OwnIdentity;
42
+ /** The slot the handle was built with. See {@link LedgerEntrySlot}. */
43
+ entrySlot: LedgerEntrySlot;
44
+ /**
45
+ * Persist the handle's state durably. `processCommit` must be durable before it resolves,
46
+ * and this is where that happens; a host with no durable store passes a no-op and accepts
47
+ * that a crash loses the epoch.
48
+ */
49
+ persist?: (handle: GroupHandle) => void | Promise<void>;
50
+ };
51
+ /**
52
+ * {@link GroupMLS} over a live {@link GroupHandle} — the real lifecycle port.
53
+ *
54
+ * ## Where this diverges from the memory double in `@kumiai/rpc`'s fixtures
55
+ *
56
+ * 1. **`processCommit` advances the handle IN PLACE for a received commit.** ts-mls's
57
+ * `processMessage` replaces the handle's own state, so there is nothing to adopt: the
58
+ * double models a commit as a value that is adopted separately, which is only true for a
59
+ * commit this member AUTHORED (those really do produce a fresh handle, and the peer
60
+ * adopts it in `onAccepted`). A host that treated every commit as adopt-later would
61
+ * double-apply received ones.
62
+ *
63
+ * 2. **`rosterDIDs` reads the ratchet tree, so a leaf with an unparsable credential is
64
+ * simply absent** rather than present-with-a-placeholder. The double's roster is a set of
65
+ * strings it was handed.
66
+ *
67
+ * 3. **`exportRecoverySecret` is derived from the group's GENESIS ANCHOR, which is public.**
68
+ * MLS has no lifelong group secret — every key schedule secret rotates with the epoch, and
69
+ * a member who joined at epoch 5 never held epoch 0's — so there is nothing secret and
70
+ * epoch-independent to derive it from. The double returns an opaque secret handed to it,
71
+ * which reads as though the value were confidential. It is not: anyone who has seen a
72
+ * GroupInfo for this group can compute the rendezvous topic. That is tolerable for what the
73
+ * topic is for (a stranded peer must be able to name it, and so must a removed one) but a
74
+ * host must not put anything on it that confidentiality depends on.
75
+ */
76
+ export declare function createGroupMLS(params: GroupMLSParams): GroupMLS;
package/lib/mls.js ADDED
@@ -0,0 +1,209 @@
1
+ import { createRecoveryRequest, encodeGroupAnchor, joinGroupExternal, MissingLedgerEntriesError, openSealedGroupInfo, openSealedLedger, sealGroupInfo, sealLedger } from '@kumiai/mls';
2
+ const utf8 = new TextEncoder();
3
+ /**
4
+ * The label the non-rotating recovery secret is derived under. This secret is the root of
5
+ * BOTH the commit topic and the rendezvous topic — everything downstream of it depends on
6
+ * this one label.
7
+ *
8
+ * **This secret is NOT epoch-bound and must never be used for anything that a removed
9
+ * member has to be cut off from.** The port asks for exactly that — a value stable for the
10
+ * group's whole life, so a peer stranded at any epoch can still name the topic it heals on —
11
+ * and a removed member keeps it for life by design.
12
+ */ export const RECOVERY_LABEL = 'kumiai/recovery/v1';
13
+ export function createLedgerEntrySlot() {
14
+ let current;
15
+ return {
16
+ resolve: async (ids)=>{
17
+ if (current == null) {
18
+ // No frame is being applied, or the frame carried no resolver. The handle's
19
+ // pre-pass reads this as "the bodies are not reachable", which is the truth.
20
+ throw new MissingLedgerEntriesError(ids);
21
+ }
22
+ return await current(ids);
23
+ },
24
+ install: (resolver)=>{
25
+ current = resolver;
26
+ }
27
+ };
28
+ }
29
+ /**
30
+ * How long a minted recovery request's private half is kept. The port makes retention the
31
+ * implementation's problem — the lane has no release hook and drops its `requestID` on
32
+ * timeout without saying so — so this bounds it off the mint time.
33
+ */ const REQUEST_TTL_MS = 120_000;
34
+ /**
35
+ * {@link GroupMLS} over a live {@link GroupHandle} — the real lifecycle port.
36
+ *
37
+ * ## Where this diverges from the memory double in `@kumiai/rpc`'s fixtures
38
+ *
39
+ * 1. **`processCommit` advances the handle IN PLACE for a received commit.** ts-mls's
40
+ * `processMessage` replaces the handle's own state, so there is nothing to adopt: the
41
+ * double models a commit as a value that is adopted separately, which is only true for a
42
+ * commit this member AUTHORED (those really do produce a fresh handle, and the peer
43
+ * adopts it in `onAccepted`). A host that treated every commit as adopt-later would
44
+ * double-apply received ones.
45
+ *
46
+ * 2. **`rosterDIDs` reads the ratchet tree, so a leaf with an unparsable credential is
47
+ * simply absent** rather than present-with-a-placeholder. The double's roster is a set of
48
+ * strings it was handed.
49
+ *
50
+ * 3. **`exportRecoverySecret` is derived from the group's GENESIS ANCHOR, which is public.**
51
+ * MLS has no lifelong group secret — every key schedule secret rotates with the epoch, and
52
+ * a member who joined at epoch 5 never held epoch 0's — so there is nothing secret and
53
+ * epoch-independent to derive it from. The double returns an opaque secret handed to it,
54
+ * which reads as though the value were confidential. It is not: anyone who has seen a
55
+ * GroupInfo for this group can compute the rendezvous topic. That is tolerable for what the
56
+ * topic is for (a stranded peer must be able to name it, and so must a removed one) but a
57
+ * host must not put anything on it that confidentiality depends on.
58
+ */ export function createGroupMLS(params) {
59
+ const { handle, adopt, identity, entrySlot, persist } = params;
60
+ const pending = new Map();
61
+ const sweep = ()=>{
62
+ const cutoff = Date.now() - REQUEST_TTL_MS;
63
+ for (const [id, request] of pending){
64
+ if (request.mintedAt < cutoff) pending.delete(id);
65
+ }
66
+ };
67
+ return {
68
+ async rosterDIDs () {
69
+ return handle().listMembers().map((member)=>member.id);
70
+ },
71
+ async readCommitHeader (commit) {
72
+ const header = await handle().readCommitHeader(commit);
73
+ if (header == null) return null;
74
+ return {
75
+ epoch: Number(header.epoch),
76
+ ...header.committerDID != null && {
77
+ committerDID: header.committerDID
78
+ },
79
+ ...header.external === true && {
80
+ external: true
81
+ }
82
+ };
83
+ },
84
+ async processCommit (commit, context) {
85
+ const group = handle();
86
+ const before = group.epoch;
87
+ entrySlot.install(context.resolveLedgerEntries);
88
+ try {
89
+ await group.processMessage(commit);
90
+ } catch (error) {
91
+ // The ONE throw the port is allowed: the commit named entries whose bodies would
92
+ // not resolve from its own frame. Everything else — a commit at another epoch, one
93
+ // the policy refuses, undecodable bytes — is `{ advanced: false }`, never a throw:
94
+ // a throw makes the lane re-read the frame, and a frame this member was never in a
95
+ // position to apply would wedge it there forever.
96
+ if (error instanceof MissingLedgerEntriesError) throw error;
97
+ return {
98
+ advanced: false
99
+ };
100
+ } finally{
101
+ entrySlot.install(undefined);
102
+ }
103
+ const advanced = handle().epoch !== before;
104
+ // Durable before it resolves: the lane advances its cursor on this answer, so a crash
105
+ // between applying and persisting would lose the commit and never re-read it.
106
+ if (advanced) await persist?.(handle());
107
+ return {
108
+ advanced
109
+ };
110
+ },
111
+ async createRecoveryRequest (requestID) {
112
+ sweep();
113
+ const { request, ephemeralPrivateKey } = await createRecoveryRequest({
114
+ group: handle(),
115
+ identity,
116
+ requestID
117
+ });
118
+ pending.set(requestID, {
119
+ ephemeralPrivateKey,
120
+ mintedAt: Date.now()
121
+ });
122
+ return utf8.encode(request);
123
+ },
124
+ async sealGroupInfo (request) {
125
+ // Throws for a request this member refuses — a removed requester holds no leaf in
126
+ // this member's tree — and the peer stays silent. Roster-intrinsic, not a check here.
127
+ return await sealGroupInfo({
128
+ group: handle(),
129
+ identity,
130
+ request: new TextDecoder().decode(request)
131
+ });
132
+ },
133
+ async applyRecovery (sealed, requestID) {
134
+ const held = pending.get(requestID);
135
+ if (held == null) return null;
136
+ let groupInfo;
137
+ try {
138
+ groupInfo = await openSealedGroupInfo({
139
+ group: handle(),
140
+ sealed,
141
+ requestID,
142
+ ephemeralPrivateKey: held.ephemeralPrivateKey
143
+ });
144
+ } catch {
145
+ // Bytes this peer cannot open OR cannot trust: a forged reply that merely decrypts
146
+ // fails the membership attestation, and both are `null`.
147
+ return null;
148
+ }
149
+ const rejoined = await joinGroupExternal({
150
+ identity,
151
+ groupInfo,
152
+ credential: handle().credential,
153
+ resync: true
154
+ });
155
+ return {
156
+ commit: rejoined.commitMessage,
157
+ // Adopted ONLY if the hub accepts the commit. A peer that adopted first would sit
158
+ // on a branch of its own the moment it lost the compare-and-set.
159
+ onAccepted: async ()=>{
160
+ pending.delete(requestID);
161
+ await adopt(rejoined.group);
162
+ await persist?.(rejoined.group);
163
+ }
164
+ };
165
+ },
166
+ async isLedgerComplete () {
167
+ return await handle().isLedgerComplete();
168
+ },
169
+ async getLedger () {
170
+ return await handle().getLedger();
171
+ },
172
+ async sealLedger (request) {
173
+ return await sealLedger({
174
+ group: handle(),
175
+ request: new TextDecoder().decode(request)
176
+ });
177
+ },
178
+ async openSealedLedger (sealed, requestID) {
179
+ const held = pending.get(requestID);
180
+ if (held == null) return null;
181
+ try {
182
+ // The key is NOT consumed: every responder answers, and the requester must open the
183
+ // next reply after dropping one.
184
+ return await openSealedLedger({
185
+ group: handle(),
186
+ sealed,
187
+ requestID,
188
+ ephemeralPrivateKey: held.ephemeralPrivateKey
189
+ });
190
+ } catch {
191
+ return null;
192
+ }
193
+ },
194
+ async bootstrapLedger (tokens) {
195
+ // Throws for a list whose recomputed head does not match the authenticated one — a
196
+ // lying responder can withhold, never rewrite.
197
+ await handle().bootstrapLedger(tokens);
198
+ await persist?.(handle());
199
+ },
200
+ async exportRecoverySecret () {
201
+ // Epoch-INDEPENDENT by construction: the genesis anchor never changes, so a peer
202
+ // stranded at any epoch derives the same rendezvous. See the class doc — this is not
203
+ // a confidential value.
204
+ const group = handle();
205
+ const { cipherSuite } = group.context;
206
+ return await cipherSuite.kdf.expand(await cipherSuite.kdf.extract(utf8.encode(group.groupID), encodeGroupAnchor(group.anchor)), utf8.encode(RECOVERY_LABEL), 32);
207
+ }
208
+ };
209
+ }
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@kumiai/mls-rpc",
3
+ "version": "0.4.0",
4
+ "description": "The @kumiai/rpc consumer ports (GroupCrypto, GroupMLS) implemented over @kumiai/mls",
5
+ "keywords": [
6
+ "mls",
7
+ "rpc",
8
+ "group",
9
+ "e2ee"
10
+ ],
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "https://github.com/TairuFramework/kumiai",
14
+ "directory": "packages/mls-rpc"
15
+ },
16
+ "license": "MIT",
17
+ "sideEffects": false,
18
+ "type": "module",
19
+ "exports": {
20
+ ".": "./lib/index.js"
21
+ },
22
+ "main": "lib/index.js",
23
+ "types": "lib/index.d.ts",
24
+ "files": [
25
+ "lib/*"
26
+ ],
27
+ "dependencies": {
28
+ "@kokuin/token": "^0.3.0",
29
+ "@noble/ciphers": "^2.1.1",
30
+ "@sozai/runtime": "^0.1.0",
31
+ "@kumiai/mls": "^0.4.0",
32
+ "@kumiai/rpc": "^0.4.0"
33
+ },
34
+ "devDependencies": {
35
+ "ts-mls": "2.0.0-rc.13",
36
+ "vitest": "^4.1.10",
37
+ "@kumiai/rpc-conformance": "^0.4.0"
38
+ },
39
+ "scripts": {
40
+ "build": "pnpm run build:clean && pnpm run build:js && pnpm run build:types",
41
+ "build:clean": "del lib",
42
+ "build:js": "swc src -d ./lib --config-file ../../node_modules/@kigu/dev/swc.json --strip-leading-paths",
43
+ "build:types": "tsc --emitDeclarationOnly --skipLibCheck",
44
+ "test": "pnpm run test:types && pnpm run test:unit",
45
+ "test:types": "tsc --noEmit --skipLibCheck -p tsconfig.test.json",
46
+ "test:unit": "vitest run"
47
+ }
48
+ }