@fleetmesh/leaf 0.1.1 → 0.2.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/README.md +12 -0
- package/dist/descriptor.d.ts +1 -1
- package/dist/did.d.ts +15 -1
- package/dist/did.js +36 -0
- package/dist/encoding.d.ts +17 -4
- package/dist/encoding.js +17 -6
- package/dist/giftwrap.d.ts +1 -1
- package/dist/index.d.ts +17 -17
- package/dist/index.js +1 -1
- package/dist/mediation/leaf.d.ts +2 -2
- package/dist/pwa/browser-leaf.d.ts +3 -3
- package/dist/pwa/browser-leaf.js +30 -1
- package/dist/pwa/hub.d.ts +17 -1
- package/dist/pwa/hub.js +51 -3
- package/dist/pwa/store.d.ts +3 -1
- package/dist/relay.d.ts +7 -1
- package/dist/relay.js +123 -0
- package/dist/seal.d.ts +2 -2
- package/dist/session.d.ts +27 -4
- package/dist/session.js +132 -11
- package/package.json +31 -4
- package/src/did.ts +39 -0
- package/src/encoding.ts +26 -6
- package/src/index.ts +3 -3
- package/src/pwa/browser-leaf.ts +30 -1
- package/src/pwa/hub.ts +80 -5
- package/src/pwa/store.ts +2 -1
- package/src/relay.ts +110 -1
- package/src/session.ts +141 -14
package/src/pwa/store.ts
CHANGED
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
import { schnorr } from '@noble/curves/secp256k1.js';
|
|
17
17
|
import { LEAF } from '../constants.ts';
|
|
18
18
|
import { bytesToHex, fromUtf8, hexToBytes, utf8 } from '../encoding.ts';
|
|
19
|
+
import type { NostrEvent } from '../event.ts';
|
|
19
20
|
import type { LeafClientState, OpenedDelivery } from '../mediation/leaf.ts';
|
|
20
21
|
|
|
21
22
|
export const DB_NAME = 'fleetmesh-leaf';
|
|
@@ -23,7 +24,7 @@ const VERSION = 1;
|
|
|
23
24
|
const KV = 'kv', INBOX = 'inbox';
|
|
24
25
|
|
|
25
26
|
export interface LeafIdentity { nodeSk: string; agreementSk: Uint8Array }
|
|
26
|
-
export interface MediatorConfig { pubkey: string; endpoint: string }
|
|
27
|
+
export interface MediatorConfig { pubkey: string; endpoint: string; descriptor?: NostrEvent }
|
|
27
28
|
export interface StoredDelivery extends OpenedDelivery { received_at: number }
|
|
28
29
|
|
|
29
30
|
function req<T>(r: IDBRequest<T>): Promise<T> {
|
package/src/relay.ts
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
// One NIP-01 relay connection over a standard WebSocket, which browsers and
|
|
2
2
|
// Node (22+) both provide as a global. EVENT/OK, REQ/EVENT/EOSE/CLOSED, CLOSE,
|
|
3
|
-
// NOTICE,
|
|
3
|
+
// NOTICE, NIP-42 AUTH answered with the leaf's node key, and NIP-77 Negentropy
|
|
4
|
+
// V1 range reconciliation (NEG-OPEN, NEG-MSG, NEG-CLOSE, NEG-ERR).
|
|
4
5
|
//
|
|
5
6
|
// Deliberately one socket and no reconnect policy: a leaf holds exactly one
|
|
6
7
|
// connection, to its mediator (spec § "The leaf profile"), and when it drops
|
|
7
8
|
// the session decides what to do - mobile operating systems kill sockets on
|
|
8
9
|
// screen lock, so "reconnect and catch up" is the session's ordinary path,
|
|
9
10
|
// not this module's error handling.
|
|
11
|
+
import { bytesToHex, hexToBytes } from './encoding.ts';
|
|
10
12
|
import type { NostrEvent } from './event.ts';
|
|
13
|
+
import { type Item, Negentropy, type ReconcileReport } from './negentropy.ts';
|
|
11
14
|
|
|
12
15
|
/** The slice of the WHATWG WebSocket this module uses. */
|
|
13
16
|
export interface SocketLike {
|
|
@@ -54,6 +57,18 @@ const defaultSocket: SocketFactory = (url) => {
|
|
|
54
57
|
|
|
55
58
|
interface PendingOk { resolve: (r: PublishResult) => void; timer: ReturnType<typeof setTimeout> }
|
|
56
59
|
interface Sub { filters: Filter[]; onEvent: (ev: NostrEvent) => void; eose: () => void; closed: (why: string) => void; authRetried: boolean }
|
|
60
|
+
interface PendingNeg {
|
|
61
|
+
client: Negentropy;
|
|
62
|
+
have: Set<string>;
|
|
63
|
+
need: Set<string>;
|
|
64
|
+
rounds: number;
|
|
65
|
+
maxRounds: number;
|
|
66
|
+
bytesSent: number;
|
|
67
|
+
bytesReceived: number;
|
|
68
|
+
resolve: (r: ReconcileReport) => void;
|
|
69
|
+
reject: (e: Error) => void;
|
|
70
|
+
timer: ReturnType<typeof setTimeout>;
|
|
71
|
+
}
|
|
57
72
|
|
|
58
73
|
export class RelayConnection {
|
|
59
74
|
readonly url: string;
|
|
@@ -63,6 +78,7 @@ export class RelayConnection {
|
|
|
63
78
|
private authed: Promise<boolean> | null = null;
|
|
64
79
|
private readonly oks = new Map<string, PendingOk>();
|
|
65
80
|
private readonly subs = new Map<string, Sub>();
|
|
81
|
+
private readonly negs = new Map<string, PendingNeg>();
|
|
66
82
|
private seq = 0;
|
|
67
83
|
|
|
68
84
|
constructor(url: string, opts: RelayOptions = {}) {
|
|
@@ -126,6 +142,11 @@ export class RelayConnection {
|
|
|
126
142
|
s.closed('error: connection closed');
|
|
127
143
|
this.subs.delete(id);
|
|
128
144
|
}
|
|
145
|
+
for (const [id, n] of this.negs) {
|
|
146
|
+
clearTimeout(n.timer);
|
|
147
|
+
n.reject(new RelayError('error: connection closed'));
|
|
148
|
+
this.negs.delete(id);
|
|
149
|
+
}
|
|
129
150
|
this.challenge = null;
|
|
130
151
|
this.authed = null;
|
|
131
152
|
this.opts.onClose?.();
|
|
@@ -177,6 +198,49 @@ export class RelayConnection {
|
|
|
177
198
|
};
|
|
178
199
|
}
|
|
179
200
|
|
|
201
|
+
/** NIP-77 Negentropy V1 range reconciliation over NEG-OPEN / NEG-MSG / NEG-CLOSE. */
|
|
202
|
+
reconcile(filter: Filter, items: Iterable<Item>, opts: { maxRounds?: number } = {}): Promise<ReconcileReport> {
|
|
203
|
+
if (!this.connected) return Promise.reject(new RelayError('not connected to ' + this.url));
|
|
204
|
+
const id = 'neg-' + (++this.seq).toString(36);
|
|
205
|
+
const maxRounds = opts.maxRounds ?? 32;
|
|
206
|
+
let client: Negentropy;
|
|
207
|
+
let init: Uint8Array;
|
|
208
|
+
try {
|
|
209
|
+
client = new Negentropy(items, true);
|
|
210
|
+
init = client.initiate();
|
|
211
|
+
} catch (e) {
|
|
212
|
+
return Promise.reject(e);
|
|
213
|
+
}
|
|
214
|
+
return new Promise<ReconcileReport>((resolve, reject) => {
|
|
215
|
+
const timer = setTimeout(() => {
|
|
216
|
+
this.negs.delete(id);
|
|
217
|
+
if (this.connected) {
|
|
218
|
+
try { this.send(['NEG-CLOSE', id]); } catch { /* ignore */ }
|
|
219
|
+
}
|
|
220
|
+
reject(new RelayError(`no NEG-MSG answer in ${this.timeout}ms`));
|
|
221
|
+
}, this.timeout);
|
|
222
|
+
this.negs.set(id, {
|
|
223
|
+
client,
|
|
224
|
+
have: new Set(),
|
|
225
|
+
need: new Set(),
|
|
226
|
+
rounds: 0,
|
|
227
|
+
maxRounds,
|
|
228
|
+
bytesSent: init.length,
|
|
229
|
+
bytesReceived: 0,
|
|
230
|
+
resolve,
|
|
231
|
+
reject,
|
|
232
|
+
timer,
|
|
233
|
+
});
|
|
234
|
+
try {
|
|
235
|
+
this.send(['NEG-OPEN', id, filter, bytesToHex(init)]);
|
|
236
|
+
} catch (e) {
|
|
237
|
+
clearTimeout(timer);
|
|
238
|
+
this.negs.delete(id);
|
|
239
|
+
reject(new RelayError('error: ' + (e as Error).message));
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
|
|
180
244
|
/** Answer the relay's NIP-42 challenge; false if there is none or no signer. */
|
|
181
245
|
authenticate(): Promise<boolean> {
|
|
182
246
|
if (this.authed) return this.authed;
|
|
@@ -241,6 +305,51 @@ export class RelayConnection {
|
|
|
241
305
|
p.resolve({ ok: b === true, message: typeof c === 'string' ? c : '' });
|
|
242
306
|
break;
|
|
243
307
|
}
|
|
308
|
+
case 'NEG-MSG': {
|
|
309
|
+
if (typeof a !== 'string' || typeof b !== 'string') break;
|
|
310
|
+
const n = this.negs.get(a);
|
|
311
|
+
if (!n) break;
|
|
312
|
+
try {
|
|
313
|
+
const replyBytes = hexToBytes(b.toLowerCase());
|
|
314
|
+
n.bytesReceived += replyBytes.length;
|
|
315
|
+
n.rounds += 1;
|
|
316
|
+
const [next, have, need] = n.client.reconcile(replyBytes);
|
|
317
|
+
for (const h of have) n.have.add(h);
|
|
318
|
+
for (const nd of need) n.need.add(nd);
|
|
319
|
+
if (next === null || n.rounds >= n.maxRounds) {
|
|
320
|
+
clearTimeout(n.timer);
|
|
321
|
+
this.negs.delete(a);
|
|
322
|
+
if (this.connected) this.send(['NEG-CLOSE', a]);
|
|
323
|
+
n.resolve({
|
|
324
|
+
have: [...n.have].sort(),
|
|
325
|
+
need: [...n.need].sort(),
|
|
326
|
+
rounds: n.rounds,
|
|
327
|
+
bytesSent: n.bytesSent,
|
|
328
|
+
bytesReceived: n.bytesReceived,
|
|
329
|
+
});
|
|
330
|
+
} else {
|
|
331
|
+
n.bytesSent += next.length;
|
|
332
|
+
this.send(['NEG-MSG', a, bytesToHex(next)]);
|
|
333
|
+
}
|
|
334
|
+
} catch (e) {
|
|
335
|
+
clearTimeout(n.timer);
|
|
336
|
+
this.negs.delete(a);
|
|
337
|
+
if (this.connected) {
|
|
338
|
+
try { this.send(['NEG-CLOSE', a]); } catch { /* ignore */ }
|
|
339
|
+
}
|
|
340
|
+
n.reject(new RelayError('negentropy: ' + (e as Error).message));
|
|
341
|
+
}
|
|
342
|
+
break;
|
|
343
|
+
}
|
|
344
|
+
case 'NEG-ERR': {
|
|
345
|
+
if (typeof a !== 'string') break;
|
|
346
|
+
const n = this.negs.get(a);
|
|
347
|
+
if (!n) break;
|
|
348
|
+
clearTimeout(n.timer);
|
|
349
|
+
this.negs.delete(a);
|
|
350
|
+
n.reject(new RelayError('negentropy error: ' + (typeof b === 'string' ? b : 'rejected')));
|
|
351
|
+
break;
|
|
352
|
+
}
|
|
244
353
|
case 'AUTH': {
|
|
245
354
|
if (typeof a === 'string') {
|
|
246
355
|
this.challenge = a;
|
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 {
|
|
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
|
-
|
|
95
|
-
private async learnMediator(): Promise<Uint8Array> {
|
|
122
|
+
private isLiveDescriptor(d: NostrEvent, pubkey: string): boolean {
|
|
96
123
|
const now = this.clock();
|
|
97
|
-
|
|
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
|
-
|
|
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(
|
|
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<
|
|
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) =>
|
|
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
|
|
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
|
}
|