@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/mls.js CHANGED
@@ -1,4 +1,7 @@
1
- import { createRecoveryRequest, encodeGroupAnchor, joinGroupExternal, MissingLedgerEntriesError, openSealedGroupInfo, openSealedLedger, sealGroupInfo, sealLedger } from '@kumiai/mls';
1
+ import { confirmationKey, createRecoveryRequest, encodeGroupAnchor, ledgerEntryDigest, MissingLedgerEntriesError, openRecoveryGroupInfo, openRecoveryVerdict, openSealedLedger, readCommitEntryIDs, readMessageEpoch, recoverySignerEligible, sealGroupInfo, sealLedger, sealRecoveryVerdict, verifyRecoveryRequest } from '@kumiai/mls';
2
+ import { applyCommit } from './apply-commit.js';
3
+ import { createRecoveryBindingState, createVerdictJudge, knownRecoveryRegistry } from './recovery.js';
4
+ export const groupHandleAccess = new WeakMap();
2
5
  const utf8 = new TextEncoder();
3
6
  /**
4
7
  * The label the non-rotating recovery secret is derived under. This secret is the root of
@@ -26,11 +29,59 @@ export function createLedgerEntrySlot() {
26
29
  }
27
30
  };
28
31
  }
32
+ /** Below this a topic secret is guessable; the default derives 32 bytes. */ const MIN_RECOVERY_SECRET_BYTES = 16;
29
33
  /**
30
34
  * How long a minted recovery request's private half is kept. The port makes retention the
31
35
  * implementation's problem — the lane has no release hook and drops its `requestID` on
32
36
  * timeout without saying so — so this bounds it off the mint time.
33
37
  */ const REQUEST_TTL_MS = 120_000;
38
+ export function createRecoveryPending(options) {
39
+ const ttlMS = options?.ttlMS ?? REQUEST_TTL_MS;
40
+ const requests = new Map();
41
+ const remove = (requestID, request)=>{
42
+ clearTimeout(request.timer);
43
+ request.ephemeralPrivateKey.fill(0);
44
+ requests.delete(requestID);
45
+ };
46
+ const sweep = ()=>{
47
+ const now = Date.now();
48
+ for (const [id, request] of requests){
49
+ if (request.expiresAt <= now) remove(id, request);
50
+ }
51
+ };
52
+ return {
53
+ get: (requestID)=>{
54
+ sweep();
55
+ return requests.get(requestID)?.ephemeralPrivateKey ?? null;
56
+ },
57
+ put: (requestID, ephemeralPrivateKey, deadlineMs = 0)=>{
58
+ const retentionMs = Math.max(ttlMS, deadlineMs);
59
+ sweep();
60
+ const previous = requests.get(requestID);
61
+ if (previous != null) remove(requestID, previous);
62
+ const timer = setTimeout(()=>{
63
+ const held = requests.get(requestID);
64
+ if (held?.ephemeralPrivateKey === ephemeralPrivateKey) remove(requestID, held);
65
+ }, retentionMs);
66
+ const nodeTimer = timer;
67
+ nodeTimer.unref?.();
68
+ requests.set(requestID, {
69
+ ephemeralPrivateKey,
70
+ expiresAt: Date.now() + retentionMs,
71
+ timer
72
+ });
73
+ },
74
+ delete: (requestID)=>{
75
+ sweep();
76
+ const request = requests.get(requestID);
77
+ if (request != null) remove(requestID, request);
78
+ }
79
+ };
80
+ }
81
+ export async function deriveRecoverySecret(handle) {
82
+ const { cipherSuite } = handle.context;
83
+ return await cipherSuite.kdf.expand(await cipherSuite.kdf.extract(utf8.encode(handle.groupID), encodeGroupAnchor(handle.anchor)), utf8.encode(RECOVERY_LABEL), 32);
84
+ }
34
85
  /**
35
86
  * {@link GroupMLS} over a live {@link GroupHandle} — the real lifecycle port.
36
87
  *
@@ -43,7 +94,7 @@ export function createLedgerEntrySlot() {
43
94
  * adopts it in `onAccepted`). A host that treated every commit as adopt-later would
44
95
  * double-apply received ones.
45
96
  *
46
- * 2. **`rosterDIDs` reads the ratchet tree, so a leaf with an unparsable credential is
97
+ * 2. **`rosterEntries` reads the ratchet tree, so a leaf with an unparsable credential is
47
98
  * simply absent** rather than present-with-a-placeholder. The double's roster is a set of
48
99
  * strings it was handed.
49
100
  *
@@ -56,20 +107,66 @@ export function createLedgerEntrySlot() {
56
107
  * topic is for (a stranded peer must be able to name it, and so must a removed one) but a
57
108
  * host must not put anything on it that confidentiality depends on.
58
109
  */ 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);
110
+ const { access, identity, entrySlot } = params;
111
+ const pending = createRecoveryPending();
112
+ const recovery = createRecoveryBindingState(identity, params.recoveryBinding);
113
+ const port = {
114
+ async verifyRecoveryRequest (request) {
115
+ try {
116
+ const verified = await verifyRecoveryRequest(new TextDecoder().decode(request));
117
+ return await access.read((group)=>verified.groupID === group.groupID ? {
118
+ groupID: verified.groupID,
119
+ requestID: verified.requestID,
120
+ requesterDID: verified.requesterDID
121
+ } : null);
122
+ } catch {
123
+ return null;
124
+ }
125
+ },
126
+ async confirmationKey (position, commitDigest) {
127
+ return await access.read(async (group)=>({
128
+ epoch: Number(group.epoch),
129
+ key: await confirmationKey(group, position, commitDigest)
130
+ }));
131
+ },
132
+ async sealRecoveryVerdict (request, verdict) {
133
+ return await access.read((group)=>sealRecoveryVerdict({
134
+ group,
135
+ identity,
136
+ request: new TextDecoder().decode(request),
137
+ verdict
138
+ }));
139
+ },
140
+ async openRecoveryVerdict (sealed, requestID) {
141
+ const held = pending.get(requestID);
142
+ if (held == null) return null;
143
+ try {
144
+ return await access.read((group)=>openRecoveryVerdict({
145
+ group,
146
+ sealed,
147
+ requestID,
148
+ ephemeralPrivateKey: held
149
+ }));
150
+ } catch {
151
+ return null;
152
+ }
153
+ },
154
+ async prepareRecovery () {
155
+ return await access.read((group)=>recovery.prepare(group));
156
+ },
157
+ async readEpoch () {
158
+ return await access.read((group)=>Number(group.epoch));
159
+ },
160
+ sendAdmission: ()=>access.admission(),
161
+ async rosterEntries () {
162
+ return await access.read((group)=>group.listMembers().map((member)=>({
163
+ did: member.id,
164
+ leafIndex: member.leafIndex,
165
+ longForm: member.longForm
166
+ })));
70
167
  },
71
168
  async readCommitHeader (commit) {
72
- const header = await handle().readCommitHeader(commit);
169
+ const header = await access.read((group)=>group.readCommitHeader(commit));
73
170
  if (header == null) return null;
74
171
  return {
75
172
  epoch: Number(header.epoch),
@@ -82,98 +179,162 @@ export function createLedgerEntrySlot() {
82
179
  };
83
180
  },
84
181
  async processCommit (commit, context) {
85
- const group = handle();
86
- const before = group.epoch;
87
- entrySlot.install(context.resolveLedgerEntries);
182
+ const frameEpoch = readMessageEpoch(commit);
183
+ const eligible = await access.read(async (group)=>{
184
+ const header = await group.readCommitHeader(commit);
185
+ return {
186
+ eligible: header != null && frameEpoch === group.epoch,
187
+ epoch: Number(group.epoch)
188
+ };
189
+ });
190
+ if (!eligible.eligible) {
191
+ return {
192
+ advanced: false,
193
+ epochBefore: eligible.epoch,
194
+ epochAfter: eligible.epoch
195
+ };
196
+ }
197
+ const ids = readCommitEntryIDs(commit);
198
+ const tokens = ids.length === 0 ? [] : await context.resolveLedgerEntries?.(ids);
199
+ const resolved = new Map();
200
+ for (const token of tokens ?? [])resolved.set(ledgerEntryDigest(token), token);
201
+ const ignored = Symbol('ignored commit');
202
+ let refusedEpoch;
203
+ let refusal;
88
204
  try {
89
- await group.processMessage(commit);
205
+ return await access.mutate(async (group, persist)=>{
206
+ if (group.epoch !== frameEpoch) {
207
+ // Moved while entries resolved: the caller re-classifies against the epoch it names.
208
+ refusedEpoch = Number(group.epoch);
209
+ throw ignored;
210
+ }
211
+ const result = await applyCommit({
212
+ ...context,
213
+ handle: group,
214
+ commit,
215
+ resolveLedgerEntries: async (requested)=>requested.flatMap((id)=>{
216
+ const token = resolved.get(id);
217
+ return token == null ? [] : [
218
+ token
219
+ ];
220
+ }),
221
+ entrySlot,
222
+ ownDID: identity.id,
223
+ persist
224
+ });
225
+ // Thrown so the adapter does not save a handle the commit left untouched.
226
+ if (!result.applied) {
227
+ refusedEpoch = result.epochBefore;
228
+ refusal = result.refusal;
229
+ throw ignored;
230
+ }
231
+ return {
232
+ advanced: result.advanced,
233
+ epochBefore: result.epochBefore,
234
+ epochAfter: result.epochAfter
235
+ };
236
+ });
90
237
  } 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
238
+ if (error === ignored && refusedEpoch != null) return {
239
+ advanced: false,
240
+ epochBefore: refusedEpoch,
241
+ epochAfter: refusedEpoch,
242
+ ...refusal == null ? {} : {
243
+ refusal
244
+ }
99
245
  };
100
- } finally{
101
- entrySlot.install(undefined);
246
+ throw error;
102
247
  }
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
248
  },
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
- });
249
+ async createRecoveryRequest (requestID, deadlineMs) {
250
+ const { request, ephemeralPrivateKey } = await access.read((group)=>createRecoveryRequest({
251
+ group,
252
+ identity,
253
+ requestID
254
+ }));
255
+ pending.put(requestID, ephemeralPrivateKey, Math.max(REQUEST_TTL_MS, deadlineMs ?? 0));
122
256
  return utf8.encode(request);
123
257
  },
124
258
  async sealGroupInfo (request) {
125
259
  // Throws for a request this member refuses — a removed requester holds no leaf in
126
260
  // 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
- });
261
+ return await access.read((group)=>sealGroupInfo({
262
+ group,
263
+ identity,
264
+ request: new TextDecoder().decode(request)
265
+ }));
132
266
  },
133
267
  async applyRecovery (sealed, requestID) {
134
268
  const held = pending.get(requestID);
135
269
  if (held == null) return null;
136
- let groupInfo;
270
+ let reply;
137
271
  try {
138
- groupInfo = await openSealedGroupInfo({
139
- group: handle(),
140
- sealed,
141
- requestID,
142
- ephemeralPrivateKey: held.ephemeralPrivateKey
143
- });
272
+ reply = await access.read((group)=>openRecoveryGroupInfo({
273
+ group,
274
+ sealed,
275
+ requestID,
276
+ ephemeralPrivateKey: held
277
+ }));
144
278
  } catch {
145
279
  // Bytes this peer cannot open OR cannot trust: a forged reply that merely decrypts
146
280
  // fails the membership attestation, and both are `null`.
147
281
  return null;
148
282
  }
149
- const rejoined = await joinGroupExternal({
150
- identity,
151
- groupInfo,
152
- credential: handle().credential,
153
- resync: true
283
+ const candidate = await access.read(async (group)=>{
284
+ const rejoined = await recovery.join(group, reply);
285
+ if (rejoined == null || 'renewalRequired' in rejoined) return rejoined;
286
+ return {
287
+ ...rejoined,
288
+ knownRegistry: knownRecoveryRegistry(group.registry, rejoined.sourceRegistry)
289
+ };
154
290
  });
155
- return {
291
+ if (candidate == null || 'renewalRequired' in candidate) return candidate;
292
+ const rejoined = candidate;
293
+ if (rejoined.group.anchor.controller != null && !recoverySignerEligible({
294
+ group: rejoined.group,
295
+ known: rejoined.knownRegistry,
296
+ signer: reply.signer
297
+ })) return null;
298
+ const judge = createVerdictJudge({
299
+ group: rejoined.group,
300
+ sourceTree: rejoined.sourceTree,
301
+ known: rejoined.knownRegistry,
302
+ requestID
303
+ });
304
+ let accepted;
305
+ const result = {
306
+ group: rejoined.group,
307
+ sourceTree: rejoined.sourceTree,
308
+ groupInfo: reply.groupInfo,
309
+ knownRegistry: rejoined.knownRegistry,
310
+ replyLedger: reply.ledger,
311
+ signer: reply.signer,
156
312
  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);
313
+ epoch: Number(rejoined.group.epoch),
314
+ markBindingUnusable: rejoined.markBindingUnusable,
315
+ confirmationKey: judge.confirmationKey,
316
+ judgeVerdict: judge.judgeVerdict,
317
+ onAccepted: ()=>{
318
+ accepted ??= access.replace(rejoined.group).catch((error)=>{
319
+ accepted = undefined;
320
+ throw error;
321
+ });
322
+ return accepted;
163
323
  }
164
324
  };
325
+ return result;
165
326
  },
166
327
  async isLedgerComplete () {
167
- return await handle().isLedgerComplete();
328
+ return await access.read((group)=>group.isLedgerComplete());
168
329
  },
169
330
  async getLedger () {
170
- return await handle().getLedger();
331
+ return await access.read((group)=>group.getLedger());
171
332
  },
172
333
  async sealLedger (request) {
173
- return await sealLedger({
174
- group: handle(),
175
- request: new TextDecoder().decode(request)
176
- });
334
+ return await access.read((group)=>sealLedger({
335
+ group,
336
+ request: new TextDecoder().decode(request)
337
+ }));
177
338
  },
178
339
  async openSealedLedger (sealed, requestID) {
179
340
  const held = pending.get(requestID);
@@ -181,12 +342,12 @@ export function createLedgerEntrySlot() {
181
342
  try {
182
343
  // The key is NOT consumed: every responder answers, and the requester must open the
183
344
  // next reply after dropping one.
184
- return await openSealedLedger({
185
- group: handle(),
186
- sealed,
187
- requestID,
188
- ephemeralPrivateKey: held.ephemeralPrivateKey
189
- });
345
+ return await access.read((group)=>openSealedLedger({
346
+ group,
347
+ sealed,
348
+ requestID,
349
+ ephemeralPrivateKey: held
350
+ }));
190
351
  } catch {
191
352
  return null;
192
353
  }
@@ -194,16 +355,33 @@ export function createLedgerEntrySlot() {
194
355
  async bootstrapLedger (tokens) {
195
356
  // Throws for a list whose recomputed head does not match the authenticated one — a
196
357
  // lying responder can withhold, never rewrite.
197
- await handle().bootstrapLedger(tokens);
198
- await persist?.(handle());
358
+ await access.mutate(async (group, persist)=>{
359
+ let persisted = false;
360
+ try {
361
+ await group.bootstrapLedger(tokens, {
362
+ persist: async (current)=>{
363
+ await persist(current);
364
+ persisted = true;
365
+ }
366
+ });
367
+ } catch (error) {
368
+ // A host callback after the write: the stored ledger is complete, so the adapter must
369
+ // still publish this handle.
370
+ if (!persisted) throw error;
371
+ }
372
+ });
199
373
  },
200
374
  async exportRecoverySecret () {
201
375
  // Epoch-INDEPENDENT by construction: the genesis anchor never changes, so a peer
202
376
  // stranded at any epoch derives the same rendezvous. See the class doc — this is not
203
377
  // 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);
378
+ const secret = await access.read(params.recoverySecret ?? deriveRecoverySecret);
379
+ if (!(secret instanceof Uint8Array) || secret.length < MIN_RECOVERY_SECRET_BYTES) {
380
+ throw new Error(`recoverySecret: expected at least ${MIN_RECOVERY_SECRET_BYTES} bytes from the host`);
381
+ }
382
+ return secret;
207
383
  }
208
384
  };
385
+ groupHandleAccess.set(port, access);
386
+ return port;
209
387
  }
@@ -0,0 +1,46 @@
1
+ import { type OwnIdentity } from '@kokuin/token';
2
+ import { type ClientState, type ControllerBinding, type DeviceRegistry, type GroupHandle } from '@kumiai/mls';
3
+ import type { OpenedRecoveryVerdict, PendingRecovery } from '@kumiai/rpc';
4
+ export type RecoveryBindingRequest = {
5
+ groupID: string;
6
+ controllerID: string;
7
+ current: ControllerBinding;
8
+ };
9
+ export type RecoveryBinding = (request: RecoveryBindingRequest) => Promise<ControllerBinding | null>;
10
+ export type RecoveryReply = {
11
+ groupInfo: Uint8Array;
12
+ ledger: Array<string>;
13
+ signer: string;
14
+ };
15
+ export type VerdictJudgeParams = {
16
+ group: GroupHandle;
17
+ sourceTree: ClientState['ratchetTree'];
18
+ known: DeviceRegistry;
19
+ requestID: string;
20
+ };
21
+ /** Retained with the speculative handle for subsequent signer judgement. */
22
+ export type RecoveryCandidate = PendingRecovery & {
23
+ group: GroupHandle;
24
+ sourceTree: ClientState['ratchetTree'];
25
+ groupInfo: Uint8Array;
26
+ knownRegistry: DeviceRegistry;
27
+ replyLedger: Array<string>;
28
+ signer: string;
29
+ };
30
+ export declare function knownRecoveryRegistry(known: DeviceRegistry, reply: DeviceRegistry): DeviceRegistry;
31
+ export declare function createRecoveryBindingState(identity: OwnIdentity, host?: RecoveryBinding): {
32
+ prepare(group: GroupHandle): Promise<"ready" | "renewal-required">;
33
+ join(group: GroupHandle, reply: RecoveryReply): Promise<{
34
+ markBindingUnusable: () => void;
35
+ commitMessage: Uint8Array;
36
+ group: GroupHandle;
37
+ sourceTree: ClientState["ratchetTree"];
38
+ sourceRegistry: DeviceRegistry;
39
+ } | {
40
+ readonly renewalRequired: true;
41
+ } | null>;
42
+ };
43
+ export declare function createVerdictJudge(params: VerdictJudgeParams): {
44
+ confirmationKey(position: string, commitDigest: string): Promise<Uint8Array<ArrayBufferLike>>;
45
+ judgeVerdict(opened: OpenedRecoveryVerdict): "authoritative" | "advisory";
46
+ };
@@ -0,0 +1,181 @@
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
+ }
22
+ export function createRecoveryBindingState(identity, host) {
23
+ let binding;
24
+ let asked = false;
25
+ let prepared = false;
26
+ const unusable = new Set();
27
+ const bindingID = (value)=>JSON.stringify([
28
+ value.id,
29
+ value.prefix,
30
+ value.capability
31
+ ]);
32
+ function markBindingUnusable(id) {
33
+ if (id == null) return;
34
+ unusable.delete(id);
35
+ unusable.add(id);
36
+ while(unusable.size > 16){
37
+ const oldest = unusable.values().next().value;
38
+ if (oldest != null) unusable.delete(oldest);
39
+ }
40
+ }
41
+ async function usable(group, candidate) {
42
+ if (unusable.has(bindingID(candidate))) return false;
43
+ try {
44
+ await assertRecoveryBinding({
45
+ group,
46
+ identity,
47
+ controller: candidate
48
+ });
49
+ return true;
50
+ } catch {
51
+ return false;
52
+ }
53
+ }
54
+ function current(group) {
55
+ const leaf = group.bindingOfDID(identity.id);
56
+ return leaf?.controller == null || leaf.prefix == null || leaf.capability == null ? undefined : {
57
+ id: leaf.controller,
58
+ prefix: leaf.prefix,
59
+ capability: leaf.capability
60
+ };
61
+ }
62
+ async function request(group) {
63
+ if (asked) return undefined;
64
+ asked = true;
65
+ const held = current(group);
66
+ if (host == null || held == null || group.anchor.controller == null) return undefined;
67
+ return await host({
68
+ groupID: group.groupID,
69
+ controllerID: group.anchor.controller,
70
+ current: held
71
+ }) ?? undefined;
72
+ }
73
+ return {
74
+ async prepare (group) {
75
+ asked = false;
76
+ prepared = true;
77
+ binding = current(group);
78
+ if (group.anchor.controller == null) return 'ready';
79
+ if (binding != null && await usable(group, binding)) return 'ready';
80
+ binding = await request(group);
81
+ return binding != null && await usable(group, binding) ? 'ready' : 'renewal-required';
82
+ },
83
+ async join (group, reply) {
84
+ if (!prepared) {
85
+ prepared = true;
86
+ binding = current(group);
87
+ }
88
+ let signerEligible = group.anchor.controller == null;
89
+ const build = (controller)=>{
90
+ signerEligible = group.anchor.controller == null;
91
+ return joinGroupExternal({
92
+ identity,
93
+ groupInfo: reply.groupInfo,
94
+ credential: group.credential,
95
+ resync: true,
96
+ controller,
97
+ beforeBinding: async (pending, source)=>{
98
+ if (group.anchor.controller == null) return;
99
+ if (!recoverySignerEligible({
100
+ group: pending,
101
+ known: knownRecoveryRegistry(group.registry, source.registry),
102
+ signer: reply.signer
103
+ })) throw new Error('Ineligible recovery attestation signer');
104
+ signerEligible = true;
105
+ if (controller == null || !await usable(group, controller)) throw new LeafBindingError('floating-refused');
106
+ },
107
+ options: {
108
+ commitPolicy: group.commitPolicy,
109
+ resolveLedgerEntries: group.resolveLedgerEntries,
110
+ onLedgerEntries: group.onLedgerEntries
111
+ },
112
+ ...group.anchor.controller == null ? {} : {
113
+ ledgerEntries: reply.ledger
114
+ }
115
+ });
116
+ };
117
+ const candidate = async (controller)=>{
118
+ const result = await build(controller);
119
+ const carried = current(result.group);
120
+ const id = carried == null ? undefined : bindingID(carried);
121
+ return {
122
+ ...result,
123
+ markBindingUnusable: ()=>markBindingUnusable(id)
124
+ };
125
+ };
126
+ try {
127
+ return await candidate(binding);
128
+ } catch (error) {
129
+ if (!signerEligible || group.anchor.controller == null || !(error instanceof LeafBindingError || error instanceof LeafLapsedError || error instanceof RevokeProofError)) return null;
130
+ binding = await request(group);
131
+ if (binding == null || !await usable(group, binding)) return {
132
+ renewalRequired: true
133
+ };
134
+ try {
135
+ return await candidate(binding);
136
+ } catch (replacementError) {
137
+ if (!signerEligible) return null;
138
+ return replacementError instanceof LeafBindingError || replacementError instanceof LeafLapsedError || replacementError instanceof RevokeProofError ? {
139
+ renewalRequired: true
140
+ } : null;
141
+ }
142
+ }
143
+ }
144
+ };
145
+ }
146
+ export function createVerdictJudge(params) {
147
+ const { group, sourceTree, known, requestID } = params;
148
+ let tuple;
149
+ return {
150
+ async confirmationKey (position, commitDigest) {
151
+ if (tuple != null && (tuple.position !== position || tuple.commitDigest !== commitDigest)) throw new Error('Pending recovery already bound to another commit');
152
+ tuple ??= {
153
+ position,
154
+ commitDigest
155
+ };
156
+ const key = await confirmationKey(group, position, commitDigest);
157
+ tuple.tag = confirmationTag(key, requestID);
158
+ return key;
159
+ },
160
+ judgeVerdict (opened) {
161
+ const { signer, verdict } = opened;
162
+ 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';
163
+ if (verdict.verdict === 'confirmed' && (verdict.epoch !== Number(group.epoch) || verdict.tag !== tuple.tag)) return 'advisory';
164
+ if (group.anchor.controller != null) return recoverySignerEligible({
165
+ group,
166
+ known,
167
+ signer
168
+ }) ? 'authoritative' : 'advisory';
169
+ if (verdict.verdict === 'confirmed') return 'authoritative';
170
+ for (const node of sourceTree){
171
+ if (node == null || !('leaf' in node)) continue;
172
+ const credential = node.leaf.credential;
173
+ if (!('identity' in credential)) continue;
174
+ try {
175
+ if (normalizeDID(parseMLSCredentialIdentity(credential.identity).id) === normalizeDID(signer)) return 'authoritative';
176
+ } catch {}
177
+ }
178
+ return 'advisory';
179
+ }
180
+ };
181
+ }