@kumiai/mls-rpc 0.11.0 → 0.13.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
@@ -19,6 +19,9 @@ depend on both.
19
19
 
20
20
  - `simpleHandleAccess({ handle, adopt, persist? })` — serialised access to a live handle; the
21
21
  `HandleAccess` type for a host that brings its own.
22
+ - `retainsKnownEffects(next)` — replacement guard refusing a handle that drops lifecycle effects the
23
+ live handle knows. `guardedReplace(access, next)` replaces through it, and throws afterwards if
24
+ `access` never invoked the guard (a broken adapter has then already adopted `next`).
22
25
  - `createGroupCrypto({ access, entryLabel?, runtime?, pending? })` — `GroupCrypto` over that access.
23
26
  - `createGroupMLS({ access, identity, entrySlot, recoverySecret? })` — `GroupMLS` over the same
24
27
  access.
@@ -33,8 +36,8 @@ depend on both.
33
36
 
34
37
  Both factories take the same `access` instance. The adapter reads the current handle through
35
38
  `handle: () => GroupHandle`, because authored commits and recovery replace it wholesale. A host
36
- adopts an authored commit through `access.replace(next)` after acceptance. The adapter saves before
37
- publishing the replacement and publishes its synchronous epoch hint after a successful save.
39
+ adopts an authored commit through `guardedReplace(access, next)` after acceptance. The adapter saves
40
+ before publishing the replacement and publishes its synchronous epoch hint after a successful save.
38
41
 
39
42
  Before every host commit build, `createGroupMLS` persists a handshake reservation through `access.mutate`.
40
43
  The epoch and application ratchet stay unchanged, including when a discarded CAS winner never applies.
@@ -79,8 +82,10 @@ const mls = createGroupMLS({ access, identity, entrySlot })
79
82
  A host with its own handle store implements the port instead:
80
83
  - `read(fn)` lends the handle for the callback only. `mutate(fn)` serialises with every other
81
84
  operation and resolves after the state is stored; `fn`'s `persist` argument goes to
82
- `processMessage`, `bootstrapLedger` and `reserveHandshakeGeneration`. `replace(next)` stores before publishing. A transactional
83
- host may restore a fresh handle per mutation, discard it on rollback, and publish on commit.
85
+ `processMessage`, `bootstrapLedger` and `reserveHandshakeGeneration`. `replace(next, guard)`
86
+ must run `guard(live)` on the live handle under the lock, abort if it throws, then store before
87
+ publishing. A transactional host may restore a fresh handle per mutation, discard it on rollback,
88
+ and publish on commit.
84
89
  - `epoch()` is a synchronous hint. Publish it only after the outermost successful commit, and restore
85
90
  it on rollback. No port decision reads it: every one uses an epoch read under the lock.
86
91
  - `open(fn, persistOpened)` is the durable open. `fn` stages the open and hands its state and record
package/lib/access.d.ts CHANGED
@@ -1,6 +1,14 @@
1
- import type { GroupHandle } from '@kumiai/mls';
1
+ import { type GroupHandle } from '@kumiai/mls';
2
2
  import type { PendingAppFrame, SendAdmission } from '@kumiai/rpc';
3
3
  type PersistOpened = (stagedState: Uint8Array, record: PendingAppFrame) => Promise<void>;
4
+ export type HandleAccessReplaceParams = {
5
+ next: GroupHandle;
6
+ guard: (live: GroupHandle) => Promise<void>;
7
+ };
8
+ export type HandleAccessOpenParams<TValue> = {
9
+ fn: (handle: GroupHandle, persistOpened: PersistOpened) => Promise<TValue>;
10
+ persistOpened: PersistOpened;
11
+ };
4
12
  export type HandleAccess = {
5
13
  /** Published with admission after mutation/open and after replacement adoption resolves. */
6
14
  epoch(): number;
@@ -8,9 +16,22 @@ export type HandleAccess = {
8
16
  admission(): SendAdmission;
9
17
  read<TValue>(fn: (handle: GroupHandle) => TValue | Promise<TValue>): Promise<TValue>;
10
18
  mutate<TValue>(fn: (handle: GroupHandle, persist: (handle: GroupHandle) => Promise<void>) => Promise<TValue>): Promise<TValue>;
11
- replace(next: GroupHandle): Promise<void>;
12
- open<TValue>(fn: (handle: GroupHandle, persistOpened: PersistOpened) => Promise<TValue>, persistOpened: PersistOpened): Promise<TValue>;
19
+ /** Must run the guard under the replacement lock, before persistence; a throw aborts. */
20
+ replace(params: HandleAccessReplaceParams): Promise<void>;
21
+ open<TValue>(params: HandleAccessOpenParams<TValue>): Promise<TValue>;
22
+ };
23
+ /** Refuses a replacement that drops lifecycle effects the live handle knows. */
24
+ export declare function retainsKnownEffects(next: GroupHandle): (live: GroupHandle) => Promise<void>;
25
+ export type GuardedReplaceParams = {
26
+ access: HandleAccess;
27
+ next: GroupHandle;
13
28
  };
29
+ /**
30
+ * Replaces through `retainsKnownEffects`. A guard never invoked throws after the fact (the skipping
31
+ * implementation has already adopted `next`): this surfaces a broken adapter, it does not undo it.
32
+ * It cannot prove the guard ran on the live handle or under the lock; that stays the port contract.
33
+ */
34
+ export declare function guardedReplace({ access, next }: GuardedReplaceParams): Promise<void>;
14
35
  export type SimpleHandleAccessParams = {
15
36
  handle: () => GroupHandle;
16
37
  adopt: (next: GroupHandle) => void | Promise<void>;
package/lib/access.js CHANGED
@@ -1,3 +1,31 @@
1
+ import { assertRetainsKnownEffects } from '@kumiai/mls';
2
+ /** Refuses a replacement that drops lifecycle effects the live handle knows. */ export function retainsKnownEffects(next) {
3
+ return async (live)=>{
4
+ const controller = live.anchor.controller;
5
+ if (controller != null) await assertRetainsKnownEffects({
6
+ controller,
7
+ known: live.registry,
8
+ candidate: next.registry,
9
+ crypto: live.crypto
10
+ });
11
+ };
12
+ }
13
+ /**
14
+ * Replaces through `retainsKnownEffects`. A guard never invoked throws after the fact (the skipping
15
+ * implementation has already adopted `next`): this surfaces a broken adapter, it does not undo it.
16
+ * It cannot prove the guard ran on the live handle or under the lock; that stays the port contract.
17
+ */ export async function guardedReplace({ access, next }) {
18
+ const guard = retainsKnownEffects(next);
19
+ let ran = false;
20
+ await access.replace({
21
+ next,
22
+ guard: async (live)=>{
23
+ await guard(live);
24
+ ran = true;
25
+ }
26
+ });
27
+ if (!ran) throw new Error('HandleAccess.replace did not run its guard');
28
+ }
1
29
  export function simpleHandleAccess(params) {
2
30
  let publishedAdmission = params.handle().sendAdmission();
3
31
  let tail = Promise.resolve();
@@ -33,13 +61,14 @@ export function simpleHandleAccess(params) {
33
61
  publishedAdmission = handle.sendAdmission();
34
62
  return result;
35
63
  }),
36
- replace: (next)=>serialise(async ()=>{
64
+ replace: ({ next, guard })=>serialise(async ()=>{
65
+ await guard(params.handle());
37
66
  await save(next);
38
67
  await params.adopt(next);
39
68
  publishedAdmission = next.sendAdmission();
40
69
  next.confirmAdopted();
41
70
  }),
42
- open: (fn, persistOpened)=>serialise(async ()=>{
71
+ open: ({ fn, persistOpened })=>serialise(async ()=>{
43
72
  const handle = params.handle();
44
73
  const result = await fn(handle, persistOpened);
45
74
  publishedAdmission = handle.sendAdmission();
@@ -62,7 +62,8 @@ function rosterOf(handle) {
62
62
  }
63
63
  }));
64
64
  try {
65
- await handle.processMessage(commit, {
65
+ await handle.processMessage({
66
+ message: commit,
66
67
  ...persist != null && {
67
68
  persist: async (current)=>{
68
69
  try {
package/lib/crypto.d.ts CHANGED
@@ -10,9 +10,22 @@ import type { HandleAccess } from './access.js';
10
10
  * from a caller (see below).
11
11
  */
12
12
  export declare const ENTRY_SEAL_LABEL = "kumiai/ledger-entries/v1";
13
- export declare function deriveEntryKey(handle: GroupHandle, label?: string): Promise<Uint8Array>;
14
- export declare function sealEntries(key: Uint8Array, entries: Uint8Array, runtime?: Runtime): Uint8Array;
15
- export declare function openEntries(key: Uint8Array, sealed: Uint8Array): Uint8Array;
13
+ export type DeriveEntryKeyParams = {
14
+ handle: GroupHandle;
15
+ label?: string;
16
+ };
17
+ export declare function deriveEntryKey({ handle, label }: DeriveEntryKeyParams): Promise<Uint8Array>;
18
+ export type SealEntriesParams = {
19
+ key: Uint8Array;
20
+ entries: Uint8Array;
21
+ runtime?: Runtime;
22
+ };
23
+ export declare function sealEntries({ key, entries, runtime, }: SealEntriesParams): Uint8Array;
24
+ export type OpenEntriesParams = {
25
+ key: Uint8Array;
26
+ sealed: Uint8Array;
27
+ };
28
+ export declare function openEntries({ key, sealed }: OpenEntriesParams): Uint8Array;
16
29
  export type GroupCryptoParams = {
17
30
  access: HandleAccess;
18
31
  /**
package/lib/crypto.js CHANGED
@@ -30,10 +30,14 @@ import { createRuntime } from '@sozai/runtime';
30
30
  * no v1 peer can read a v2 blob regardless, but the failure reads as "unsupported version"
31
31
  * rather than an AEAD refusal indistinguishable from a wrong epoch or a tampered frame.
32
32
  */ const ENTRY_VERSION = 1;
33
- export function deriveEntryKey(handle, label) {
34
- return handle.exportSecret(label ?? ENTRY_SEAL_LABEL, new Uint8Array(), SECRET_LENGTH);
33
+ export function deriveEntryKey({ handle, label }) {
34
+ return handle.exportSecret({
35
+ label: label ?? ENTRY_SEAL_LABEL,
36
+ context: new Uint8Array(),
37
+ length: SECRET_LENGTH
38
+ });
35
39
  }
36
- export function sealEntries(key, entries, runtime = createRuntime()) {
40
+ export function sealEntries({ key, entries, runtime = createRuntime() }) {
37
41
  // Random per seal: two members can frame a commit at the same epoch.
38
42
  const nonce = runtime.getRandomValues(new Uint8Array(ENTRY_NONCE_BYTES));
39
43
  const ciphertext = xchacha20poly1305(key, nonce).encrypt(entries);
@@ -49,7 +53,7 @@ function assertSealedEntryBlob(sealed) {
49
53
  throw new Error(`openEntries: unsupported blob version ${sealed[0]}`);
50
54
  }
51
55
  }
52
- export function openEntries(key, sealed) {
56
+ export function openEntries({ key, sealed }) {
53
57
  assertSealedEntryBlob(sealed);
54
58
  return xchacha20poly1305(key, sealed.subarray(1, 1 + ENTRY_NONCE_BYTES)).decrypt(sealed.subarray(1 + ENTRY_NONCE_BYTES));
55
59
  }
@@ -61,24 +65,38 @@ export function createGroupCrypto(params) {
61
65
  // not be an independent export — it's the exact exporter call `sealEntries`/`openEntries`
62
66
  // make below (same context, same `SECRET_LENGTH`), so it would hand back the ledger-entry
63
67
  // seal key under another name. Refused here, loudly, rather than left to the doc alone.
64
- exportSecret: (label, length = SECRET_LENGTH)=>{
68
+ exportSecret: ({ label, length = SECRET_LENGTH })=>{
65
69
  if (label === entryLabel) {
66
70
  throw new Error(`exportSecret: label '${label}' is reserved for the ledger-entry seal`);
67
71
  }
68
72
  return access.read(async (group)=>({
69
- secret: await group.exportSecret(label, EXPORT_CONTEXT, length),
73
+ secret: await group.exportSecret({
74
+ label,
75
+ context: EXPORT_CONTEXT,
76
+ length
77
+ }),
70
78
  epoch: Number(group.epoch)
71
79
  }));
72
80
  },
73
- wrap: (bytes, opts)=>access.mutate((group)=>group.encrypt(bytes, opts)),
81
+ wrap: ({ bytes, ...opts })=>access.mutate((group)=>group.encrypt({
82
+ plaintext: bytes,
83
+ ...opts
84
+ })),
74
85
  sealEntries: async (bytes)=>{
75
86
  const { key, epoch } = await access.read(async (group)=>({
76
- key: await deriveEntryKey(group, entryLabel),
87
+ key: await deriveEntryKey({
88
+ handle: group,
89
+ label: entryLabel
90
+ }),
77
91
  epoch: Number(group.epoch)
78
92
  }));
79
93
  try {
80
94
  return {
81
- sealed: sealEntries(key, bytes, runtime),
95
+ sealed: sealEntries({
96
+ key,
97
+ entries: bytes,
98
+ runtime
99
+ }),
82
100
  epoch
83
101
  };
84
102
  } finally{
@@ -87,14 +105,20 @@ export function createGroupCrypto(params) {
87
105
  },
88
106
  openEntries: async (sealed)=>{
89
107
  assertSealedEntryBlob(sealed);
90
- const key = await access.read((group)=>deriveEntryKey(group, entryLabel));
108
+ const key = await access.read((group)=>deriveEntryKey({
109
+ handle: group,
110
+ label: entryLabel
111
+ }));
91
112
  try {
92
- return openEntries(key, sealed);
113
+ return openEntries({
114
+ key,
115
+ sealed
116
+ });
93
117
  } finally{
94
118
  key.fill(0);
95
119
  }
96
120
  },
97
- unwrap: async (bytes, opts)=>{
121
+ unwrap: async ({ bytes, ...opts })=>{
98
122
  if (opts?.frame != null) {
99
123
  if (pending == null) throw new Error('unwrap: pending store required for durable open');
100
124
  const frame = opts.frame;
@@ -113,22 +137,29 @@ export function createGroupCrypto(params) {
113
137
  const epoch = Number(group.epoch);
114
138
  const frameEpoch = readMessageEpoch(bytes);
115
139
  if (frameEpoch != null && Number(frameEpoch) !== epoch) {
116
- throw new FrameEpochError(Number(frameEpoch), epoch);
140
+ throw new FrameEpochError({
141
+ frameEpoch: Number(frameEpoch),
142
+ handleEpoch: epoch
143
+ });
117
144
  }
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
- });
145
+ const result = await group.decryptStaged({
146
+ message: bytes,
147
+ opts,
148
+ persist: async (stagedState, result)=>{
149
+ // The handle adopts the staged state only after this returns: a fault here leaves
150
+ // the key unspent, so the frame must be retried, not dropped.
151
+ try {
152
+ await persistStaged(stagedState, {
153
+ frame,
154
+ payload: result.payload,
155
+ senderDID: result.senderDID
156
+ });
157
+ } catch (error) {
158
+ if (isAppFrameStorageError(error)) throw error;
159
+ throw new AppFrameStorageError('failed to stage opened app frame', {
160
+ cause: error
161
+ });
162
+ }
132
163
  }
133
164
  });
134
165
  return {
@@ -138,14 +169,17 @@ export function createGroupCrypto(params) {
138
169
  };
139
170
  let opened;
140
171
  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);
172
+ opened = await access.open({
173
+ fn: async (group, persistStaged)=>{
174
+ try {
175
+ return await open(group, persistStaged);
176
+ } catch (error) {
177
+ openError = error;
178
+ throw error;
179
+ }
180
+ },
181
+ persistOpened
182
+ });
149
183
  } catch (error) {
150
184
  // The open's own refusal says whether the frame is dead. Anything the adapter raised
151
185
  // around it (a restore, a read) left the key unspent, so the lane must retry.
@@ -164,9 +198,15 @@ export function createGroupCrypto(params) {
164
198
  const epoch = Number(group.epoch);
165
199
  const frameEpoch = readMessageEpoch(bytes);
166
200
  if (frameEpoch != null && Number(frameEpoch) !== epoch) {
167
- throw new FrameEpochError(Number(frameEpoch), epoch);
201
+ throw new FrameEpochError({
202
+ frameEpoch: Number(frameEpoch),
203
+ handleEpoch: epoch
204
+ });
168
205
  }
169
- const opened = await group.decrypt(bytes, opts);
206
+ const opened = await group.decrypt({
207
+ message: bytes,
208
+ ...opts
209
+ });
170
210
  return {
171
211
  ...opened,
172
212
  epoch
package/lib/index.d.ts CHANGED
@@ -18,8 +18,11 @@
18
18
  *
19
19
  * @module mls-rpc
20
20
  */
21
- export { type HandleAccess, type SimpleHandleAccessParams, simpleHandleAccess } from './access.js';
21
+ export type { GuardedReplaceParams, HandleAccessOpenParams, HandleAccessReplaceParams, } from './access.js';
22
+ export { guardedReplace, type HandleAccess, retainsKnownEffects, type SimpleHandleAccessParams, simpleHandleAccess, } from './access.js';
22
23
  export { type ApplyCommitParams, type ApplyCommitResult, applyCommit } from './apply-commit.js';
24
+ export type { DeriveEntryKeyParams, OpenEntriesParams, SealEntriesParams } from './crypto.js';
23
25
  export { createGroupCrypto, deriveEntryKey, ENTRY_SEAL_LABEL, type GroupCryptoParams, openEntries, sealEntries, } from './crypto.js';
26
+ export type { RecoveryPendingPutParams } from './mls.js';
24
27
  export { createGroupMLS, createLedgerEntrySlot, createRecoveryPending, deriveRecoverySecret, type GroupMLSParams, type LedgerEntrySlot, RECOVERY_LABEL, type RecoveryPending, } from './mls.js';
25
28
  export { type PublishRevokeProofParams, type PublishRevokeResult, publishRevokeProof, type RevokeJournalOptions, } from './revoke.js';
package/lib/index.js CHANGED
@@ -17,7 +17,7 @@
17
17
  * failure mode the seam already has.
18
18
  *
19
19
  * @module mls-rpc
20
- */ export { simpleHandleAccess } from './access.js';
20
+ */ export { guardedReplace, retainsKnownEffects, simpleHandleAccess } from './access.js';
21
21
  export { applyCommit } from './apply-commit.js';
22
22
  export { createGroupCrypto, deriveEntryKey, ENTRY_SEAL_LABEL, openEntries, sealEntries } from './crypto.js';
23
23
  export { createGroupMLS, createLedgerEntrySlot, createRecoveryPending, deriveRecoverySecret, RECOVERY_LABEL } from './mls.js';
package/lib/mls.d.ts CHANGED
@@ -1,7 +1,7 @@
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';
4
+ import { type HandleAccess } from './access.js';
5
5
  import { type RecoveryBinding } from './recovery.js';
6
6
  export declare const groupHandleAccess: WeakMap<GroupMLS, HandleAccess>;
7
7
  /**
@@ -50,9 +50,14 @@ export type GroupMLSParams = {
50
50
  /** Fresh own-leaf binding, at most once per attempt. Return null without waiting on the user. */
51
51
  recoveryBinding?: RecoveryBinding;
52
52
  };
53
+ export type RecoveryPendingPutParams = {
54
+ requestID: string;
55
+ ephemeralPrivateKey: Uint8Array;
56
+ deadlineMs?: number;
57
+ };
53
58
  export type RecoveryPending = {
54
59
  get(requestID: string): Uint8Array | null;
55
- put(requestID: string, ephemeralPrivateKey: Uint8Array, deadlineMs?: number): void;
60
+ put(params: RecoveryPendingPutParams): void;
56
61
  delete(requestID: string): void;
57
62
  };
58
63
  export declare function createRecoveryPending(options?: {
package/lib/mls.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { confirmationKey, createRecoveryRequest, encodeGroupAnchor, ledgerEntryDigest, MissingLedgerEntriesError, openRecoveryGroupInfo, openRecoveryVerdict, openSealedLedger, readCommitEntryIDs, readMessageEpoch, recoverySignerEligible, sealGroupInfo, sealLedger, sealRecoveryVerdict, verifyRecoveryRequest } from '@kumiai/mls';
2
+ import { guardedReplace } from './access.js';
2
3
  import { applyCommit } from './apply-commit.js';
3
- import { createRecoveryBindingState, createVerdictJudge, knownRecoveryRegistry } from './recovery.js';
4
+ import { createRecoveryBindingState, createVerdictJudge } from './recovery.js';
4
5
  export const groupHandleAccess = new WeakMap();
5
6
  const utf8 = new TextEncoder();
6
7
  /**
@@ -54,7 +55,7 @@ export function createRecoveryPending(options) {
54
55
  sweep();
55
56
  return requests.get(requestID)?.ephemeralPrivateKey ?? null;
56
57
  },
57
- put: (requestID, ephemeralPrivateKey, deadlineMs = 0)=>{
58
+ put: ({ requestID, ephemeralPrivateKey, deadlineMs = 0 })=>{
58
59
  const retentionMs = Math.max(ttlMS, deadlineMs);
59
60
  sweep();
60
61
  const previous = requests.get(requestID);
@@ -113,7 +114,11 @@ export async function deriveRecoverySecret(handle) {
113
114
  const port = {
114
115
  async verifyRecoveryRequest (request) {
115
116
  try {
116
- const verified = await verifyRecoveryRequest(new TextDecoder().decode(request));
117
+ const crypto = await access.read((group)=>group.crypto);
118
+ const verified = await verifyRecoveryRequest({
119
+ token: new TextDecoder().decode(request),
120
+ crypto
121
+ });
117
122
  return await access.read((group)=>verified.groupID === group.groupID ? {
118
123
  groupID: verified.groupID,
119
124
  requestID: verified.requestID,
@@ -123,13 +128,17 @@ export async function deriveRecoverySecret(handle) {
123
128
  return null;
124
129
  }
125
130
  },
126
- async confirmationKey (position, commitDigest) {
131
+ async confirmationKey ({ position, commitDigest }) {
127
132
  return await access.read(async (group)=>({
128
133
  epoch: Number(group.epoch),
129
- key: await confirmationKey(group, position, commitDigest)
134
+ key: await confirmationKey({
135
+ group,
136
+ position,
137
+ commitDigest
138
+ })
130
139
  }));
131
140
  },
132
- async sealRecoveryVerdict (request, verdict) {
141
+ async sealRecoveryVerdict ({ request, verdict }) {
133
142
  return await access.read((group)=>sealRecoveryVerdict({
134
143
  group,
135
144
  identity,
@@ -137,7 +146,7 @@ export async function deriveRecoverySecret(handle) {
137
146
  verdict
138
147
  }));
139
148
  },
140
- async openRecoveryVerdict (sealed, requestID) {
149
+ async openRecoveryVerdict ({ sealed, requestID }) {
141
150
  const held = pending.get(requestID);
142
151
  if (held == null) return null;
143
152
  try {
@@ -187,7 +196,7 @@ export async function deriveRecoverySecret(handle) {
187
196
  }
188
197
  };
189
198
  },
190
- async processCommit (commit, context) {
199
+ async processCommit ({ commit, context }) {
191
200
  const frameEpoch = readMessageEpoch(commit);
192
201
  const eligible = await access.read(async (group)=>{
193
202
  const header = await group.readCommitHeader(commit);
@@ -255,13 +264,17 @@ export async function deriveRecoverySecret(handle) {
255
264
  throw error;
256
265
  }
257
266
  },
258
- async createRecoveryRequest (requestID, deadlineMs) {
267
+ async createRecoveryRequest ({ requestID, deadlineMs }) {
259
268
  const { request, ephemeralPrivateKey } = await access.read((group)=>createRecoveryRequest({
260
269
  group,
261
270
  identity,
262
271
  requestID
263
272
  }));
264
- pending.put(requestID, ephemeralPrivateKey, Math.max(REQUEST_TTL_MS, deadlineMs ?? 0));
273
+ pending.put({
274
+ requestID,
275
+ ephemeralPrivateKey,
276
+ deadlineMs: Math.max(REQUEST_TTL_MS, deadlineMs ?? 0)
277
+ });
265
278
  return utf8.encode(request);
266
279
  },
267
280
  async sealGroupInfo (request) {
@@ -273,7 +286,7 @@ export async function deriveRecoverySecret(handle) {
273
286
  request: new TextDecoder().decode(request)
274
287
  }));
275
288
  },
276
- async applyRecovery (sealed, requestID) {
289
+ async applyRecovery ({ sealed, requestID }) {
277
290
  const held = pending.get(requestID);
278
291
  if (held == null) return null;
279
292
  let reply;
@@ -294,14 +307,14 @@ export async function deriveRecoverySecret(handle) {
294
307
  if (rejoined == null || 'renewalRequired' in rejoined) return rejoined;
295
308
  return {
296
309
  ...rejoined,
297
- knownRegistry: knownRecoveryRegistry(group.registry, rejoined.sourceRegistry)
310
+ knownRegistry: rejoined.group.registry
298
311
  };
299
312
  });
300
313
  if (candidate == null || 'renewalRequired' in candidate) return candidate;
301
314
  const rejoined = candidate;
302
- if (rejoined.group.anchor.controller != null && !recoverySignerEligible({
315
+ if (rejoined.group.anchor.controller != null && !await recoverySignerEligible({
303
316
  group: rejoined.group,
304
- known: rejoined.knownRegistry,
317
+ registry: rejoined.knownRegistry,
305
318
  signer: reply.signer
306
319
  })) return null;
307
320
  const judge = createVerdictJudge({
@@ -324,7 +337,10 @@ export async function deriveRecoverySecret(handle) {
324
337
  confirmationKey: judge.confirmationKey,
325
338
  judgeVerdict: judge.judgeVerdict,
326
339
  onAccepted: ()=>{
327
- accepted ??= access.replace(rejoined.group).catch((error)=>{
340
+ accepted ??= guardedReplace({
341
+ access,
342
+ next: rejoined.group
343
+ }).catch((error)=>{
328
344
  accepted = undefined;
329
345
  throw error;
330
346
  });
@@ -345,7 +361,7 @@ export async function deriveRecoverySecret(handle) {
345
361
  request: new TextDecoder().decode(request)
346
362
  }));
347
363
  },
348
- async openSealedLedger (sealed, requestID) {
364
+ async openSealedLedger ({ sealed, requestID }) {
349
365
  const held = pending.get(requestID);
350
366
  if (held == null) return null;
351
367
  try {
@@ -367,7 +383,8 @@ export async function deriveRecoverySecret(handle) {
367
383
  await access.mutate(async (group, persist)=>{
368
384
  let persisted = false;
369
385
  try {
370
- await group.bootstrapLedger(tokens, {
386
+ await group.bootstrapLedger({
387
+ tokens,
371
388
  persist: async (current)=>{
372
389
  await persist(current);
373
390
  persisted = true;
package/lib/recovery.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type OwnIdentity } from '@kokuin/token';
2
2
  import { type ClientState, type ControllerBinding, type DeviceRegistry, type GroupHandle } from '@kumiai/mls';
3
- import type { OpenedRecoveryVerdict, PendingRecovery } from '@kumiai/rpc';
3
+ import type { OpenedRecoveryVerdict, PendingRecovery, PendingRecoveryConfirmationKeyParams } from '@kumiai/rpc';
4
4
  export type RecoveryBindingRequest = {
5
5
  groupID: string;
6
6
  controllerID: string;
@@ -27,7 +27,6 @@ export type RecoveryCandidate = PendingRecovery & {
27
27
  replyLedger: Array<string>;
28
28
  signer: string;
29
29
  };
30
- export declare function knownRecoveryRegistry(known: DeviceRegistry, reply: DeviceRegistry): DeviceRegistry;
31
30
  export declare function createRecoveryBindingState(identity: OwnIdentity, host?: RecoveryBinding): {
32
31
  prepare(group: GroupHandle): Promise<"ready" | "renewal-required">;
33
32
  join(group: GroupHandle, reply: RecoveryReply): Promise<{
@@ -41,6 +40,6 @@ export declare function createRecoveryBindingState(identity: OwnIdentity, host?:
41
40
  } | null>;
42
41
  };
43
42
  export declare function createVerdictJudge(params: VerdictJudgeParams): {
44
- confirmationKey(position: string, commitDigest: string): Promise<Uint8Array<ArrayBufferLike>>;
45
- judgeVerdict(opened: OpenedRecoveryVerdict): "authoritative" | "advisory";
43
+ confirmationKey({ position, commitDigest }: PendingRecoveryConfirmationKeyParams): Promise<Uint8Array<ArrayBufferLike>>;
44
+ judgeVerdict(opened: OpenedRecoveryVerdict): Promise<"authoritative" | "advisory">;
46
45
  };
package/lib/recovery.js CHANGED
@@ -1,24 +1,5 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
- import { assertRecoveryBinding, confirmationKey, confirmationTag, joinGroupExternal, LeafBindingError, LeafLapsedError, parseMLSCredentialIdentity, RevokeProofError, recoverySignerEligible } from '@kumiai/mls';
3
- export function knownRecoveryRegistry(known, reply) {
4
- const devices = new Map(reply.devices);
5
- for (const [did, record] of known.devices){
6
- if (record.status === 'revoked' || !devices.has(did)) devices.set(did, record);
7
- }
8
- const controllers = new Map(reply.controllers);
9
- for (const [id, projection] of known.controllers){
10
- const offered = controllers.get(id);
11
- controllers.set(id, offered == null ? projection : {
12
- ...offered,
13
- genFloor: Math.max(projection.genFloor, offered.genFloor),
14
- timeFloor: Math.max(projection.timeFloor, offered.timeFloor)
15
- });
16
- }
17
- return {
18
- devices,
19
- controllers
20
- };
21
- }
2
+ import { assertRecoveryBinding, assertRetainsKnownEffects, confirmationKey, confirmationTag, joinGroupExternal, LeafBindingError, LeafLapsedError, parseMLSCredentialIdentity, RevokeProofError, recoverySignerEligible } from '@kumiai/mls';
22
3
  export function createRecoveryBindingState(identity, host) {
23
4
  let binding;
24
5
  let asked = false;
@@ -28,7 +9,9 @@ export function createRecoveryBindingState(identity, host) {
28
9
  value.id,
29
10
  value.prefix,
30
11
  value.capability,
31
- value.holderGrant
12
+ value.holderGrant,
13
+ value.member,
14
+ value.iat
32
15
  ]);
33
16
  function markBindingUnusable(id) {
34
17
  if (id == null) return;
@@ -54,10 +37,15 @@ export function createRecoveryBindingState(identity, host) {
54
37
  }
55
38
  function current(group) {
56
39
  const leaf = group.bindingOfDID(identity.id);
57
- return leaf?.controller == null || leaf.prefix == null || leaf.capability == null ? undefined : {
40
+ return leaf?.controller == null || leaf.prefix == null ? undefined : {
58
41
  id: leaf.controller,
59
42
  prefix: leaf.prefix,
60
- capability: leaf.capability,
43
+ ...leaf.member == null ? {
44
+ capability: leaf.capability
45
+ } : {
46
+ member: leaf.member,
47
+ iat: leaf.iat
48
+ },
61
49
  ...leaf.holderGrant == null ? {} : {
62
50
  holderGrant: leaf.holderGrant
63
51
  }
@@ -90,6 +78,7 @@ export function createRecoveryBindingState(identity, host) {
90
78
  binding = current(group);
91
79
  }
92
80
  let signerEligible = group.anchor.controller == null;
81
+ let candidateSource;
93
82
  const build = (controller)=>{
94
83
  signerEligible = group.anchor.controller == null;
95
84
  return joinGroupExternal({
@@ -98,17 +87,25 @@ export function createRecoveryBindingState(identity, host) {
98
87
  credential: group.credential,
99
88
  resync: true,
100
89
  controller,
101
- beforeBinding: async (pending, source)=>{
90
+ beforeBinding: async ({ pending, source })=>{
102
91
  if (group.anchor.controller == null) return;
103
- if (!recoverySignerEligible({
92
+ await assertRetainsKnownEffects({
93
+ controller: group.anchor.controller,
94
+ known: group.registry,
95
+ candidate: source.registry,
96
+ crypto: group.crypto
97
+ });
98
+ if (!await recoverySignerEligible({
104
99
  group: pending,
105
- known: knownRecoveryRegistry(group.registry, source.registry),
100
+ registry: source.registry,
106
101
  signer: reply.signer
107
102
  })) throw new Error('Ineligible recovery attestation signer');
108
103
  signerEligible = true;
109
- if (controller == null || !await usable(group, controller)) throw new LeafBindingError('floating-refused');
104
+ candidateSource = source;
105
+ if (controller == null || !await usable(source, controller)) throw new LeafBindingError('floating-refused');
110
106
  },
111
107
  options: {
108
+ crypto: group.crypto,
112
109
  commitPolicy: group.commitPolicy,
113
110
  resolveLedgerEntries: group.resolveLedgerEntries,
114
111
  onLedgerEntries: group.onLedgerEntries
@@ -132,7 +129,7 @@ export function createRecoveryBindingState(identity, host) {
132
129
  } catch (error) {
133
130
  if (!signerEligible || group.anchor.controller == null || !(error instanceof LeafBindingError || error instanceof LeafLapsedError || error instanceof RevokeProofError)) return null;
134
131
  binding = await request(group);
135
- if (binding == null || !await usable(group, binding)) return {
132
+ if (binding == null || candidateSource == null || !await usable(candidateSource, binding)) return {
136
133
  renewalRequired: true
137
134
  };
138
135
  try {
@@ -151,23 +148,30 @@ export function createVerdictJudge(params) {
151
148
  const { group, sourceTree, known, requestID } = params;
152
149
  let tuple;
153
150
  return {
154
- async confirmationKey (position, commitDigest) {
151
+ async confirmationKey ({ position, commitDigest }) {
155
152
  if (tuple != null && (tuple.position !== position || tuple.commitDigest !== commitDigest)) throw new Error('Pending recovery already bound to another commit');
156
153
  tuple ??= {
157
154
  position,
158
155
  commitDigest
159
156
  };
160
- const key = await confirmationKey(group, position, commitDigest);
161
- tuple.tag = confirmationTag(key, requestID);
157
+ const key = await confirmationKey({
158
+ group,
159
+ position,
160
+ commitDigest
161
+ });
162
+ tuple.tag = confirmationTag({
163
+ key,
164
+ requestID
165
+ });
162
166
  return key;
163
167
  },
164
- judgeVerdict (opened) {
168
+ async judgeVerdict (opened) {
165
169
  const { signer, verdict } = opened;
166
170
  if (normalizeDID(signer) === normalizeDID(group.credential.id) || tuple == null || verdict.groupID !== group.groupID || verdict.requestID !== requestID || verdict.position !== tuple.position || verdict.commitDigest !== tuple.commitDigest) return 'advisory';
167
171
  if (verdict.verdict === 'confirmed' && (verdict.epoch !== Number(group.epoch) || verdict.tag !== tuple.tag)) return 'advisory';
168
- if (group.anchor.controller != null) return recoverySignerEligible({
172
+ if (group.anchor.controller != null) return await recoverySignerEligible({
169
173
  group,
170
- known,
174
+ registry: known,
171
175
  signer
172
176
  }) ? 'authoritative' : 'advisory';
173
177
  if (verdict.verdict === 'confirmed') return 'authoritative';
package/lib/revoke.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type GroupHandle, type RevokeBuildResult, type RevokeWithProofParams } from '@kumiai/mls';
1
+ import { type EffectClaim, type GroupHandle, type RevokeBuildResult, type RevokeProofInput } from '@kumiai/mls';
2
2
  import type { GroupMLS, GroupPeer, GroupProtocolDefinition } from '@kumiai/rpc';
3
3
  export type RevokeJournalOptions = {
4
4
  /** Must restore the derived handle INCLUDING its ledger through the host's adoptJournalled. */
@@ -7,13 +7,14 @@ export type RevokeJournalOptions = {
7
7
  export type PublishRevokeResult = {
8
8
  status: 'committed';
9
9
  epoch: number;
10
+ effects: Array<EffectClaim>;
10
11
  } | Exclude<RevokeBuildResult, {
11
12
  status: 'built';
12
13
  }>;
13
14
  export type PublishRevokeProofParams<Protocols extends Record<string, GroupProtocolDefinition>> = {
14
15
  peer: GroupPeer<Protocols>;
15
16
  mls: GroupMLS;
16
- input: RevokeWithProofParams;
17
+ input: RevokeProofInput;
17
18
  options: RevokeJournalOptions;
18
19
  };
19
20
  export declare function publishRevokeProof<Protocols extends Record<string, GroupProtocolDefinition>>(params: PublishRevokeProofParams<Protocols>): Promise<PublishRevokeResult>;
package/lib/revoke.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { revokeWithProof } from '@kumiai/mls';
2
+ import { guardedReplace } from './access.js';
2
3
  import { groupHandleAccess } from './mls.js';
3
4
  export async function publishRevokeProof(params) {
4
5
  const { peer, mls, input, options } = params;
@@ -7,34 +8,43 @@ export async function publishRevokeProof(params) {
7
8
  const finished = Symbol('proof needs no commit');
8
9
  let outcome;
9
10
  try {
10
- await peer.commit(async ()=>{
11
- const built = await access.read(async (group)=>{
12
- const result = await revokeWithProof(group, input);
13
- return {
14
- result,
15
- priorTokens: new Set(group.ledgerTokens)
16
- };
17
- });
18
- if (built.result.status !== 'built') {
19
- outcome = built.result;
20
- throw finished;
21
- }
22
- const { newGroup, commitMessage, epoch } = built.result.result;
23
- const journal = await options.serializeJournal(newGroup);
24
- return {
25
- commit: commitMessage,
26
- bodies: newGroup.ledgerTokens.filter((token)=>!built.priorTokens.has(token)),
27
- kind: 'ledger',
28
- journal,
29
- onAccepted: async ()=>{
30
- await access.replace(newGroup);
31
- outcome = {
32
- status: 'committed',
33
- epoch: Number(epoch)
11
+ await peer.commit({
12
+ build: async ()=>{
13
+ const built = await access.read(async (group)=>{
14
+ const result = await revokeWithProof({
15
+ group,
16
+ ...input
17
+ });
18
+ return {
19
+ result,
20
+ priorTokens: new Set(group.ledgerTokens)
34
21
  };
22
+ });
23
+ if (built.result.status !== 'built') {
24
+ outcome = built.result;
25
+ throw finished;
35
26
  }
36
- };
37
- }, {
27
+ const effects = built.result.effects;
28
+ const { newGroup, commitMessage, epoch } = built.result.result;
29
+ const journal = await options.serializeJournal(newGroup);
30
+ return {
31
+ commit: commitMessage,
32
+ bodies: newGroup.ledgerTokens.filter((token)=>!built.priorTokens.has(token)),
33
+ kind: 'ledger',
34
+ journal,
35
+ onAccepted: async ()=>{
36
+ await guardedReplace({
37
+ access,
38
+ next: newGroup
39
+ });
40
+ outcome = {
41
+ status: 'committed',
42
+ epoch: Number(epoch),
43
+ effects
44
+ };
45
+ }
46
+ };
47
+ },
38
48
  holdLogSends: true
39
49
  });
40
50
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/mls-rpc",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "The @kumiai/rpc consumer ports (GroupCrypto, GroupMLS) implemented over @kumiai/mls",
5
5
  "keywords": [
6
6
  "mls",
@@ -25,16 +25,16 @@
25
25
  "lib/*"
26
26
  ],
27
27
  "dependencies": {
28
- "@kokuin/token": "^0.6.1",
29
- "@kumiai/mls": "^0.11.0",
30
- "@kumiai/rpc": "^0.11.0",
28
+ "@kokuin/token": "^0.7.0",
29
+ "@kumiai/mls": "^0.13.0",
30
+ "@kumiai/rpc": "^0.13.0",
31
31
  "@noble/ciphers": "^2.4.0",
32
32
  "@sozai/runtime": "^0.1.0"
33
33
  },
34
34
  "devDependencies": {
35
- "@kumiai/rpc-conformance": "^0.11.0",
35
+ "@kumiai/rpc-conformance": "^0.13.0",
36
36
  "ts-mls": "2.0.0-rc.13",
37
- "vitest": "^5.0.5"
37
+ "vitest": "^5.1.0"
38
38
  },
39
39
  "publishConfig": {
40
40
  "access": "public"