@fleetmesh/leaf 0.1.1 → 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/dist/session.js CHANGED
@@ -11,13 +11,18 @@
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.js';
20
- import { agreementPublic } from './didcomm.js';
24
+ import { agreementPublic, encrypt as encryptDidcomm } from './didcomm.js';
25
+ import { b64uDec, fromUtf8, isHex } from './encoding.js';
21
26
  import { pubkeyOf, signEvent, verifyEvent } from './event.js';
22
27
  import { TWO_DAYS, WRAP_LIVE, WRAP_STORED } from './giftwrap.js';
23
28
  import { LeafClient } from './mediation/leaf.js';
@@ -27,6 +32,14 @@ import { EMPTY_TYPE, open, Reassembler, seal } from './seal.js';
27
32
  export class SessionError extends Error {
28
33
  }
29
34
  const SEEN_MAX = 4096;
35
+ const pubkeyFromDidOrKid = (didOrKid) => {
36
+ const clean = didOrKid.trim().split('#', 1)[0];
37
+ if (clean.startsWith('did:nostr:')) {
38
+ const pk = clean.slice('did:nostr:'.length).toLowerCase();
39
+ return isHex(pk, 64) ? pk : null;
40
+ }
41
+ return isHex(clean.toLowerCase(), 64) ? clean.toLowerCase() : null;
42
+ };
30
43
  export class LeafSession {
31
44
  pubkey;
32
45
  client;
@@ -36,6 +49,7 @@ export class LeafSession {
36
49
  relay;
37
50
  sub = null;
38
51
  mediatorAgreement = null;
52
+ peerAgreements = new Map();
39
53
  descriptor = null;
40
54
  waiters = new Map();
41
55
  seen = new Set();
@@ -48,6 +62,7 @@ export class LeafSession {
48
62
  this.client = new LeafClient({ nodePk: this.pubkey, agreementSk: opts.agreementSk }, this.clock);
49
63
  if (opts.state)
50
64
  this.client.restore(opts.state);
65
+ this.peerAgreements.set(this.pubkey, agreementPublic(opts.agreementSk));
51
66
  this.relay = this.newRelay();
52
67
  }
53
68
  newRelay() {
@@ -63,22 +78,56 @@ export class LeafSession {
63
78
  get connected() {
64
79
  return this.relay.connected && this.sub !== null;
65
80
  }
66
- /** The mediator's agreement key, from a descriptor it signed and that is live. */
67
- async learnMediator() {
81
+ isLiveDescriptor(d, pubkey) {
68
82
  const now = this.clock();
69
- const live = (d) => d.kind === DESCRIPTOR_KIND && d.pubkey === this.opts.mediator.pubkey && verifyEvent(d)
83
+ return d.kind === DESCRIPTOR_KIND && d.pubkey === pubkey && verifyEvent(d)
70
84
  && !d.tags.some((t) => t[0] === 'expiration' && /^\d+$/.test(t[1] ?? '') && +t[1] <= now);
71
- let desc = this.opts.mediator.descriptor && live(this.opts.mediator.descriptor) ? this.opts.mediator.descriptor : null;
85
+ }
86
+ /** The mediator's agreement key, from a descriptor it signed and that is live. */
87
+ async learnMediator() {
88
+ let desc = this.opts.mediator.descriptor && this.isLiveDescriptor(this.opts.mediator.descriptor, this.opts.mediator.pubkey)
89
+ ? this.opts.mediator.descriptor
90
+ : null;
72
91
  if (!desc) {
73
92
  const found = [];
74
93
  const sub = this.relay.subscribe([{ kinds: [DESCRIPTOR_KIND], authors: [this.opts.mediator.pubkey] }], (ev) => found.push(ev));
75
94
  await this.within(sub.eose, 'the mediator\'s descriptor');
76
95
  sub.close();
77
- desc = found.filter(live).sort((a, b) => b.created_at - a.created_at)[0] ?? null;
96
+ desc = found.filter((d) => this.isLiveDescriptor(d, this.opts.mediator.pubkey)).sort((a, b) => b.created_at - a.created_at)[0] ?? null;
78
97
  }
79
98
  const agree = desc ? agreementOf(desc) : null;
80
99
  if (!agree)
81
100
  throw new SessionError('no live descriptor with an agreement key for the mediator ' + this.opts.mediator.pubkey.slice(0, 16));
101
+ this.peerAgreements.set(this.opts.mediator.pubkey, agree);
102
+ return agree;
103
+ }
104
+ /** Resolve a peer's X25519 agreement key from cache or by querying its live kind 11801 descriptor. */
105
+ async resolvePeerAgreement(pubkeyOrDid) {
106
+ const pk = pubkeyFromDidOrKid(pubkeyOrDid);
107
+ if (!pk)
108
+ return null;
109
+ if (pk === this.opts.mediator.pubkey && this.mediatorAgreement)
110
+ return this.mediatorAgreement;
111
+ const cached = this.peerAgreements.get(pk);
112
+ if (cached)
113
+ return cached;
114
+ if (!this.relay.connected)
115
+ return null;
116
+ const found = [];
117
+ const sub = this.relay.subscribe([{ kinds: [DESCRIPTOR_KIND], authors: [pk] }], (ev) => found.push(ev));
118
+ try {
119
+ await this.within(sub.eose, `descriptor for ${pk.slice(0, 16)}`);
120
+ }
121
+ catch {
122
+ return null;
123
+ }
124
+ finally {
125
+ sub.close();
126
+ }
127
+ const desc = found.filter((d) => this.isLiveDescriptor(d, pk)).sort((a, b) => b.created_at - a.created_at)[0] ?? null;
128
+ const agree = desc ? agreementOf(desc) : null;
129
+ if (agree)
130
+ this.peerAgreements.set(pk, agree);
82
131
  return agree;
83
132
  }
84
133
  within(p, what) {
@@ -141,7 +190,7 @@ export class LeafSession {
141
190
  this.seen.delete(this.seen.values().next().value);
142
191
  let opened;
143
192
  try {
144
- opened = open(ev, { nodeSk: this.opts.nodeSk, agreementSk: this.opts.agreementSk, pubkey: this.pubkey }, (pk) => (pk === this.opts.mediator.pubkey ? this.mediatorAgreement : null), this.reassembler, this.clock());
193
+ opened = open(ev, { nodeSk: this.opts.nodeSk, agreementSk: this.opts.agreementSk, pubkey: this.pubkey }, (pk) => (pk === this.opts.mediator.pubkey ? this.mediatorAgreement : this.peerAgreements.get(pk) ?? null), this.reassembler, this.clock());
145
194
  }
146
195
  catch (e) {
147
196
  this.opts.onDrop?.(e.message, ev.id);
@@ -167,11 +216,14 @@ export class LeafSession {
167
216
  if (!this.mediatorAgreement)
168
217
  throw new SessionError('start() first');
169
218
  const wraps = seal(msg, { nodeSk: this.opts.nodeSk, agreementSk: this.opts.agreementSk, pubkey: this.pubkey }, { pubkey: this.opts.mediator.pubkey, agreementPub: this.mediatorAgreement }, { now: this.clock() });
219
+ const ids = [];
170
220
  for (const w of wraps) {
171
221
  const r = await this.relay.publish(w);
172
222
  if (!r.ok)
173
223
  throw new SessionError('the mediator\'s relay refused a wrap: ' + r.message);
224
+ ids.push(w.id);
174
225
  }
226
+ return ids;
175
227
  }
176
228
  /** Send a message and wait for the mediator's answer on its thread. */
177
229
  async request(msg) {
@@ -198,21 +250,57 @@ export class LeafSession {
198
250
  this.opts.onState?.(this.client.snapshot());
199
251
  return r;
200
252
  }
253
+ /** Pre-resolve any unknown authcrypt sender agreement keys referenced in a delivery batch. */
254
+ async prefetchDeliverySenders(reply, customResolver) {
255
+ const rows = Array.isArray(reply.body?.messages) ? reply.body.messages : [];
256
+ const unknownPks = new Set();
257
+ for (const r of rows) {
258
+ for (const att of Array.isArray(r?.attachments) ? r.attachments : []) {
259
+ const jwe = att?.data?.json;
260
+ if (!jwe || typeof jwe.protected !== 'string')
261
+ continue;
262
+ try {
263
+ const prot = JSON.parse(fromUtf8(b64uDec(jwe.protected)));
264
+ if (typeof prot.skid === 'string') {
265
+ if (customResolver?.(prot.skid))
266
+ continue;
267
+ const pk = pubkeyFromDidOrKid(prot.skid);
268
+ if (pk && !this.peerAgreements.has(pk) && pk !== this.opts.mediator.pubkey)
269
+ unknownPks.add(pk);
270
+ }
271
+ }
272
+ catch {
273
+ // Malformed header is handled by openDelivery
274
+ }
275
+ }
276
+ }
277
+ for (const pk of unknownPks) {
278
+ await this.resolvePeerAgreement(pk);
279
+ }
280
+ }
201
281
  /** Drain every registered key until the mediator has nothing left, acking
202
282
  * each batch so it purges what was taken. maxRounds bounds a mediator that
203
283
  * keeps returning the same batch. */
204
284
  async pickup(opts = {}) {
205
285
  const limit = opts.limit ?? PICKUP_LIMIT_DEFAULT, maxRounds = opts.maxRounds ?? 50;
206
- // The mediator's own key is always known here, so messages it authcrypts
207
- // itself open; anyone else needs the caller's resolver.
208
286
  const mediatorKid = this.mediatorDid + '#agree';
209
- const resolve = (skid) => (skid === mediatorKid ? this.mediatorAgreement : opts.resolveSender?.(skid));
287
+ const resolve = (skid) => {
288
+ if (skid === mediatorKid)
289
+ return this.mediatorAgreement;
290
+ const custom = opts.resolveSender?.(skid);
291
+ if (custom)
292
+ return custom;
293
+ const pk = pubkeyFromDidOrKid(skid);
294
+ return pk ? this.peerAgreements.get(pk) ?? null : null;
295
+ };
210
296
  const out = [];
211
297
  const taken = new Set();
212
298
  for (const first of this.client.buildDeliveryRequests(this.mediatorDid, limit)) {
213
299
  let req = first;
214
300
  for (let round = 0; round < maxRounds; round++) {
215
- const batch = this.client.openDelivery(await this.request(req), resolve).filter((d) => !taken.has(d.id));
301
+ const reply = await this.request(req);
302
+ await this.prefetchDeliverySenders(reply, opts.resolveSender);
303
+ const batch = this.client.openDelivery(reply, resolve).filter((d) => !taken.has(d.id));
216
304
  if (!batch.length)
217
305
  break;
218
306
  batch.forEach((d) => taken.add(d.id));
@@ -227,4 +315,37 @@ export class LeafSession {
227
315
  }
228
316
  return out;
229
317
  }
318
+ /** Encrypt an inner DIDComm message to a recipient and publish a routing/2.0/forward through the mediator. */
319
+ async sendForward(recipientDid, message, opts = {}) {
320
+ if (!this.connected)
321
+ throw new SessionError('not connected; start() or resume() first');
322
+ const targetDid = recipientDid.startsWith('did:') ? recipientDid : ('did:nostr:' + recipientDid.toLowerCase());
323
+ const leafPk = opts.recipientLeafPubkey
324
+ ? (pubkeyFromDidOrKid(opts.recipientLeafPubkey) ?? opts.recipientLeafPubkey.toLowerCase())
325
+ : (pubkeyFromDidOrKid(targetDid) ?? '');
326
+ const recipientAgree = opts.recipientAgreementPub ?? (leafPk ? await this.resolvePeerAgreement(leafPk) : null);
327
+ if (!recipientAgree) {
328
+ throw new SessionError('could not resolve X25519 agreement key for recipient ' + targetDid);
329
+ }
330
+ const now = this.clock();
331
+ const innerMsg = { ...message };
332
+ if (!opts.anoncrypt) {
333
+ innerMsg.from ??= this.client.did;
334
+ }
335
+ innerMsg.to ??= [targetDid];
336
+ innerMsg.created_time ??= now;
337
+ const recipientKids = new Map();
338
+ if (leafPk)
339
+ recipientKids.set(`did:nostr:${leafPk}#agree`, recipientAgree);
340
+ recipientKids.set(`${targetDid.split('#', 1)[0]}#agree`, recipientAgree);
341
+ const jwe = encryptDidcomm(innerMsg, [...recipientKids.entries()], opts.anoncrypt ? {} : { sender: [this.client.kid, this.opts.agreementSk] });
342
+ const fwd = this.client.wrapForward(jwe, opts.mediatorDid ?? this.mediatorDid, targetDid);
343
+ return this.send(fwd);
344
+ }
345
+ /** Run a NIP-77 Negentropy V1 range reconciliation over the active relay connection. */
346
+ async reconcile(filter, items, opts = {}) {
347
+ if (!this.connected)
348
+ throw new SessionError('not connected; start() or resume() first');
349
+ return this.relay.reconcile(filter, items, opts);
350
+ }
230
351
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@fleetmesh/leaf",
3
- "version": "0.1.1",
4
- "description": "Fleetmesh leaf profile in TypeScript: browsers and PWAs as mediated mesh leaves",
3
+ "version": "0.2.0",
4
+ "description": "Fleetmesh leaf profile in TypeScript: browsers and PWAs as mediated mesh leaves with NIP-59 gift wraps, DIDComm v2, and NIP-77 Negentropy reconciliation",
5
5
  "license": "CC0-1.0",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",
@@ -17,8 +17,31 @@
17
17
  "dist",
18
18
  "src"
19
19
  ],
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "keywords": [
24
+ "fleetmesh",
25
+ "leaf",
26
+ "didcomm",
27
+ "nostr",
28
+ "nip-44",
29
+ "nip-59",
30
+ "nip-77",
31
+ "negentropy",
32
+ "bip340",
33
+ "x25519",
34
+ "pwa"
35
+ ],
36
+ "devEngines": {
37
+ "runtime": {
38
+ "name": "node",
39
+ "version": "^22.18.0 || ^24.0.0 || >=26.0.0",
40
+ "onFail": "warn"
41
+ }
42
+ },
20
43
  "scripts": {
21
- "build": "tsc --ignoreConfig --target ES2022 --module ESNext --moduleResolution Bundler --lib ES2022,DOM --strict --declaration --rewriteRelativeImportExtensions --outDir dist --rootDir src src/index.ts",
44
+ "build": "tsc -p tsconfig.build.json && node -e \"import('node:fs').then(fs=>{const walk=d=>fs.readdirSync(d,{withFileTypes:true}).forEach(e=>{const p=d+'/'+e.name;if(e.isDirectory())walk(p);else if(p.endsWith('.d.ts'))fs.writeFileSync(p,fs.readFileSync(p,'utf8').replace(/(from\\s+['\\\"][^'\\\"]+)\\.ts(['\\\"])/g,(_,a,b)=>a+'.js'+b));});walk('dist');})\"",
22
45
  "prepack": "npm run build",
23
46
  "test": "vitest run --project node",
24
47
  "test:browser": "vitest run --project browser",
package/src/index.ts CHANGED
@@ -14,7 +14,7 @@ export * as negentropy from './negentropy.ts';
14
14
  export * as nip44 from './nip44.ts';
15
15
  export * as relay from './relay.ts';
16
16
  export * as seal from './seal.ts';
17
- export { LeafSession, type LeafSessionOptions, SessionError } from './session.ts';
17
+ export { LeafSession, type LeafSessionOptions, type SendForwardOptions, SessionError } from './session.ts';
18
18
  export { type BrowserLeafOptions, startBrowserLeaf, SW_PICKUP } from './pwa/browser-leaf.ts';
19
- export { type HubEvent, LeafHub, type LeafStatus } from './pwa/hub.ts';
20
- export { LeafStore } from './pwa/store.ts';
19
+ export { type HubEvent, type HubOptions, type Leader, LeafHub, type LeafStatus } from './pwa/hub.ts';
20
+ export { DB_NAME, type LeafIdentity, LeafStore, type MediatorConfig, type StoredDelivery } from './pwa/store.ts';
@@ -68,12 +68,15 @@ export function startBrowserLeaf(opts: BrowserLeafOptions): LeafHub {
68
68
  // Drains run one after another. Two at once - the launch drain and a
69
69
  // tab's request, say - would each be handed the same unacked batch.
70
70
  let queue: Promise<unknown> = Promise.resolve();
71
- const once = async () => {
71
+ const ensureConnected = async () => {
72
72
  if (!session.connected) {
73
73
  h.setStatus('connecting');
74
74
  await session.resume();
75
75
  h.setStatus('connected');
76
76
  }
77
+ };
78
+ const once = async () => {
79
+ await ensureConnected();
77
80
  // Only what the inbox did not already hold is news.
78
81
  return store.addToInbox(await session.pickup());
79
82
  };
@@ -85,6 +88,32 @@ export function startBrowserLeaf(opts: BrowserLeafOptions): LeafHub {
85
88
  queue = p.catch(() => {});
86
89
  return p;
87
90
  },
91
+ updateKeylist: (add = [], remove = []) => {
92
+ const p = queue.then(async () => {
93
+ await ensureConnected();
94
+ const res = await session.updateKeylist(add, remove);
95
+ await store.saveState(session.client.snapshot());
96
+ return res;
97
+ });
98
+ queue = p.catch(() => {});
99
+ return p;
100
+ },
101
+ sendForward: (recipientDid, message, forwardOpts) => {
102
+ const p = queue.then(async () => {
103
+ await ensureConnected();
104
+ return session.sendForward(recipientDid, message, forwardOpts);
105
+ });
106
+ queue = p.catch(() => {});
107
+ return p;
108
+ },
109
+ reconcile: (filter, items, reconcileOpts) => {
110
+ const p = queue.then(async () => {
111
+ await ensureConnected();
112
+ return session.reconcile(filter, items, reconcileOpts);
113
+ });
114
+ queue = p.catch(() => {});
115
+ return p;
116
+ },
88
117
  close: () => {
89
118
  clearTimeout(initTimer);
90
119
  document.removeEventListener('visibilitychange', onVisible);
package/src/pwa/hub.ts CHANGED
@@ -6,18 +6,25 @@
6
6
  // failover - when the leader's tab closes, crashes or stop()s, the browser
7
7
  // grants the lock to the next tab, which becomes leader and connects.
8
8
  // Followers reach the leader over a BroadcastChannel: they call it (pickup,
9
- // status) and hear what it hears (deliveries, status changes).
9
+ // status, keylist, forward, reconcile) and hear what it hears (deliveries,
10
+ // status changes).
10
11
  //
11
12
  // Why not a service worker: browsers stop an idle worker within about thirty
12
13
  // seconds and an open WebSocket does not keep it alive, so a worker cannot
13
14
  // hold this connection. The worker's job is push-to-wake and the app shell.
14
15
  import type { OpenedDelivery } from '../mediation/leaf.ts';
16
+ import type { Item, ReconcileReport } from '../negentropy.ts';
17
+ import type { Filter } from '../relay.ts';
18
+ import type { SendForwardOptions } from '../session.ts';
15
19
 
16
20
  export type LeafStatus = 'idle' | 'connecting' | 'connected' | 'offline' | 'error';
17
21
 
18
22
  /** What the leader tab runs. */
19
23
  export interface Leader {
20
24
  pickup(): Promise<OpenedDelivery[]>;
25
+ updateKeylist?(add?: string[], remove?: string[]): Promise<unknown>;
26
+ sendForward?(recipientDid: string, message: Record<string, unknown>, opts?: SendForwardOptions): Promise<string[]>;
27
+ reconcile?(filter: Filter, items: Item[], opts?: { maxRounds?: number }): Promise<ReconcileReport>;
21
28
  close(): void;
22
29
  }
23
30
 
@@ -27,7 +34,19 @@ export type HubEvent =
27
34
  | { t: 'delivered'; deliveries: OpenedDelivery[] };
28
35
 
29
36
  type Wire =
30
- | { t: 'call'; id: string; op: 'pickup' | 'status' }
37
+ | {
38
+ t: 'call';
39
+ id: string;
40
+ op: 'pickup' | 'status' | 'keylist' | 'forward' | 'reconcile';
41
+ add?: string[];
42
+ remove?: string[];
43
+ recipientDid?: string;
44
+ message?: Record<string, unknown>;
45
+ forwardOpts?: SendForwardOptions;
46
+ filter?: Filter;
47
+ items?: Item[];
48
+ reconcileOpts?: { maxRounds?: number };
49
+ }
31
50
  | { t: 'reply'; id: string; ok: boolean; value?: unknown; error?: string }
32
51
  | Extract<HubEvent, { t: 'status' | 'delivered' }>;
33
52
 
@@ -87,8 +106,10 @@ export class LeafHub {
87
106
  }
88
107
 
89
108
  private async becomeLeader(): Promise<void> {
109
+ if (this.abort.signal.aborted) return;
90
110
  this.role = 'leader';
91
111
  this.emit({ t: 'role', role: 'leader' });
112
+ if (this.abort.signal.aborted) return;
92
113
  const held = new Promise<void>((r) => (this.release = r));
93
114
  try {
94
115
  this.setStatus('connecting');
@@ -113,12 +134,57 @@ export class LeafHub {
113
134
  return this.call('pickup') as Promise<OpenedDelivery[]>;
114
135
  }
115
136
 
137
+ /** Update the mediator keylist: here if this tab leads, else through the leader. */
138
+ async updateKeylist(add: string[] = [], remove: string[] = []): Promise<unknown> {
139
+ if (this.role === 'leader') {
140
+ if (!this.leader) throw new Error('the leader is not connected');
141
+ if (!this.leader.updateKeylist) throw new Error('this leader does not support updateKeylist');
142
+ const res = await this.leader.updateKeylist(add, remove);
143
+ this.setStatus(this.status);
144
+ return res;
145
+ }
146
+ return this.call('keylist', { add, remove });
147
+ }
148
+
149
+ /** Send a routing/2.0/forward through the mediator: here if this tab leads, else through the leader. */
150
+ async sendForward(recipientDid: string, message: Record<string, unknown>, opts?: SendForwardOptions): Promise<string[]> {
151
+ if (this.role === 'leader') {
152
+ if (!this.leader) throw new Error('the leader is not connected');
153
+ if (!this.leader.sendForward) throw new Error('this leader does not support sendForward');
154
+ return this.leader.sendForward(recipientDid, message, opts);
155
+ }
156
+ return this.call('forward', { recipientDid, message, ...(opts ? { forwardOpts: opts } : {}) }) as Promise<string[]>;
157
+ }
158
+
159
+ /** Run NIP-77 Negentropy reconciliation: here if this tab leads, else through the leader. */
160
+ async reconcile(filter: Filter, items: Iterable<Item>, opts?: { maxRounds?: number }): Promise<ReconcileReport> {
161
+ const itemList = [...items];
162
+ if (this.role === 'leader') {
163
+ if (!this.leader) throw new Error('the leader is not connected');
164
+ if (!this.leader.reconcile) throw new Error('this leader does not support reconcile');
165
+ return this.leader.reconcile(filter, itemList, opts);
166
+ }
167
+ return this.call('reconcile', { filter, items: itemList, ...(opts ? { reconcileOpts: opts } : {}) }) as Promise<ReconcileReport>;
168
+ }
169
+
116
170
  /** The leader's status, asked of it (a follower's own copy may be stale). */
117
171
  async leaderStatus(): Promise<LeafStatus> {
118
172
  return this.role === 'leader' ? this.status : (this.call('status') as Promise<LeafStatus>);
119
173
  }
120
174
 
121
- private call(op: 'pickup' | 'status'): Promise<unknown> {
175
+ private call(
176
+ op: 'pickup' | 'status' | 'keylist' | 'forward' | 'reconcile',
177
+ extra?: {
178
+ add?: string[];
179
+ remove?: string[];
180
+ recipientDid?: string;
181
+ message?: Record<string, unknown>;
182
+ forwardOpts?: SendForwardOptions;
183
+ filter?: Filter;
184
+ items?: Item[];
185
+ reconcileOpts?: { maxRounds?: number };
186
+ },
187
+ ): Promise<unknown> {
122
188
  const id = rid();
123
189
  return new Promise((resolve, reject) => {
124
190
  const timer = setTimeout(() => {
@@ -126,7 +192,7 @@ export class LeafHub {
126
192
  reject(new Error(`no leader answered ${op} in ${this.opts.timeoutMs ?? 20000}ms`));
127
193
  }, this.opts.timeoutMs ?? 20000);
128
194
  this.calls.set(id, { resolve, reject, timer });
129
- this.channel.postMessage({ t: 'call', id, op } satisfies Wire);
195
+ this.channel.postMessage({ t: 'call', id, op, ...extra } satisfies Wire);
130
196
  });
131
197
  }
132
198
 
@@ -135,7 +201,16 @@ export class LeafHub {
135
201
  if (m.t === 'call') {
136
202
  if (this.role !== 'leader') return;
137
203
  try {
138
- const value = m.op === 'pickup' ? await this.pickup() : this.status;
204
+ const value =
205
+ m.op === 'pickup'
206
+ ? await this.pickup()
207
+ : m.op === 'keylist'
208
+ ? await this.updateKeylist(m.add ?? [], m.remove ?? [])
209
+ : m.op === 'forward'
210
+ ? await this.sendForward(m.recipientDid ?? '', m.message ?? {}, m.forwardOpts)
211
+ : m.op === 'reconcile'
212
+ ? await this.reconcile(m.filter ?? {}, m.items ?? [], m.reconcileOpts)
213
+ : this.status;
139
214
  this.channel.postMessage({ t: 'reply', id: m.id, ok: true, value } satisfies Wire);
140
215
  } catch (e) {
141
216
  this.channel.postMessage({ t: 'reply', id: m.id, ok: false, error: (e as Error).message } satisfies Wire);
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, and NIP-42 AUTH answered with the leaf's node key.
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;