@kumiai/mls-rpc 0.9.0 → 0.10.1

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/lib/crypto.js CHANGED
@@ -1,4 +1,5 @@
1
- import { readMessageEpoch } from '@kumiai/mls';
1
+ import { readMessageAAD, readMessageEpoch } from '@kumiai/mls';
2
+ import { AppFrameStorageError, FrameEpochError, isAppFrameStorageError, sortPendingAppFrames } from '@kumiai/rpc';
2
3
  import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
3
4
  import { createRuntime } from '@sozai/runtime';
4
5
  /**
@@ -29,32 +30,33 @@ import { createRuntime } from '@sozai/runtime';
29
30
  * no v1 peer can read a v2 blob regardless, but the failure reads as "unsupported version"
30
31
  * rather than an AEAD refusal indistinguishable from a wrong epoch or a tampered frame.
31
32
  */ 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;
33
+ export function deriveEntryKey(handle, label) {
34
+ return handle.exportSecret(label ?? ENTRY_SEAL_LABEL, new Uint8Array(), SECRET_LENGTH);
35
+ }
36
+ export function sealEntries(key, entries, runtime = createRuntime()) {
37
+ // Random per seal: two members can frame a commit at the same epoch.
38
+ const nonce = runtime.getRandomValues(new Uint8Array(ENTRY_NONCE_BYTES));
39
+ const ciphertext = xchacha20poly1305(key, nonce).encrypt(entries);
40
+ const sealed = new Uint8Array(1 + nonce.length + ciphertext.length);
41
+ sealed[0] = ENTRY_VERSION;
42
+ sealed.set(nonce, 1);
43
+ sealed.set(ciphertext, 1 + nonce.length);
44
+ return sealed;
45
+ }
46
+ function assertSealedEntryBlob(sealed) {
47
+ if (sealed.length <= 1 + ENTRY_NONCE_BYTES) throw new Error('openEntries: not a sealed blob');
48
+ if (sealed[0] !== ENTRY_VERSION) {
49
+ throw new Error(`openEntries: unsupported blob version ${sealed[0]}`);
50
+ }
51
+ }
52
+ export function openEntries(key, sealed) {
53
+ assertSealedEntryBlob(sealed);
54
+ return xchacha20poly1305(key, sealed.subarray(1, 1 + ENTRY_NONCE_BYTES)).decrypt(sealed.subarray(1 + ENTRY_NONCE_BYTES));
55
+ }
56
+ export function createGroupCrypto(params) {
57
+ const { access, entryLabel = ENTRY_SEAL_LABEL, runtime = createRuntime(), pending } = params;
56
58
  return {
57
- epoch: ()=>Number(handle().epoch),
59
+ epoch: ()=>access.epoch(),
58
60
  // Passed straight through to the handle's exporter, except `entryLabel`: reusing it would
59
61
  // not be an independent export — it's the exact exporter call `sealEntries`/`openEntries`
60
62
  // make below (same context, same `SECRET_LENGTH`), so it would hand back the ledger-entry
@@ -63,48 +65,133 @@ import { createRuntime } from '@sozai/runtime';
63
65
  if (label === entryLabel) {
64
66
  throw new Error(`exportSecret: label '${label}' is reserved for the ledger-entry seal`);
65
67
  }
66
- return handle().exportSecret(label, EXPORT_CONTEXT, length);
68
+ return access.read(async (group)=>({
69
+ secret: await group.exportSecret(label, EXPORT_CONTEXT, length),
70
+ epoch: Number(group.epoch)
71
+ }));
67
72
  },
68
- wrap: (bytes, opts)=>handle().encrypt(bytes, opts),
73
+ wrap: (bytes, opts)=>access.mutate((group)=>group.encrypt(bytes, opts)),
69
74
  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;
75
+ const { key, epoch } = await access.read(async (group)=>({
76
+ key: await deriveEntryKey(group, entryLabel),
77
+ epoch: Number(group.epoch)
78
+ }));
79
+ try {
80
+ return {
81
+ sealed: sealEntries(key, bytes, runtime),
82
+ epoch
83
+ };
84
+ } finally{
85
+ key.fill(0);
86
+ }
80
87
  },
81
88
  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]}`);
89
+ assertSealedEntryBlob(sealed);
90
+ const key = await access.read((group)=>deriveEntryKey(group, entryLabel));
91
+ try {
92
+ return openEntries(key, sealed);
93
+ } finally{
94
+ key.fill(0);
88
95
  }
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
96
  },
94
97
  unwrap: async (bytes, opts)=>{
95
- const { payload, senderDID } = await handle().decrypt(bytes, opts);
98
+ if (opts?.frame != null) {
99
+ if (pending == null) throw new Error('unwrap: pending store required for durable open');
100
+ const frame = opts.frame;
101
+ // Wrapped here, not inside `fn`: a transactional adapter makes the write after `fn`.
102
+ const persistOpened = async (state, record)=>{
103
+ try {
104
+ await pending.persistOpened(state, record);
105
+ } catch (error) {
106
+ throw new AppFrameStorageError('failed to persist opened app frame', {
107
+ cause: error
108
+ });
109
+ }
110
+ };
111
+ let openError;
112
+ const open = async (group, persistStaged)=>{
113
+ const epoch = Number(group.epoch);
114
+ const frameEpoch = readMessageEpoch(bytes);
115
+ if (frameEpoch != null && Number(frameEpoch) !== epoch) {
116
+ throw new FrameEpochError(Number(frameEpoch), epoch);
117
+ }
118
+ const result = await group.decryptStaged(bytes, opts, async (stagedState, result)=>{
119
+ // The handle adopts the staged state only after this returns: a fault here leaves
120
+ // the key unspent, so the frame must be retried, not dropped.
121
+ try {
122
+ await persistStaged(stagedState, {
123
+ frame,
124
+ payload: result.payload,
125
+ senderDID: result.senderDID
126
+ });
127
+ } catch (error) {
128
+ if (isAppFrameStorageError(error)) throw error;
129
+ throw new AppFrameStorageError('failed to stage opened app frame', {
130
+ cause: error
131
+ });
132
+ }
133
+ });
134
+ return {
135
+ ...result,
136
+ epoch
137
+ };
138
+ };
139
+ let opened;
140
+ try {
141
+ opened = await access.open(async (group, persistStaged)=>{
142
+ try {
143
+ return await open(group, persistStaged);
144
+ } catch (error) {
145
+ openError = error;
146
+ throw error;
147
+ }
148
+ }, persistOpened);
149
+ } catch (error) {
150
+ // The open's own refusal says whether the frame is dead. Anything the adapter raised
151
+ // around it (a restore, a read) left the key unspent, so the lane must retry.
152
+ if (error === openError || isAppFrameStorageError(error)) throw error;
153
+ throw new AppFrameStorageError('handle access failed during durable open', {
154
+ cause: error
155
+ });
156
+ }
157
+ return {
158
+ payload: opened.payload,
159
+ senderDID: opened.senderDID,
160
+ epoch: opened.epoch
161
+ };
162
+ }
163
+ const { payload, senderDID, epoch } = await access.mutate(async (group)=>{
164
+ const epoch = Number(group.epoch);
165
+ const frameEpoch = readMessageEpoch(bytes);
166
+ if (frameEpoch != null && Number(frameEpoch) !== epoch) {
167
+ throw new FrameEpochError(Number(frameEpoch), epoch);
168
+ }
169
+ const opened = await group.decrypt(bytes, opts);
170
+ return {
171
+ ...opened,
172
+ epoch
173
+ };
174
+ });
96
175
  if (senderDID == null) {
97
176
  throw new Error('unwrap: opened frame has no authenticated sender');
98
177
  }
99
178
  return {
100
179
  payload,
101
- senderDID
180
+ senderDID,
181
+ epoch
102
182
  };
103
183
  },
104
184
  frameEpoch: (bytes)=>{
105
185
  // Total by contract: readMessageEpoch never throws and answers without a key.
106
186
  const epoch = readMessageEpoch(bytes);
107
187
  return epoch == null ? null : Number(epoch);
188
+ },
189
+ frameAAD: (bytes)=>readMessageAAD(bytes),
190
+ ...pending == null ? {} : {
191
+ pending: {
192
+ list: async ()=>sortPendingAppFrames(await pending.list()),
193
+ complete: (id)=>pending.complete(id)
194
+ }
108
195
  }
109
196
  };
110
197
  }
package/lib/index.d.ts CHANGED
@@ -18,5 +18,8 @@
18
18
  *
19
19
  * @module mls-rpc
20
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';
21
+ export { type HandleAccess, type SimpleHandleAccessParams, simpleHandleAccess } from './access.js';
22
+ export { type ApplyCommitParams, type ApplyCommitResult, applyCommit } from './apply-commit.js';
23
+ export { createGroupCrypto, deriveEntryKey, ENTRY_SEAL_LABEL, type GroupCryptoParams, openEntries, sealEntries, } from './crypto.js';
24
+ export { createGroupMLS, createLedgerEntrySlot, createRecoveryPending, deriveRecoverySecret, type GroupMLSParams, type LedgerEntrySlot, RECOVERY_LABEL, type RecoveryPending, } from './mls.js';
25
+ export { type PublishRevokeProofParams, type PublishRevokeResult, publishRevokeProof, type RevokeJournalOptions, } from './revoke.js';
package/lib/index.js CHANGED
@@ -17,5 +17,8 @@
17
17
  * failure mode the seam already has.
18
18
  *
19
19
  * @module mls-rpc
20
- */ export { createGroupCrypto, ENTRY_SEAL_LABEL } from './crypto.js';
21
- export { createGroupMLS, createLedgerEntrySlot, RECOVERY_LABEL } from './mls.js';
20
+ */ export { simpleHandleAccess } from './access.js';
21
+ export { applyCommit } from './apply-commit.js';
22
+ export { createGroupCrypto, deriveEntryKey, ENTRY_SEAL_LABEL, openEntries, sealEntries } from './crypto.js';
23
+ export { createGroupMLS, createLedgerEntrySlot, createRecoveryPending, deriveRecoverySecret, RECOVERY_LABEL } from './mls.js';
24
+ export { publishRevokeProof } from './revoke.js';
package/lib/mls.d.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  import type { OwnIdentity } from '@kokuin/token';
2
2
  import { type GroupHandle } from '@kumiai/mls';
3
3
  import type { GroupMLS } from '@kumiai/rpc';
4
+ import type { HandleAccess } from './access.js';
5
+ import { type RecoveryBinding } from './recovery.js';
6
+ export declare const groupHandleAccess: WeakMap<GroupMLS, HandleAccess>;
4
7
  /**
5
8
  * The label the non-rotating recovery secret is derived under. This secret is the root of
6
9
  * BOTH the commit topic and the rendezvous topic — everything downstream of it depends on
@@ -33,21 +36,29 @@ export type LedgerEntrySlot = {
33
36
  };
34
37
  export declare function createLedgerEntrySlot(): LedgerEntrySlot;
35
38
  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>;
39
+ access: HandleAccess;
40
40
  /** This member's signing identity: recovery requests and attestations are signed with it. */
41
41
  identity: OwnIdentity;
42
42
  /** The slot the handle was built with. See {@link LedgerEntrySlot}. */
43
43
  entrySlot: LedgerEntrySlot;
44
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.
45
+ * The group's recovery secret, read under `access.read`. Defaults to
46
+ * {@link deriveRecoverySecret}. A host whose groups already use another derivation passes it
47
+ * here for every restore of that group: the commit and rendezvous topics follow the choice.
48
48
  */
49
- persist?: (handle: GroupHandle) => void | Promise<void>;
49
+ recoverySecret?: (handle: GroupHandle) => Promise<Uint8Array>;
50
+ /** Fresh own-leaf binding, at most once per attempt. Return null without waiting on the user. */
51
+ recoveryBinding?: RecoveryBinding;
50
52
  };
53
+ export type RecoveryPending = {
54
+ get(requestID: string): Uint8Array | null;
55
+ put(requestID: string, ephemeralPrivateKey: Uint8Array, deadlineMs?: number): void;
56
+ delete(requestID: string): void;
57
+ };
58
+ export declare function createRecoveryPending(options?: {
59
+ ttlMS?: number;
60
+ }): RecoveryPending;
61
+ export declare function deriveRecoverySecret(handle: GroupHandle): Promise<Uint8Array>;
51
62
  /**
52
63
  * {@link GroupMLS} over a live {@link GroupHandle} — the real lifecycle port.
53
64
  *
@@ -60,7 +71,7 @@ export type GroupMLSParams = {
60
71
  * adopts it in `onAccepted`). A host that treated every commit as adopt-later would
61
72
  * double-apply received ones.
62
73
  *
63
- * 2. **`rosterDIDs` reads the ratchet tree, so a leaf with an unparsable credential is
74
+ * 2. **`rosterEntries` reads the ratchet tree, so a leaf with an unparsable credential is
64
75
  * simply absent** rather than present-with-a-placeholder. The double's roster is a set of
65
76
  * strings it was handed.
66
77
  *