@fleetmesh/leaf 0.1.0 → 0.2.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/src/session.ts CHANGED
@@ -11,22 +11,39 @@
11
11
  // updateKeylist() keylist-update, answered by keylist-update-response.
12
12
  // pickup() delivery-request per registered key, opened and
13
13
  // acked, until the inbox is empty.
14
+ // sendForward() encrypt an inner DIDComm message to a peer and send it
15
+ // wrapped in a routing/2.0/forward through the mediator.
16
+ // reconcile() run NIP-77 Negentropy V1 range reconciliation over the
17
+ // active relay connection.
14
18
  //
15
19
  // A phone's socket dies on screen lock. Nothing here survives that except
16
20
  // the grant and keylist; resume() reconnects and resubscribes, and the next
17
21
  // pickup() catches up. Messages the anchor stored as kind 1059 are replayed
18
22
  // by the relay inside the subscription's two-day window.
19
23
  import { agreementOf, buildLeafDescriptor, KIND as DESCRIPTOR_KIND } from './descriptor.ts';
20
- import { agreementPublic } from './didcomm.ts';
24
+ import { agreementPublic, encrypt as encryptDidcomm, type JWE, type ProtectedHeader } from './didcomm.ts';
25
+ import { b64uDec, fromUtf8, isHex } from './encoding.ts';
21
26
  import { type NostrEvent, pubkeyOf, signEvent, verifyEvent } from './event.ts';
22
27
  import { TWO_DAYS, WRAP_LIVE, WRAP_STORED } from './giftwrap.ts';
23
28
  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';
29
+ import { type DeliveredMessage, type Message, PICKUP_LIMIT_DEFAULT, type PickupDeliveryBody } from './mediation/messages.ts';
30
+ import type { Item, ReconcileReport } from './negentropy.ts';
31
+ import { authEvent, type Filter, RelayConnection, type SocketFactory, type Subscription } from './relay.ts';
26
32
  import { EMPTY_TYPE, open, type Opened, Reassembler, seal } from './seal.ts';
27
33
 
28
34
  export class SessionError extends Error {}
29
35
 
36
+ export interface SendForwardOptions {
37
+ /** 64-hex leaf pubkey that owns the X25519 #agree key when recipientDid is a bound alias DID. */
38
+ recipientLeafPubkey?: string;
39
+ /** Explicit 32-byte X25519 agreement public key for the recipient leaf; resolved from kind 11801 when omitted. */
40
+ recipientAgreementPub?: Uint8Array;
41
+ /** Target mediator DID; defaults to this session's mediatorDid. */
42
+ mediatorDid?: string;
43
+ /** Use anoncrypt (ECDH-ES+A256KW) instead of authcrypt (ECDH-1PU+A256KW). Default false. */
44
+ anoncrypt?: boolean;
45
+ }
46
+
30
47
  export interface LeafSessionOptions {
31
48
  /** The leaf's node key (secp256k1, hex) and agreement key (X25519, raw). */
32
49
  nodeSk: string;
@@ -51,6 +68,15 @@ export interface LeafSessionOptions {
51
68
 
52
69
  const SEEN_MAX = 4096;
53
70
 
71
+ const pubkeyFromDidOrKid = (didOrKid: string): string | null => {
72
+ const clean = didOrKid.trim().split('#', 1)[0]!;
73
+ if (clean.startsWith('did:nostr:')) {
74
+ const pk = clean.slice('did:nostr:'.length).toLowerCase();
75
+ return isHex(pk, 64) ? pk : null;
76
+ }
77
+ return isHex(clean.toLowerCase(), 64) ? clean.toLowerCase() : null;
78
+ };
79
+
54
80
  export class LeafSession {
55
81
  readonly pubkey: string;
56
82
  readonly client: LeafClient;
@@ -60,6 +86,7 @@ export class LeafSession {
60
86
  private relay: RelayConnection;
61
87
  private sub: Subscription | null = null;
62
88
  private mediatorAgreement: Uint8Array | null = null;
89
+ private readonly peerAgreements = new Map<string, Uint8Array>();
63
90
  private descriptor: NostrEvent | null = null;
64
91
  private readonly waiters = new Map<string, (m: Opened) => void>();
65
92
  private readonly seen = new Set<string>();
@@ -72,6 +99,7 @@ export class LeafSession {
72
99
  this.mediatorDid = 'did:nostr:' + opts.mediator.pubkey;
73
100
  this.client = new LeafClient({ nodePk: this.pubkey, agreementSk: opts.agreementSk }, this.clock);
74
101
  if (opts.state) this.client.restore(opts.state);
102
+ this.peerAgreements.set(this.pubkey, agreementPublic(opts.agreementSk));
75
103
  this.relay = this.newRelay();
76
104
  }
77
105
 
@@ -91,21 +119,50 @@ export class LeafSession {
91
119
  return this.relay.connected && this.sub !== null;
92
120
  }
93
121
 
94
- /** The mediator's agreement key, from a descriptor it signed and that is live. */
95
- private async learnMediator(): Promise<Uint8Array> {
122
+ private isLiveDescriptor(d: NostrEvent, pubkey: string): boolean {
96
123
  const now = this.clock();
97
- const live = (d: NostrEvent) => d.kind === DESCRIPTOR_KIND && d.pubkey === this.opts.mediator.pubkey && verifyEvent(d)
124
+ return d.kind === DESCRIPTOR_KIND && d.pubkey === pubkey && verifyEvent(d)
98
125
  && !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;
126
+ }
127
+
128
+ /** The mediator's agreement key, from a descriptor it signed and that is live. */
129
+ private async learnMediator(): Promise<Uint8Array> {
130
+ let desc = this.opts.mediator.descriptor && this.isLiveDescriptor(this.opts.mediator.descriptor, this.opts.mediator.pubkey)
131
+ ? this.opts.mediator.descriptor
132
+ : null;
100
133
  if (!desc) {
101
134
  const found: NostrEvent[] = [];
102
135
  const sub = this.relay.subscribe([{ kinds: [DESCRIPTOR_KIND], authors: [this.opts.mediator.pubkey] }], (ev) => found.push(ev));
103
136
  await this.within(sub.eose, 'the mediator\'s descriptor');
104
137
  sub.close();
105
- desc = found.filter(live).sort((a, b) => b.created_at - a.created_at)[0] ?? null;
138
+ desc = found.filter((d) => this.isLiveDescriptor(d, this.opts.mediator.pubkey)).sort((a, b) => b.created_at - a.created_at)[0] ?? null;
106
139
  }
107
140
  const agree = desc ? agreementOf(desc) : null;
108
141
  if (!agree) throw new SessionError('no live descriptor with an agreement key for the mediator ' + this.opts.mediator.pubkey.slice(0, 16));
142
+ this.peerAgreements.set(this.opts.mediator.pubkey, agree);
143
+ return agree;
144
+ }
145
+
146
+ /** Resolve a peer's X25519 agreement key from cache or by querying its live kind 11801 descriptor. */
147
+ async resolvePeerAgreement(pubkeyOrDid: string): Promise<Uint8Array | null> {
148
+ const pk = pubkeyFromDidOrKid(pubkeyOrDid);
149
+ if (!pk) return null;
150
+ if (pk === this.opts.mediator.pubkey && this.mediatorAgreement) return this.mediatorAgreement;
151
+ const cached = this.peerAgreements.get(pk);
152
+ if (cached) return cached;
153
+ if (!this.relay.connected) return null;
154
+ const found: NostrEvent[] = [];
155
+ const sub = this.relay.subscribe([{ kinds: [DESCRIPTOR_KIND], authors: [pk] }], (ev) => found.push(ev));
156
+ try {
157
+ await this.within(sub.eose, `descriptor for ${pk.slice(0, 16)}`);
158
+ } catch {
159
+ return null;
160
+ } finally {
161
+ sub.close();
162
+ }
163
+ const desc = found.filter((d) => this.isLiveDescriptor(d, pk)).sort((a, b) => b.created_at - a.created_at)[0] ?? null;
164
+ const agree = desc ? agreementOf(desc) : null;
165
+ if (agree) this.peerAgreements.set(pk, agree);
109
166
  return agree;
110
167
  }
111
168
 
@@ -171,7 +228,7 @@ export class LeafSession {
171
228
  let opened: Opened | null;
172
229
  try {
173
230
  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());
231
+ (pk) => (pk === this.opts.mediator.pubkey ? this.mediatorAgreement : this.peerAgreements.get(pk) ?? null), this.reassembler, this.clock());
175
232
  } catch (e) {
176
233
  this.opts.onDrop?.((e as Error).message, ev.id);
177
234
  return;
@@ -189,14 +246,17 @@ export class LeafSession {
189
246
  }
190
247
 
191
248
  /** Seal and publish; throws if the relay took none of the wraps. */
192
- private async send(msg: Record<string, unknown>): Promise<void> {
249
+ private async send(msg: Record<string, unknown>): Promise<string[]> {
193
250
  if (!this.mediatorAgreement) throw new SessionError('start() first');
194
251
  const wraps = seal(msg, { nodeSk: this.opts.nodeSk, agreementSk: this.opts.agreementSk, pubkey: this.pubkey },
195
252
  { pubkey: this.opts.mediator.pubkey, agreementPub: this.mediatorAgreement }, { now: this.clock() });
253
+ const ids: string[] = [];
196
254
  for (const w of wraps) {
197
255
  const r = await this.relay.publish(w);
198
256
  if (!r.ok) throw new SessionError('the mediator\'s relay refused a wrap: ' + r.message);
257
+ ids.push(w.id);
199
258
  }
259
+ return ids;
200
260
  }
201
261
 
202
262
  /** Send a message and wait for the mediator's answer on its thread. */
@@ -225,21 +285,52 @@ export class LeafSession {
225
285
  return r;
226
286
  }
227
287
 
288
+ /** Pre-resolve any unknown authcrypt sender agreement keys referenced in a delivery batch. */
289
+ private async prefetchDeliverySenders(reply: Message<PickupDeliveryBody>, customResolver?: (skid: string) => Uint8Array | null | undefined): Promise<void> {
290
+ const rows: DeliveredMessage[] = Array.isArray(reply.body?.messages) ? reply.body.messages : [];
291
+ const unknownPks = new Set<string>();
292
+ for (const r of rows) {
293
+ for (const att of Array.isArray(r?.attachments) ? r.attachments : []) {
294
+ const jwe = att?.data?.json as JWE | undefined;
295
+ if (!jwe || typeof jwe.protected !== 'string') continue;
296
+ try {
297
+ const prot = JSON.parse(fromUtf8(b64uDec(jwe.protected))) as ProtectedHeader;
298
+ if (typeof prot.skid === 'string') {
299
+ if (customResolver?.(prot.skid)) continue;
300
+ const pk = pubkeyFromDidOrKid(prot.skid);
301
+ if (pk && !this.peerAgreements.has(pk) && pk !== this.opts.mediator.pubkey) unknownPks.add(pk);
302
+ }
303
+ } catch {
304
+ // Malformed header is handled by openDelivery
305
+ }
306
+ }
307
+ }
308
+ for (const pk of unknownPks) {
309
+ await this.resolvePeerAgreement(pk);
310
+ }
311
+ }
312
+
228
313
  /** Drain every registered key until the mediator has nothing left, acking
229
314
  * each batch so it purges what was taken. maxRounds bounds a mediator that
230
315
  * keeps returning the same batch. */
231
316
  async pickup(opts: { limit?: number; maxRounds?: number; resolveSender?: (skid: string) => Uint8Array | null | undefined } = {}): Promise<OpenedDelivery[]> {
232
317
  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
318
  const mediatorKid = this.mediatorDid + '#agree';
236
- const resolve = (skid: string) => (skid === mediatorKid ? this.mediatorAgreement : opts.resolveSender?.(skid));
319
+ const resolve = (skid: string) => {
320
+ if (skid === mediatorKid) return this.mediatorAgreement;
321
+ const custom = opts.resolveSender?.(skid);
322
+ if (custom) return custom;
323
+ const pk = pubkeyFromDidOrKid(skid);
324
+ return pk ? this.peerAgreements.get(pk) ?? null : null;
325
+ };
237
326
  const out: OpenedDelivery[] = [];
238
327
  const taken = new Set<string>();
239
328
  for (const first of this.client.buildDeliveryRequests(this.mediatorDid, limit)) {
240
329
  let req = first;
241
330
  for (let round = 0; round < maxRounds; round++) {
242
- const batch = this.client.openDelivery(await this.request(req), resolve).filter((d) => !taken.has(d.id));
331
+ const reply = await this.request(req);
332
+ await this.prefetchDeliverySenders(reply, opts.resolveSender);
333
+ const batch = this.client.openDelivery(reply, resolve).filter((d) => !taken.has(d.id));
243
334
  if (!batch.length) break;
244
335
  batch.forEach((d) => taken.add(d.id));
245
336
  out.push(...batch);
@@ -252,4 +343,40 @@ export class LeafSession {
252
343
  }
253
344
  return out;
254
345
  }
346
+
347
+ /** Encrypt an inner DIDComm message to a recipient and publish a routing/2.0/forward through the mediator. */
348
+ async sendForward(recipientDid: string, message: Record<string, unknown>, opts: SendForwardOptions = {}): Promise<string[]> {
349
+ if (!this.connected) throw new SessionError('not connected; start() or resume() first');
350
+ const targetDid = recipientDid.startsWith('did:') ? recipientDid : ('did:nostr:' + recipientDid.toLowerCase());
351
+ const leafPk = opts.recipientLeafPubkey
352
+ ? (pubkeyFromDidOrKid(opts.recipientLeafPubkey) ?? opts.recipientLeafPubkey.toLowerCase())
353
+ : (pubkeyFromDidOrKid(targetDid) ?? '');
354
+ const recipientAgree = opts.recipientAgreementPub ?? (leafPk ? await this.resolvePeerAgreement(leafPk) : null);
355
+ if (!recipientAgree) {
356
+ throw new SessionError('could not resolve X25519 agreement key for recipient ' + targetDid);
357
+ }
358
+ const now = this.clock();
359
+ const innerMsg: Record<string, unknown> = { ...message };
360
+ if (!opts.anoncrypt) {
361
+ innerMsg.from ??= this.client.did;
362
+ }
363
+ innerMsg.to ??= [targetDid];
364
+ innerMsg.created_time ??= now;
365
+ const recipientKids = new Map<string, Uint8Array>();
366
+ if (leafPk) recipientKids.set(`did:nostr:${leafPk}#agree`, recipientAgree);
367
+ recipientKids.set(`${targetDid.split('#', 1)[0]}#agree`, recipientAgree);
368
+ const jwe = encryptDidcomm(
369
+ innerMsg,
370
+ [...recipientKids.entries()],
371
+ opts.anoncrypt ? {} : { sender: [this.client.kid, this.opts.agreementSk] },
372
+ );
373
+ const fwd = this.client.wrapForward(jwe, opts.mediatorDid ?? this.mediatorDid, targetDid);
374
+ return this.send(fwd as unknown as Record<string, unknown>);
375
+ }
376
+
377
+ /** Run a NIP-77 Negentropy V1 range reconciliation over the active relay connection. */
378
+ async reconcile(filter: Filter, items: Iterable<Item>, opts: { maxRounds?: number } = {}): Promise<ReconcileReport> {
379
+ if (!this.connected) throw new SessionError('not connected; start() or resume() first');
380
+ return this.relay.reconcile(filter, items, opts);
381
+ }
255
382
  }