@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/dist/session.d.ts CHANGED
@@ -1,9 +1,20 @@
1
- import { type NostrEvent } from './event.ts';
2
- import { LeafClient, type LeafClientState, type OpenedDelivery } from './mediation/leaf.ts';
3
- import { type SocketFactory } from './relay.ts';
4
- import { type Opened } from './seal.ts';
1
+ import { type NostrEvent } from './event.js';
2
+ import { LeafClient, type LeafClientState, type OpenedDelivery } from './mediation/leaf.js';
3
+ import type { Item, ReconcileReport } from './negentropy.js';
4
+ import { type Filter, type SocketFactory } from './relay.js';
5
+ import { type Opened } from './seal.js';
5
6
  export declare class SessionError extends Error {
6
7
  }
8
+ export interface SendForwardOptions {
9
+ /** 64-hex leaf pubkey that owns the X25519 #agree key when recipientDid is a bound alias DID. */
10
+ recipientLeafPubkey?: string;
11
+ /** Explicit 32-byte X25519 agreement public key for the recipient leaf; resolved from kind 11801 when omitted. */
12
+ recipientAgreementPub?: Uint8Array;
13
+ /** Target mediator DID; defaults to this session's mediatorDid. */
14
+ mediatorDid?: string;
15
+ /** Use anoncrypt (ECDH-ES+A256KW) instead of authcrypt (ECDH-1PU+A256KW). Default false. */
16
+ anoncrypt?: boolean;
17
+ }
7
18
  export interface LeafSessionOptions {
8
19
  /** The leaf's node key (secp256k1, hex) and agreement key (X25519, raw). */
9
20
  nodeSk: string;
@@ -38,6 +49,7 @@ export declare class LeafSession {
38
49
  private relay;
39
50
  private sub;
40
51
  private mediatorAgreement;
52
+ private readonly peerAgreements;
41
53
  private descriptor;
42
54
  private readonly waiters;
43
55
  private readonly seen;
@@ -46,8 +58,11 @@ export declare class LeafSession {
46
58
  private newRelay;
47
59
  private get timeout();
48
60
  get connected(): boolean;
61
+ private isLiveDescriptor;
49
62
  /** The mediator's agreement key, from a descriptor it signed and that is live. */
50
63
  private learnMediator;
64
+ /** Resolve a peer's X25519 agreement key from cache or by querying its live kind 11801 descriptor. */
65
+ resolvePeerAgreement(pubkeyOrDid: string): Promise<Uint8Array | null>;
51
66
  private within;
52
67
  /** Connect, learn the mediator, publish this leaf's descriptor, listen. */
53
68
  start(): Promise<void>;
@@ -64,6 +79,8 @@ export declare class LeafSession {
64
79
  private request;
65
80
  requestMediation(): Promise<'granted' | 'denied'>;
66
81
  updateKeylist(add?: string[], remove?: string[]): Promise<import("./mediation/messages.ts").KeylistUpdated[]>;
82
+ /** Pre-resolve any unknown authcrypt sender agreement keys referenced in a delivery batch. */
83
+ private prefetchDeliverySenders;
67
84
  /** Drain every registered key until the mediator has nothing left, acking
68
85
  * each batch so it purges what was taken. maxRounds bounds a mediator that
69
86
  * keeps returning the same batch. */
@@ -72,4 +89,10 @@ export declare class LeafSession {
72
89
  maxRounds?: number;
73
90
  resolveSender?: (skid: string) => Uint8Array | null | undefined;
74
91
  }): Promise<OpenedDelivery[]>;
92
+ /** Encrypt an inner DIDComm message to a recipient and publish a routing/2.0/forward through the mediator. */
93
+ sendForward(recipientDid: string, message: Record<string, unknown>, opts?: SendForwardOptions): Promise<string[]>;
94
+ /** Run a NIP-77 Negentropy V1 range reconciliation over the active relay connection. */
95
+ reconcile(filter: Filter, items: Iterable<Item>, opts?: {
96
+ maxRounds?: number;
97
+ }): Promise<ReconcileReport>;
75
98
  }
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.1",
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",
@@ -11,14 +11,41 @@
11
11
  "types": "./dist/index.d.ts",
12
12
  "default": "./dist/index.js"
13
13
  },
14
- "./src/*": "./src/*"
14
+ "./*": {
15
+ "types": "./dist/*.d.ts",
16
+ "default": "./dist/*.js"
17
+ }
15
18
  },
19
+ "sideEffects": false,
16
20
  "files": [
17
21
  "dist",
18
22
  "src"
19
23
  ],
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "keywords": [
28
+ "fleetmesh",
29
+ "leaf",
30
+ "didcomm",
31
+ "nostr",
32
+ "nip-44",
33
+ "nip-59",
34
+ "nip-77",
35
+ "negentropy",
36
+ "bip340",
37
+ "x25519",
38
+ "pwa"
39
+ ],
40
+ "devEngines": {
41
+ "runtime": {
42
+ "name": "node",
43
+ "version": "^22.18.0 || ^24.0.0 || >=26.0.0",
44
+ "onFail": "warn"
45
+ }
46
+ },
20
47
  "scripts": {
21
- "build": "tsc --ignoreConfig --target ES2022 --module ESNext --moduleResolution Bundler --lib ES2022,DOM --strict --declaration --rewriteRelativeImportExtensions --outDir dist --rootDir src src/index.ts",
48
+ "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
49
  "prepack": "npm run build",
23
50
  "test": "vitest run --project node",
24
51
  "test:browser": "vitest run --project browser",
package/src/did.ts CHANGED
@@ -12,6 +12,7 @@ import { schnorr } from '@noble/curves/secp256k1.js';
12
12
  import { base58 } from '@scure/base';
13
13
  import { DESCRIPTOR, DID } from './constants.ts';
14
14
  import { b64u, b64uDec, bytesToHex, canonicalJson, fromUtf8, hexToBytes, isHex, utf8 } from './encoding.ts';
15
+ import { sha256 } from '@noble/hashes/sha2.js';
15
16
  import { type KeyKind, KEY_KINDS, multikey, parseMultikey } from './keys.ts';
16
17
 
17
18
  export interface ServiceEndpoint { uri?: string; accept?: string[]; routingKeys?: string[] }
@@ -220,3 +221,41 @@ export function document(desc: Descriptor): Document {
220
221
  service: services,
221
222
  };
222
223
  }
224
+
225
+ // ---------------------------------------------------------------------------
226
+ // did:web and deterministic identifiers shared by the protocol packages.
227
+
228
+ /** Hex of SHA-256(seed), extended with SHA-256(seed + ":1") when more than 64
229
+ * hex digits are asked for. The one derivation every package uses for
230
+ * synthetic, reproducible identifiers. */
231
+ export function deterministicHexHash(seed: string, length = 64): string {
232
+ const full = bytesToHex(sha256(utf8(seed)));
233
+ if (length <= 64) return full.slice(0, length);
234
+ return (full + bytesToHex(sha256(utf8(`${seed}:1`)))).slice(0, length);
235
+ }
236
+
237
+ /** A DNS-label-safe slug for a human name; `fallback` when nothing survives. */
238
+ export function slugifyDidName(raw: string, fallback = 'fleetmesh-entity'): string {
239
+ const cleaned = (raw || '')
240
+ .toLowerCase()
241
+ .replace(/[^a-z0-9-_]+/g, '-')
242
+ .replace(/-+/g, '-')
243
+ .replace(/^-|-$/g, '');
244
+ return cleaned || fallback;
245
+ }
246
+
247
+ export interface DidWebDomain { domain: string; didWeb: string; wellKnownUrl: string }
248
+
249
+ /** Normalises user input (a bare domain, a URL, or a did:web) to the did:web
250
+ * triple. Input with no dot becomes `<slug>.<defaultZone>`. */
251
+ export function normalizeDidWebDomain(rawInput: string, defaultZone = 'fleetmesh.org', slugFallback = 'node'): DidWebDomain {
252
+ let clean = (rawInput || '').trim().toLowerCase();
253
+ if (clean.startsWith('did:web:')) clean = clean.slice('did:web:'.length);
254
+ clean = clean
255
+ .replace(/^https?:\/\//, '')
256
+ .replace(/\/.*$/, '')
257
+ .replace(/:\d+$/, '')
258
+ .replace(/[^a-z0-9.-]/g, '');
259
+ if (!clean || !clean.includes('.')) clean = `${slugifyDidName(rawInput || slugFallback, slugFallback)}.${defaultZone}`;
260
+ return { domain: clean, didWeb: `did:web:${clean}`, wellKnownUrl: `https://${clean}/.well-known/did.json` };
261
+ }
package/src/encoding.ts CHANGED
@@ -37,6 +37,11 @@ export function b64uDec(s: string): Uint8Array {
37
37
  return out;
38
38
  }
39
39
 
40
+ /** base64url (no padding) of a string's UTF-8 bytes: JWS-style segment encoding. */
41
+ export const b64uUtf8 = (s: string): string => b64u(utf8(s));
42
+ /** Inverse of `b64uUtf8`; strict, like `b64uDec`. */
43
+ export const b64uUtf8Dec = (s: string): string => fromUtf8(b64uDec(s));
44
+
40
45
  // Python sorts keys by code point; JS's default sort is by UTF-16 unit, which
41
46
  // differs above the BMP.
42
47
  function byCodePoint(a: string, b: string): number {
@@ -48,20 +53,35 @@ function byCodePoint(a: string, b: string): number {
48
53
  return x.length - y.length;
49
54
  }
50
55
 
51
- /** Canonical JSON: sorted keys, no whitespace, non-ASCII left as is. Numbers
52
- * must be integers: Python spells 1.0 as "1.0" and JS as "1", so a float
53
- * cannot be made to agree and is refused. */
54
- export function canonicalJson(v: unknown): string {
56
+ export interface CanonicalJsonOptions {
57
+ /** `'integers'` (default) refuses any non-safe-integer number: Python spells 1.0 as
58
+ * "1.0" and JS as "1", so a float cannot be made to agree across runtimes and the
59
+ * caller must fix its data. `'js'` accepts finite floats and spells them as
60
+ * `JSON.stringify` does; this is the byte form the textile shards were published
61
+ * with and must keep. */
62
+ numbers?: 'integers' | 'js';
63
+ }
64
+
65
+ /** Canonical JSON: keys sorted by code point at every level (as Python
66
+ * `json.dumps(sort_keys=True, separators=(',', ':'))`), `undefined` members
67
+ * dropped, `undefined` array items spelled `null`, no whitespace, non-ASCII left as
68
+ * is. See `CanonicalJsonOptions.numbers` for the one semantic choice. */
69
+ export function canonicalJson(v: unknown, opts: CanonicalJsonOptions = {}): string {
70
+ const numbers = opts.numbers ?? 'integers';
55
71
  if (v === null || typeof v === 'boolean' || typeof v === 'string') return JSON.stringify(v);
56
72
  if (typeof v === 'number') {
73
+ if (numbers === 'js') {
74
+ if (!Number.isFinite(v)) throw new Error('canonical JSON cannot carry NaN or Infinity');
75
+ return JSON.stringify(v);
76
+ }
57
77
  if (!Number.isSafeInteger(v)) throw new Error('canonical JSON carries integers only');
58
78
  return String(v);
59
79
  }
60
- if (Array.isArray(v)) return '[' + v.map((el) => canonicalJson(el === undefined ? null : el)).join(',') + ']';
80
+ if (Array.isArray(v)) return '[' + v.map((el) => canonicalJson(el === undefined ? null : el, opts)).join(',') + ']';
61
81
  if (typeof v === 'object') {
62
82
  const o = v as Record<string, unknown>;
63
83
  return '{' + Object.keys(o).filter((k) => o[k] !== undefined).sort(byCodePoint)
64
- .map((k) => JSON.stringify(k) + ':' + canonicalJson(o[k])).join(',') + '}';
84
+ .map((k) => JSON.stringify(k) + ':' + canonicalJson(o[k], opts)).join(',') + '}';
65
85
  }
66
86
  throw new Error('not JSON: ' + typeof v);
67
87
  }
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);