@fleetmesh/leaf 0.0.0-stage → 0.1.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.
Files changed (59) hide show
  1. package/README.md +103 -2
  2. package/dist/constants.d.ts +27 -0
  3. package/dist/constants.js +32 -0
  4. package/dist/descriptor.d.ts +29 -0
  5. package/dist/descriptor.js +73 -0
  6. package/dist/did.d.ts +59 -0
  7. package/dist/did.js +221 -0
  8. package/dist/didcomm.d.ts +59 -0
  9. package/dist/didcomm.js +176 -0
  10. package/dist/encoding.d.ts +14 -0
  11. package/dist/encoding.js +68 -0
  12. package/dist/event.d.ts +22 -0
  13. package/dist/event.js +42 -0
  14. package/dist/giftwrap.d.ts +29 -0
  15. package/dist/giftwrap.js +100 -0
  16. package/dist/index.d.ts +17 -0
  17. package/dist/index.js +20 -0
  18. package/dist/keys.d.ts +6 -0
  19. package/dist/keys.js +31 -0
  20. package/dist/mediation/leaf.d.ts +121 -0
  21. package/dist/mediation/leaf.js +238 -0
  22. package/dist/mediation/messages.d.ts +96 -0
  23. package/dist/mediation/messages.js +79 -0
  24. package/dist/negentropy.d.ts +81 -0
  25. package/dist/negentropy.js +352 -0
  26. package/dist/nip44.d.ts +18 -0
  27. package/dist/nip44.js +119 -0
  28. package/dist/pwa/browser-leaf.d.ts +15 -0
  29. package/dist/pwa/browser-leaf.js +91 -0
  30. package/dist/pwa/hub.d.ts +51 -0
  31. package/dist/pwa/hub.js +137 -0
  32. package/dist/pwa/store.d.ts +39 -0
  33. package/dist/pwa/store.js +157 -0
  34. package/dist/relay.d.ts +67 -0
  35. package/dist/relay.js +232 -0
  36. package/dist/seal.d.ts +56 -0
  37. package/dist/seal.js +146 -0
  38. package/dist/session.d.ts +75 -0
  39. package/dist/session.js +230 -0
  40. package/package.json +45 -4
  41. package/src/constants.ts +36 -0
  42. package/src/descriptor.ts +88 -0
  43. package/src/did.ts +222 -0
  44. package/src/didcomm.ts +196 -0
  45. package/src/encoding.ts +67 -0
  46. package/src/event.ts +56 -0
  47. package/src/giftwrap.ts +108 -0
  48. package/src/index.ts +20 -0
  49. package/src/keys.ts +33 -0
  50. package/src/mediation/leaf.ts +292 -0
  51. package/src/mediation/messages.ts +124 -0
  52. package/src/negentropy.ts +357 -0
  53. package/src/nip44.ts +110 -0
  54. package/src/pwa/browser-leaf.ts +99 -0
  55. package/src/pwa/hub.ts +173 -0
  56. package/src/pwa/store.ts +173 -0
  57. package/src/relay.ts +273 -0
  58. package/src/seal.ts +154 -0
  59. package/src/session.ts +255 -0
package/src/seal.ts ADDED
@@ -0,0 +1,154 @@
1
+ // What a DIDComm message becomes on a relay, both ways, by the rules
2
+ // meshnode's relay rung keeps (node/transport/relay_rung/{wire,outbound,
3
+ // inbound}.py and node/transport/didcomm_inbound.py):
4
+ //
5
+ // out message -> authcrypt JWE to the peer's #agree key -> fragments when
6
+ // the JWE is over FRAGMENT_BYTES -> each a NIP-59 gift wrap to the
7
+ // peer's node key, kind 21059 (live) or 1059 (stored).
8
+ // in wrap -> unwrap (the seal signer is the sender) -> reassemble ->
9
+ // decrypt with this leaf's #agree key -> the three names must agree:
10
+ // the plaintext `from`, the authcrypt skid, and the seal signer.
11
+ //
12
+ // Anoncrypt opens too, unauthenticated: it is what first contact is, and the
13
+ // caller decides whether an unproven sender is worth reading.
14
+ import { randomBytes } from '@noble/curves/utils.js';
15
+ import * as didcomm from './didcomm.ts';
16
+ import { bytesToHex, canonicalJson, isHex } from './encoding.ts';
17
+ import type { NostrEvent } from './event.ts';
18
+ import { unwrap, WRAP_LIVE, WRAP_STORED, wrap } from './giftwrap.ts';
19
+
20
+ export const FRAGMENT_BYTES = 24000;
21
+ export const MAX_FRAGMENTS = 64;
22
+ export const ENVELOPE_MAX = FRAGMENT_BYTES * MAX_FRAGMENTS;
23
+ export const PARTIALS_PER_SENDER = 4;
24
+ export const PARTIALS_MAX = 64;
25
+ export const PARTIAL_TTL_SECONDS = 600;
26
+ export const EMPTY_TYPE = 'https://didcomm.org/empty/1.0/empty';
27
+
28
+ export class SealError extends Error {}
29
+
30
+ export interface LeafSecrets { nodeSk: string; agreementSk: Uint8Array }
31
+ export interface PeerKeys { pubkey: string; agreementPub: Uint8Array }
32
+
33
+ export interface Fragment { frag: string; i: number; n: number; data: string }
34
+
35
+ /** The JWE itself when it fits a wrap, else its pieces under one fragment id. */
36
+ export function fragments(jwe: didcomm.JWE): (didcomm.JWE | Fragment)[] {
37
+ const text = canonicalJson(jwe);
38
+ if (text.length <= FRAGMENT_BYTES) return [jwe];
39
+ if (text.length > ENVELOPE_MAX) {
40
+ throw new SealError(`an envelope of ${text.length} bytes needs ${Math.ceil(text.length / FRAGMENT_BYTES)} fragments and the receiver refuses more than ${MAX_FRAGMENTS}; send less in one message`);
41
+ }
42
+ const frag = bytesToHex(randomBytes(8));
43
+ const parts: string[] = [];
44
+ for (let i = 0; i < text.length; i += FRAGMENT_BYTES) parts.push(text.slice(i, i + FRAGMENT_BYTES));
45
+ return parts.map((data, i) => ({ frag, i, n: parts.length, data }));
46
+ }
47
+
48
+ export interface SealOptions { stored?: boolean; now?: number }
49
+
50
+ /** Address, encrypt and wrap one message to a peer: the wraps to publish, in order. */
51
+ export function seal(message: Record<string, unknown>, me: LeafSecrets & { pubkey: string }, to: PeerKeys,
52
+ opts: SealOptions = {}): NostrEvent[] {
53
+ const now = opts.now ?? Math.floor(Date.now() / 1000);
54
+ const msg: Record<string, unknown> = { ...message };
55
+ msg.from ??= 'did:nostr:' + me.pubkey;
56
+ msg.to ??= ['did:nostr:' + to.pubkey];
57
+ msg.created_time ??= now;
58
+ if (opts.stored && typeof msg.id === 'string') msg.please_ack = [''];
59
+ const jwe = didcomm.encrypt(msg, [['did:nostr:' + to.pubkey + '#agree', to.agreementPub]], {
60
+ sender: ['did:nostr:' + me.pubkey + '#agree', me.agreementSk],
61
+ });
62
+ const kind = opts.stored ? WRAP_STORED : WRAP_LIVE;
63
+ return fragments(jwe).map((p) => wrap(p, me.nodeSk, to.pubkey, now, { kind }));
64
+ }
65
+
66
+ export interface Opened {
67
+ message: Record<string, any>;
68
+ /** The x-only key of whoever sealed it. */
69
+ sender: string;
70
+ /** True for authcrypt: the agreement proved the sender. False for anoncrypt. */
71
+ authenticated: boolean;
72
+ wrapId: string;
73
+ }
74
+
75
+ const pubkeyOfDid = (name: unknown): string | null => {
76
+ if (typeof name !== 'string' || !name.startsWith('did:nostr:')) return null;
77
+ const pk = name.slice('did:nostr:'.length).split('#', 1)[0]!.toLowerCase();
78
+ return isHex(pk, 64) ? pk : null;
79
+ };
80
+
81
+ /** Collects fragments by (sender, fragment id), bounded as the anchor bounds them. */
82
+ export class Reassembler {
83
+ private readonly partials = new Map<string, { n: number; parts: Map<number, string>; at: number }>();
84
+
85
+ /** The whole JWE once every fragment has arrived; null while waiting. */
86
+ add(frag: Fragment, sender: string, now: number): unknown | null {
87
+ const { frag: fid, i, n, data } = frag;
88
+ if (!Number.isInteger(n) || !Number.isInteger(i) || !(n > 0 && n <= MAX_FRAGMENTS && i >= 0 && i < n)) throw new SealError('fragment out of range');
89
+ if (typeof fid !== 'string' || fid.length > 64 || typeof data !== 'string' || data.length > FRAGMENT_BYTES + 16) throw new SealError('fragment out of range');
90
+ for (const [k, v] of this.partials) if (now - v.at > PARTIAL_TTL_SECONDS) this.partials.delete(k);
91
+ const key = sender + ' ' + fid;
92
+ let p = this.partials.get(key);
93
+ if (!p) {
94
+ const mine = [...this.partials.keys()].filter((k) => k.startsWith(sender + ' ')).length;
95
+ if (mine >= PARTIALS_PER_SENDER || this.partials.size >= PARTIALS_MAX) throw new SealError('fragment: too many unfinished envelopes');
96
+ p = { n, parts: new Map(), at: now };
97
+ this.partials.set(key, p);
98
+ }
99
+ if (p.n !== n) {
100
+ this.partials.delete(key);
101
+ throw new SealError('fragment: count changed mid-envelope');
102
+ }
103
+ p.parts.set(i, data);
104
+ if (p.parts.size < n) return null;
105
+ this.partials.delete(key);
106
+ try {
107
+ return JSON.parse(Array.from({ length: n }, (_, k) => p.parts.get(k)).join(''));
108
+ } catch {
109
+ throw new SealError('reassembled fragments are not JSON');
110
+ }
111
+ }
112
+ }
113
+
114
+ /** Open one wrap addressed to this leaf. Null while a fragmented envelope is
115
+ * incomplete; throws with the reason for anything refused.
116
+ * resolveAgreement maps a sender's node key to its X25519 key (from its
117
+ * descriptor); a sender it cannot resolve cannot be authenticated. */
118
+ export function open(wrapEvent: NostrEvent, me: LeafSecrets & { pubkey: string },
119
+ resolveAgreement: (pubkey: string) => Uint8Array | null | undefined, reassembler: Reassembler, now?: number): Opened | null {
120
+ let payload: unknown, sealPk: string;
121
+ try {
122
+ [payload, sealPk] = unwrap(wrapEvent, me.nodeSk, now);
123
+ } catch (e) {
124
+ throw new SealError('wrap: ' + (e as Error).message);
125
+ }
126
+ if (payload && typeof payload === 'object' && 'frag' in payload) {
127
+ const whole = reassembler.add(payload as Fragment, sealPk, now ?? Math.floor(Date.now() / 1000));
128
+ if (whole === null) return null;
129
+ payload = whole;
130
+ }
131
+ if (!payload || typeof payload !== 'object' || !('protected' in payload) || !('recipients' in payload)) {
132
+ const t = (payload as { type?: unknown } | null)?.type;
133
+ throw new SealError(typeof t === 'string' ? 'another protocol: ' + t.slice(0, 80) : 'payload is not a JWE');
134
+ }
135
+ let message: any, skid: string | null;
136
+ try {
137
+ [message, skid] = didcomm.decrypt(payload as didcomm.JWE, 'did:nostr:' + me.pubkey + '#agree', me.agreementSk, (kid) =>
138
+ kid.endsWith('#agree') ? resolveAgreement(pubkeyOfDid(kid) ?? '') : null);
139
+ } catch (e) {
140
+ throw new SealError('envelope: ' + (e as Error).message);
141
+ }
142
+ if (!message || typeof message !== 'object' || typeof message.type !== 'string' || typeof message.id !== 'string')
143
+ throw new SealError('plaintext is not a DIDComm message');
144
+ const claimed = pubkeyOfDid(message.from);
145
+ if (claimed === null) throw new SealError('from is not a did:nostr');
146
+ if (claimed !== sealPk) throw new SealError(`from ${claimed.slice(0, 8)} does not match the seal signer ${sealPk.slice(0, 8)}`);
147
+ if (skid !== null) {
148
+ const signer = pubkeyOfDid(skid);
149
+ if (signer === null) throw new SealError('skid is not a did:nostr');
150
+ if (signer !== sealPk) throw new SealError('skid does not match the seal signer');
151
+ }
152
+ if (message.thid !== undefined && typeof message.thid !== 'string') throw new SealError('thid is not a string');
153
+ return { message, sender: sealPk, authenticated: skid !== null, wrapId: wrapEvent.id };
154
+ }
package/src/session.ts ADDED
@@ -0,0 +1,255 @@
1
+ // A leaf's session with its mediator: the one wss:// connection the leaf
2
+ // profile allows, and everything said over it.
3
+ //
4
+ // start() connect (answering AUTH), learn the mediator's
5
+ // agreement key from its descriptor, publish this
6
+ // leaf's descriptor so the anchor can authenticate it,
7
+ // and subscribe for wraps addressed to this leaf -
8
+ // before anything is sent, because replies are kind
9
+ // 21059 and a relay keeps none of them.
10
+ // requestMediation() mediate-request, answered by grant or deny.
11
+ // updateKeylist() keylist-update, answered by keylist-update-response.
12
+ // pickup() delivery-request per registered key, opened and
13
+ // acked, until the inbox is empty.
14
+ //
15
+ // A phone's socket dies on screen lock. Nothing here survives that except
16
+ // the grant and keylist; resume() reconnects and resubscribes, and the next
17
+ // pickup() catches up. Messages the anchor stored as kind 1059 are replayed
18
+ // by the relay inside the subscription's two-day window.
19
+ import { agreementOf, buildLeafDescriptor, KIND as DESCRIPTOR_KIND } from './descriptor.ts';
20
+ import { agreementPublic } from './didcomm.ts';
21
+ import { type NostrEvent, pubkeyOf, signEvent, verifyEvent } from './event.ts';
22
+ import { TWO_DAYS, WRAP_LIVE, WRAP_STORED } from './giftwrap.ts';
23
+ import { LeafClient, type LeafClientState, type OpenedDelivery } from './mediation/leaf.ts';
24
+ import { type Message, PICKUP_LIMIT_DEFAULT } from './mediation/messages.ts';
25
+ import { authEvent, RelayConnection, type SocketFactory, type Subscription } from './relay.ts';
26
+ import { EMPTY_TYPE, open, type Opened, Reassembler, seal } from './seal.ts';
27
+
28
+ export class SessionError extends Error {}
29
+
30
+ export interface LeafSessionOptions {
31
+ /** The leaf's node key (secp256k1, hex) and agreement key (X25519, raw). */
32
+ nodeSk: string;
33
+ agreementSk: Uint8Array;
34
+ /** The mediator: its node key and the wss:// endpoint its relay face serves. */
35
+ mediator: { pubkey: string; endpoint: string; descriptor?: NostrEvent };
36
+ socket?: SocketFactory;
37
+ clock?: () => number;
38
+ timeoutMs?: number;
39
+ /** Fields for this leaf's own descriptor. */
40
+ operator?: string;
41
+ powBits?: number;
42
+ /** Grants and keylists from a previous launch (LeafClient.snapshot()). */
43
+ state?: LeafClientState;
44
+ /** Called with a fresh snapshot whenever a grant or keylist changes. */
45
+ onState?: (state: LeafClientState) => void;
46
+ /** Messages nobody was waiting for: unsolicited traffic from the mediator. */
47
+ onMessage?: (m: Opened) => void;
48
+ /** Wraps that did not open, with why. Nothing else reports them. */
49
+ onDrop?: (why: string, wrapId: string) => void;
50
+ }
51
+
52
+ const SEEN_MAX = 4096;
53
+
54
+ export class LeafSession {
55
+ readonly pubkey: string;
56
+ readonly client: LeafClient;
57
+ readonly mediatorDid: string;
58
+ private readonly opts: LeafSessionOptions;
59
+ private readonly clock: () => number;
60
+ private relay: RelayConnection;
61
+ private sub: Subscription | null = null;
62
+ private mediatorAgreement: Uint8Array | null = null;
63
+ private descriptor: NostrEvent | null = null;
64
+ private readonly waiters = new Map<string, (m: Opened) => void>();
65
+ private readonly seen = new Set<string>();
66
+ private readonly reassembler = new Reassembler();
67
+
68
+ constructor(opts: LeafSessionOptions) {
69
+ this.opts = opts;
70
+ this.clock = opts.clock ?? (() => Math.floor(Date.now() / 1000));
71
+ this.pubkey = pubkeyOf(opts.nodeSk);
72
+ this.mediatorDid = 'did:nostr:' + opts.mediator.pubkey;
73
+ this.client = new LeafClient({ nodePk: this.pubkey, agreementSk: opts.agreementSk }, this.clock);
74
+ if (opts.state) this.client.restore(opts.state);
75
+ this.relay = this.newRelay();
76
+ }
77
+
78
+ private newRelay(): RelayConnection {
79
+ return new RelayConnection(this.opts.mediator.endpoint, {
80
+ ...(this.opts.socket ? { socket: this.opts.socket } : {}),
81
+ timeoutMs: this.timeout,
82
+ signAuth: (challenge, url) => authEvent((at, k, t, c) => signEvent(this.opts.nodeSk, at, k, t, c), challenge, url, this.clock()),
83
+ });
84
+ }
85
+
86
+ private get timeout(): number {
87
+ return this.opts.timeoutMs ?? 10000;
88
+ }
89
+
90
+ get connected(): boolean {
91
+ return this.relay.connected && this.sub !== null;
92
+ }
93
+
94
+ /** The mediator's agreement key, from a descriptor it signed and that is live. */
95
+ private async learnMediator(): Promise<Uint8Array> {
96
+ const now = this.clock();
97
+ const live = (d: NostrEvent) => d.kind === DESCRIPTOR_KIND && d.pubkey === this.opts.mediator.pubkey && verifyEvent(d)
98
+ && !d.tags.some((t) => t[0] === 'expiration' && /^\d+$/.test(t[1] ?? '') && +t[1]! <= now);
99
+ let desc = this.opts.mediator.descriptor && live(this.opts.mediator.descriptor) ? this.opts.mediator.descriptor : null;
100
+ if (!desc) {
101
+ const found: NostrEvent[] = [];
102
+ const sub = this.relay.subscribe([{ kinds: [DESCRIPTOR_KIND], authors: [this.opts.mediator.pubkey] }], (ev) => found.push(ev));
103
+ await this.within(sub.eose, 'the mediator\'s descriptor');
104
+ sub.close();
105
+ desc = found.filter(live).sort((a, b) => b.created_at - a.created_at)[0] ?? null;
106
+ }
107
+ const agree = desc ? agreementOf(desc) : null;
108
+ if (!agree) throw new SessionError('no live descriptor with an agreement key for the mediator ' + this.opts.mediator.pubkey.slice(0, 16));
109
+ return agree;
110
+ }
111
+
112
+ private within<T>(p: Promise<T>, what: string): Promise<T> {
113
+ return new Promise<T>((resolve, reject) => {
114
+ const t = setTimeout(() => reject(new SessionError(`no answer for ${what} in ${this.timeout}ms`)), this.timeout);
115
+ p.then((v) => { clearTimeout(t); resolve(v); }, (e) => { clearTimeout(t); reject(e); });
116
+ });
117
+ }
118
+
119
+ /** Connect, learn the mediator, publish this leaf's descriptor, listen. */
120
+ async start(): Promise<void> {
121
+ await this.relay.connect();
122
+ this.mediatorAgreement ??= await this.learnMediator();
123
+ await this.publishDescriptor();
124
+ await this.listen();
125
+ }
126
+
127
+ /** After the socket died: a fresh connection and subscription, and a new
128
+ * descriptor only if the old one is close to expiring. */
129
+ async resume(): Promise<void> {
130
+ this.sub = null;
131
+ this.relay.close();
132
+ this.relay = this.newRelay();
133
+ await this.relay.connect();
134
+ this.mediatorAgreement ??= await this.learnMediator();
135
+ const exp = Number(this.descriptor?.tags.find((t) => t[0] === 'expiration')?.[1] ?? 0);
136
+ if (exp - this.clock() < 3600) await this.publishDescriptor();
137
+ await this.listen();
138
+ }
139
+
140
+ close(): void {
141
+ this.sub?.close();
142
+ this.sub = null;
143
+ this.relay.close();
144
+ }
145
+
146
+ private async publishDescriptor(): Promise<void> {
147
+ const d = buildLeafDescriptor(this.opts.nodeSk, {
148
+ agreementPub: agreementPublic(this.opts.agreementSk),
149
+ mediators: [this.mediatorDid],
150
+ now: this.clock(),
151
+ ...(this.opts.operator ? { operator: this.opts.operator } : {}),
152
+ ...(this.opts.powBits ? { powBits: this.opts.powBits } : {}),
153
+ });
154
+ const r = await this.relay.publish(d);
155
+ if (!r.ok) throw new SessionError('the mediator\'s relay refused this leaf\'s descriptor: ' + r.message);
156
+ this.descriptor = d;
157
+ }
158
+
159
+ private async listen(): Promise<void> {
160
+ const filter = { kinds: [WRAP_LIVE, WRAP_STORED], '#p': [this.pubkey], since: this.clock() - TWO_DAYS };
161
+ const sub = this.relay.subscribe([filter], (ev) => this.onWrap(ev));
162
+ await this.within(sub.eose, 'the subscription');
163
+ this.sub = sub;
164
+ void sub.closed.then(() => { if (this.sub === sub) this.sub = null; });
165
+ }
166
+
167
+ private onWrap(ev: NostrEvent): void {
168
+ if (!ev || typeof ev.id !== 'string' || this.seen.has(ev.id)) return;
169
+ this.seen.add(ev.id);
170
+ if (this.seen.size > SEEN_MAX) this.seen.delete(this.seen.values().next().value!);
171
+ let opened: Opened | null;
172
+ try {
173
+ opened = open(ev, { nodeSk: this.opts.nodeSk, agreementSk: this.opts.agreementSk, pubkey: this.pubkey },
174
+ (pk) => (pk === this.opts.mediator.pubkey ? this.mediatorAgreement : null), this.reassembler, this.clock());
175
+ } catch (e) {
176
+ this.opts.onDrop?.((e as Error).message, ev.id);
177
+ return;
178
+ }
179
+ if (!opened) return; // more fragments to come
180
+ const m = opened.message;
181
+ if (Array.isArray(m.please_ack) && (m.please_ack.includes('') || m.please_ack.includes(m.id)) && m.type !== EMPTY_TYPE)
182
+ void this.send({ id: 'ack-' + m.id, type: EMPTY_TYPE, ack: [m.id], body: {} }).catch(() => {});
183
+ if (m.type === EMPTY_TYPE) return;
184
+ const waiter = typeof m.thid === 'string' ? this.waiters.get(m.thid) : undefined;
185
+ if (waiter && opened.authenticated && opened.sender === this.opts.mediator.pubkey) {
186
+ this.waiters.delete(m.thid);
187
+ waiter(opened);
188
+ } else this.opts.onMessage?.(opened);
189
+ }
190
+
191
+ /** Seal and publish; throws if the relay took none of the wraps. */
192
+ private async send(msg: Record<string, unknown>): Promise<void> {
193
+ if (!this.mediatorAgreement) throw new SessionError('start() first');
194
+ const wraps = seal(msg, { nodeSk: this.opts.nodeSk, agreementSk: this.opts.agreementSk, pubkey: this.pubkey },
195
+ { pubkey: this.opts.mediator.pubkey, agreementPub: this.mediatorAgreement }, { now: this.clock() });
196
+ for (const w of wraps) {
197
+ const r = await this.relay.publish(w);
198
+ if (!r.ok) throw new SessionError('the mediator\'s relay refused a wrap: ' + r.message);
199
+ }
200
+ }
201
+
202
+ /** Send a message and wait for the mediator's answer on its thread. */
203
+ private async request(msg: Message<any>): Promise<Message<any>> {
204
+ if (!this.connected) throw new SessionError('not connected; start() or resume() first');
205
+ const answer = new Promise<Opened>((resolve) => this.waiters.set(msg.id, resolve));
206
+ try {
207
+ await this.send(msg as unknown as Record<string, unknown>);
208
+ return (await this.within(answer, msg.type.split('/').pop()!)).message as Message<any>;
209
+ } finally {
210
+ this.waiters.delete(msg.id);
211
+ }
212
+ }
213
+
214
+ async requestMediation(): Promise<'granted' | 'denied'> {
215
+ const reply = await this.request(this.client.buildMediateRequest(this.mediatorDid));
216
+ const r = this.client.recordMediationResponse(reply);
217
+ this.opts.onState?.(this.client.snapshot());
218
+ return r;
219
+ }
220
+
221
+ async updateKeylist(add: string[] = [], remove: string[] = []) {
222
+ const reply = await this.request(this.client.buildKeylistUpdate(this.mediatorDid, add, remove));
223
+ const r = this.client.recordKeylistUpdateResponse(reply);
224
+ this.opts.onState?.(this.client.snapshot());
225
+ return r;
226
+ }
227
+
228
+ /** Drain every registered key until the mediator has nothing left, acking
229
+ * each batch so it purges what was taken. maxRounds bounds a mediator that
230
+ * keeps returning the same batch. */
231
+ async pickup(opts: { limit?: number; maxRounds?: number; resolveSender?: (skid: string) => Uint8Array | null | undefined } = {}): Promise<OpenedDelivery[]> {
232
+ const limit = opts.limit ?? PICKUP_LIMIT_DEFAULT, maxRounds = opts.maxRounds ?? 50;
233
+ // The mediator's own key is always known here, so messages it authcrypts
234
+ // itself open; anyone else needs the caller's resolver.
235
+ const mediatorKid = this.mediatorDid + '#agree';
236
+ const resolve = (skid: string) => (skid === mediatorKid ? this.mediatorAgreement : opts.resolveSender?.(skid));
237
+ const out: OpenedDelivery[] = [];
238
+ const taken = new Set<string>();
239
+ for (const first of this.client.buildDeliveryRequests(this.mediatorDid, limit)) {
240
+ let req = first;
241
+ for (let round = 0; round < maxRounds; round++) {
242
+ const batch = this.client.openDelivery(await this.request(req), resolve).filter((d) => !taken.has(d.id));
243
+ if (!batch.length) break;
244
+ batch.forEach((d) => taken.add(d.id));
245
+ out.push(...batch);
246
+ // messages-received has no answer; the next drain shows whether it took.
247
+ await this.send(this.client.buildMessagesReceived(this.mediatorDid, batch.map((d) => d.id)) as unknown as Record<string, unknown>);
248
+ if (batch.length < limit) break;
249
+ const key = first.body.recipient_key;
250
+ req = this.client.buildDeliveryRequest(this.mediatorDid, limit, key);
251
+ }
252
+ }
253
+ return out;
254
+ }
255
+ }