@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 CHANGED
@@ -78,6 +78,18 @@ import { startBrowserLeaf } from '@fleetmesh/leaf';
78
78
 
79
79
  const hub = startBrowserLeaf({ mediator: { pubkey: '<anchor node key>', endpoint: 'wss://anchor.example' } });
80
80
  hub.on((e) => { if (e.t === 'delivered') render(e.deliveries); });
81
+
82
+ // Outbound DIDComm v2 forward (authcrypt when peer X25519 key is known, anoncrypt fallback):
83
+ await hub.sendForward('did:nostr:<recipient>', {
84
+ id: 'msg-1',
85
+ type: 'https://didcomm.org/basicmessage/2.0/message',
86
+ from: `did:nostr:${leafPubkey}`,
87
+ to: ['did:nostr:<recipient>'],
88
+ body: { content: 'hello' },
89
+ });
90
+
91
+ // NIP-77 Negentropy set reconciliation over the shared relay session:
92
+ const { have, need } = await hub.reconcile({ kinds: [11801] }, localItems);
81
93
  ```
82
94
 
83
95
  - **One connection per origin.** Every tab asks Web Locks for one lock; the
@@ -1,4 +1,4 @@
1
- import { type NostrEvent, type Tags } from './event.ts';
1
+ import { type NostrEvent, type Tags } from './event.js';
2
2
  export declare const KIND = 11801;
3
3
  export declare const SOFTWARE: [string, string];
4
4
  export interface LeafDescriptorOptions {
package/dist/did.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type KeyKind } from './keys.ts';
1
+ import { type KeyKind } from './keys.js';
2
2
  export interface ServiceEndpoint {
3
3
  uri?: string;
4
4
  accept?: string[];
@@ -57,3 +57,17 @@ export declare function nodeOfDid(didOrKid: string): string;
57
57
  export declare function didcommService(desc: Descriptor): Service | null;
58
58
  /** The node profile a did:nostr resolver emits for a kind 11801, with its aliases. */
59
59
  export declare function document(desc: Descriptor): Document;
60
+ /** Hex of SHA-256(seed), extended with SHA-256(seed + ":1") when more than 64
61
+ * hex digits are asked for. The one derivation every package uses for
62
+ * synthetic, reproducible identifiers. */
63
+ export declare function deterministicHexHash(seed: string, length?: number): string;
64
+ /** A DNS-label-safe slug for a human name; `fallback` when nothing survives. */
65
+ export declare function slugifyDidName(raw: string, fallback?: string): string;
66
+ export interface DidWebDomain {
67
+ domain: string;
68
+ didWeb: string;
69
+ wellKnownUrl: string;
70
+ }
71
+ /** Normalises user input (a bare domain, a URL, or a did:web) to the did:web
72
+ * triple. Input with no dot becomes `<slug>.<defaultZone>`. */
73
+ export declare function normalizeDidWebDomain(rawInput: string, defaultZone?: string, slugFallback?: string): DidWebDomain;
package/dist/did.js 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.js';
14
14
  import { b64u, b64uDec, bytesToHex, canonicalJson, fromUtf8, hexToBytes, isHex, utf8 } from './encoding.js';
15
+ import { sha256 } from '@noble/hashes/sha2.js';
15
16
  import { KEY_KINDS, multikey, parseMultikey } from './keys.js';
16
17
  const CODEC = {
17
18
  node: hexToBytes(DID.multicodec.node),
@@ -219,3 +220,38 @@ export function document(desc) {
219
220
  service: services,
220
221
  };
221
222
  }
223
+ // ---------------------------------------------------------------------------
224
+ // did:web and deterministic identifiers shared by the protocol packages.
225
+ /** Hex of SHA-256(seed), extended with SHA-256(seed + ":1") when more than 64
226
+ * hex digits are asked for. The one derivation every package uses for
227
+ * synthetic, reproducible identifiers. */
228
+ export function deterministicHexHash(seed, length = 64) {
229
+ const full = bytesToHex(sha256(utf8(seed)));
230
+ if (length <= 64)
231
+ return full.slice(0, length);
232
+ return (full + bytesToHex(sha256(utf8(`${seed}:1`)))).slice(0, length);
233
+ }
234
+ /** A DNS-label-safe slug for a human name; `fallback` when nothing survives. */
235
+ export function slugifyDidName(raw, fallback = 'fleetmesh-entity') {
236
+ const cleaned = (raw || '')
237
+ .toLowerCase()
238
+ .replace(/[^a-z0-9-_]+/g, '-')
239
+ .replace(/-+/g, '-')
240
+ .replace(/^-|-$/g, '');
241
+ return cleaned || fallback;
242
+ }
243
+ /** Normalises user input (a bare domain, a URL, or a did:web) to the did:web
244
+ * triple. Input with no dot becomes `<slug>.<defaultZone>`. */
245
+ export function normalizeDidWebDomain(rawInput, defaultZone = 'fleetmesh.org', slugFallback = 'node') {
246
+ let clean = (rawInput || '').trim().toLowerCase();
247
+ if (clean.startsWith('did:web:'))
248
+ clean = clean.slice('did:web:'.length);
249
+ clean = clean
250
+ .replace(/^https?:\/\//, '')
251
+ .replace(/\/.*$/, '')
252
+ .replace(/:\d+$/, '')
253
+ .replace(/[^a-z0-9.-]/g, '');
254
+ if (!clean || !clean.includes('.'))
255
+ clean = `${slugifyDidName(rawInput || slugFallback, slugFallback)}.${defaultZone}`;
256
+ return { domain: clean, didWeb: `did:web:${clean}`, wellKnownUrl: `https://${clean}/.well-known/did.json` };
257
+ }
@@ -8,7 +8,20 @@ export declare function b64u(b: Uint8Array): string;
8
8
  /** Strict base64url without padding: the alphabet only, and canonical (no
9
9
  * trailing bits), so two strings never decode to the same bytes. */
10
10
  export declare function b64uDec(s: string): Uint8Array;
11
- /** Canonical JSON: sorted keys, no whitespace, non-ASCII left as is. Numbers
12
- * must be integers: Python spells 1.0 as "1.0" and JS as "1", so a float
13
- * cannot be made to agree and is refused. */
14
- export declare function canonicalJson(v: unknown): string;
11
+ /** base64url (no padding) of a string's UTF-8 bytes: JWS-style segment encoding. */
12
+ export declare const b64uUtf8: (s: string) => string;
13
+ /** Inverse of `b64uUtf8`; strict, like `b64uDec`. */
14
+ export declare const b64uUtf8Dec: (s: string) => string;
15
+ export interface CanonicalJsonOptions {
16
+ /** `'integers'` (default) refuses any non-safe-integer number: Python spells 1.0 as
17
+ * "1.0" and JS as "1", so a float cannot be made to agree across runtimes and the
18
+ * caller must fix its data. `'js'` accepts finite floats and spells them as
19
+ * `JSON.stringify` does; this is the byte form the textile shards were published
20
+ * with and must keep. */
21
+ numbers?: 'integers' | 'js';
22
+ }
23
+ /** Canonical JSON: keys sorted by code point at every level (as Python
24
+ * `json.dumps(sort_keys=True, separators=(',', ':'))`), `undefined` members
25
+ * dropped, `undefined` array items spelled `null`, no whitespace, non-ASCII left as
26
+ * is. See `CanonicalJsonOptions.numbers` for the one semantic choice. */
27
+ export declare function canonicalJson(v: unknown, opts?: CanonicalJsonOptions): string;
package/dist/encoding.js CHANGED
@@ -35,6 +35,10 @@ export function b64uDec(s) {
35
35
  throw new Error('not canonical base64url');
36
36
  return out;
37
37
  }
38
+ /** base64url (no padding) of a string's UTF-8 bytes: JWS-style segment encoding. */
39
+ export const b64uUtf8 = (s) => b64u(utf8(s));
40
+ /** Inverse of `b64uUtf8`; strict, like `b64uDec`. */
41
+ export const b64uUtf8Dec = (s) => fromUtf8(b64uDec(s));
38
42
  // Python sorts keys by code point; JS's default sort is by UTF-16 unit, which
39
43
  // differs above the BMP.
40
44
  function byCodePoint(a, b) {
@@ -46,23 +50,30 @@ function byCodePoint(a, b) {
46
50
  }
47
51
  return x.length - y.length;
48
52
  }
49
- /** Canonical JSON: sorted keys, no whitespace, non-ASCII left as is. Numbers
50
- * must be integers: Python spells 1.0 as "1.0" and JS as "1", so a float
51
- * cannot be made to agree and is refused. */
52
- export function canonicalJson(v) {
53
+ /** Canonical JSON: keys sorted by code point at every level (as Python
54
+ * `json.dumps(sort_keys=True, separators=(',', ':'))`), `undefined` members
55
+ * dropped, `undefined` array items spelled `null`, no whitespace, non-ASCII left as
56
+ * is. See `CanonicalJsonOptions.numbers` for the one semantic choice. */
57
+ export function canonicalJson(v, opts = {}) {
58
+ const numbers = opts.numbers ?? 'integers';
53
59
  if (v === null || typeof v === 'boolean' || typeof v === 'string')
54
60
  return JSON.stringify(v);
55
61
  if (typeof v === 'number') {
62
+ if (numbers === 'js') {
63
+ if (!Number.isFinite(v))
64
+ throw new Error('canonical JSON cannot carry NaN or Infinity');
65
+ return JSON.stringify(v);
66
+ }
56
67
  if (!Number.isSafeInteger(v))
57
68
  throw new Error('canonical JSON carries integers only');
58
69
  return String(v);
59
70
  }
60
71
  if (Array.isArray(v))
61
- return '[' + v.map((el) => canonicalJson(el === undefined ? null : el)).join(',') + ']';
72
+ return '[' + v.map((el) => canonicalJson(el === undefined ? null : el, opts)).join(',') + ']';
62
73
  if (typeof v === 'object') {
63
74
  const o = v;
64
75
  return '{' + Object.keys(o).filter((k) => o[k] !== undefined).sort(byCodePoint)
65
- .map((k) => JSON.stringify(k) + ':' + canonicalJson(o[k])).join(',') + '}';
76
+ .map((k) => JSON.stringify(k) + ':' + canonicalJson(o[k], opts)).join(',') + '}';
66
77
  }
67
78
  throw new Error('not JSON: ' + typeof v);
68
79
  }
@@ -1,4 +1,4 @@
1
- import { type NostrEvent } from './event.ts';
1
+ import { type NostrEvent } from './event.js';
2
2
  export declare const SEAL = 13;
3
3
  export declare const WRAP_LIVE = 21059;
4
4
  export declare const WRAP_STORED = 1059;
package/dist/index.d.ts CHANGED
@@ -1,17 +1,17 @@
1
- export * as descriptor from './descriptor.ts';
2
- export * as did from './did.ts';
3
- export * as didcomm from './didcomm.ts';
4
- export * as encoding from './encoding.ts';
5
- export * as event from './event.ts';
6
- export * as giftwrap from './giftwrap.ts';
7
- export * as keys from './keys.ts';
8
- export * as mediation from './mediation/leaf.ts';
9
- export * as mediationMessages from './mediation/messages.ts';
10
- export * as negentropy from './negentropy.ts';
11
- export * as nip44 from './nip44.ts';
12
- export * as relay from './relay.ts';
13
- export * as seal from './seal.ts';
14
- export { LeafSession, type LeafSessionOptions, SessionError } from './session.ts';
15
- export { type BrowserLeafOptions, startBrowserLeaf, SW_PICKUP } from './pwa/browser-leaf.ts';
16
- export { type HubEvent, LeafHub, type LeafStatus } from './pwa/hub.ts';
17
- export { LeafStore } from './pwa/store.ts';
1
+ export * as descriptor from './descriptor.js';
2
+ export * as did from './did.js';
3
+ export * as didcomm from './didcomm.js';
4
+ export * as encoding from './encoding.js';
5
+ export * as event from './event.js';
6
+ export * as giftwrap from './giftwrap.js';
7
+ export * as keys from './keys.js';
8
+ export * as mediation from './mediation/leaf.js';
9
+ export * as mediationMessages from './mediation/messages.js';
10
+ export * as negentropy from './negentropy.js';
11
+ export * as nip44 from './nip44.js';
12
+ export * as relay from './relay.js';
13
+ export * as seal from './seal.js';
14
+ export { LeafSession, type LeafSessionOptions, type SendForwardOptions, SessionError } from './session.js';
15
+ export { type BrowserLeafOptions, startBrowserLeaf, SW_PICKUP } from './pwa/browser-leaf.js';
16
+ export { type HubEvent, type HubOptions, type Leader, LeafHub, type LeafStatus } from './pwa/hub.js';
17
+ export { DB_NAME, type LeafIdentity, LeafStore, type MediatorConfig, type StoredDelivery } from './pwa/store.js';
package/dist/index.js CHANGED
@@ -17,4 +17,4 @@ export * as seal from './seal.js';
17
17
  export { LeafSession, SessionError } from './session.js';
18
18
  export { startBrowserLeaf, SW_PICKUP } from './pwa/browser-leaf.js';
19
19
  export { LeafHub } from './pwa/hub.js';
20
- export { LeafStore } from './pwa/store.js';
20
+ export { DB_NAME, LeafStore } from './pwa/store.js';
@@ -1,5 +1,5 @@
1
- import { type NostrEvent } from '../event.ts';
2
- import { type ForwardBody, type KeylistUpdateBody, type KeylistUpdateResponseBody, type MediateDenyBody, type MediateGrantBody, type Message, type PickupDeliveryBody, type PickupDeliveryRequestBody, type PickupMessagesReceivedBody } from './messages.ts';
1
+ import { type NostrEvent } from '../event.js';
2
+ import { type ForwardBody, type KeylistUpdateBody, type KeylistUpdateResponseBody, type MediateDenyBody, type MediateGrantBody, type Message, type PickupDeliveryBody, type PickupDeliveryRequestBody, type PickupMessagesReceivedBody } from './messages.js';
3
3
  /** NIP-66 / kind 11801 query a leaf with no peers sends to bootstrap relays. */
4
4
  export declare const DESCRIPTOR_KIND = 11801;
5
5
  export declare const COLD_START_FILTER: {
@@ -1,6 +1,6 @@
1
- import { LeafHub } from './hub.ts';
2
- import { type MediatorConfig } from './store.ts';
3
- import type { SocketFactory } from '../relay.ts';
1
+ import { LeafHub } from './hub.js';
2
+ import { type MediatorConfig } from './store.js';
3
+ import type { SocketFactory } from '../relay.js';
4
4
  export interface BrowserLeafOptions {
5
5
  mediator: MediatorConfig;
6
6
  name?: string;
@@ -60,12 +60,15 @@ export function startBrowserLeaf(opts) {
60
60
  // Drains run one after another. Two at once - the launch drain and a
61
61
  // tab's request, say - would each be handed the same unacked batch.
62
62
  let queue = Promise.resolve();
63
- const once = async () => {
63
+ const ensureConnected = async () => {
64
64
  if (!session.connected) {
65
65
  h.setStatus('connecting');
66
66
  await session.resume();
67
67
  h.setStatus('connected');
68
68
  }
69
+ };
70
+ const once = async () => {
71
+ await ensureConnected();
69
72
  // Only what the inbox did not already hold is news.
70
73
  return store.addToInbox(await session.pickup());
71
74
  };
@@ -77,6 +80,32 @@ export function startBrowserLeaf(opts) {
77
80
  queue = p.catch(() => { });
78
81
  return p;
79
82
  },
83
+ updateKeylist: (add = [], remove = []) => {
84
+ const p = queue.then(async () => {
85
+ await ensureConnected();
86
+ const res = await session.updateKeylist(add, remove);
87
+ await store.saveState(session.client.snapshot());
88
+ return res;
89
+ });
90
+ queue = p.catch(() => { });
91
+ return p;
92
+ },
93
+ sendForward: (recipientDid, message, forwardOpts) => {
94
+ const p = queue.then(async () => {
95
+ await ensureConnected();
96
+ return session.sendForward(recipientDid, message, forwardOpts);
97
+ });
98
+ queue = p.catch(() => { });
99
+ return p;
100
+ },
101
+ reconcile: (filter, items, reconcileOpts) => {
102
+ const p = queue.then(async () => {
103
+ await ensureConnected();
104
+ return session.reconcile(filter, items, reconcileOpts);
105
+ });
106
+ queue = p.catch(() => { });
107
+ return p;
108
+ },
80
109
  close: () => {
81
110
  clearTimeout(initTimer);
82
111
  document.removeEventListener('visibilitychange', onVisible);
package/dist/pwa/hub.d.ts CHANGED
@@ -1,8 +1,16 @@
1
- import type { OpenedDelivery } from '../mediation/leaf.ts';
1
+ import type { OpenedDelivery } from '../mediation/leaf.js';
2
+ import type { Item, ReconcileReport } from '../negentropy.js';
3
+ import type { Filter } from '../relay.js';
4
+ import type { SendForwardOptions } from '../session.js';
2
5
  export type LeafStatus = 'idle' | 'connecting' | 'connected' | 'offline' | 'error';
3
6
  /** What the leader tab runs. */
4
7
  export interface Leader {
5
8
  pickup(): Promise<OpenedDelivery[]>;
9
+ updateKeylist?(add?: string[], remove?: string[]): Promise<unknown>;
10
+ sendForward?(recipientDid: string, message: Record<string, unknown>, opts?: SendForwardOptions): Promise<string[]>;
11
+ reconcile?(filter: Filter, items: Item[], opts?: {
12
+ maxRounds?: number;
13
+ }): Promise<ReconcileReport>;
6
14
  close(): void;
7
15
  }
8
16
  export type HubEvent = {
@@ -42,6 +50,14 @@ export declare class LeafHub {
42
50
  private becomeLeader;
43
51
  /** Drain the mediator: here if this tab leads, else through the leader. */
44
52
  pickup(): Promise<OpenedDelivery[]>;
53
+ /** Update the mediator keylist: here if this tab leads, else through the leader. */
54
+ updateKeylist(add?: string[], remove?: string[]): Promise<unknown>;
55
+ /** Send a routing/2.0/forward through the mediator: here if this tab leads, else through the leader. */
56
+ sendForward(recipientDid: string, message: Record<string, unknown>, opts?: SendForwardOptions): Promise<string[]>;
57
+ /** Run NIP-77 Negentropy reconciliation: here if this tab leads, else through the leader. */
58
+ reconcile(filter: Filter, items: Iterable<Item>, opts?: {
59
+ maxRounds?: number;
60
+ }): Promise<ReconcileReport>;
45
61
  /** The leader's status, asked of it (a follower's own copy may be stale). */
46
62
  leaderStatus(): Promise<LeafStatus>;
47
63
  private call;
package/dist/pwa/hub.js CHANGED
@@ -45,8 +45,12 @@ export class LeafHub {
45
45
  this.channel.postMessage(e);
46
46
  }
47
47
  async becomeLeader() {
48
+ if (this.abort.signal.aborted)
49
+ return;
48
50
  this.role = 'leader';
49
51
  this.emit({ t: 'role', role: 'leader' });
52
+ if (this.abort.signal.aborted)
53
+ return;
50
54
  const held = new Promise((r) => (this.release = r));
51
55
  try {
52
56
  this.setStatus('connecting');
@@ -71,11 +75,47 @@ export class LeafHub {
71
75
  }
72
76
  return this.call('pickup');
73
77
  }
78
+ /** Update the mediator keylist: here if this tab leads, else through the leader. */
79
+ async updateKeylist(add = [], remove = []) {
80
+ if (this.role === 'leader') {
81
+ if (!this.leader)
82
+ throw new Error('the leader is not connected');
83
+ if (!this.leader.updateKeylist)
84
+ throw new Error('this leader does not support updateKeylist');
85
+ const res = await this.leader.updateKeylist(add, remove);
86
+ this.setStatus(this.status);
87
+ return res;
88
+ }
89
+ return this.call('keylist', { add, remove });
90
+ }
91
+ /** Send a routing/2.0/forward through the mediator: here if this tab leads, else through the leader. */
92
+ async sendForward(recipientDid, message, opts) {
93
+ if (this.role === 'leader') {
94
+ if (!this.leader)
95
+ throw new Error('the leader is not connected');
96
+ if (!this.leader.sendForward)
97
+ throw new Error('this leader does not support sendForward');
98
+ return this.leader.sendForward(recipientDid, message, opts);
99
+ }
100
+ return this.call('forward', { recipientDid, message, ...(opts ? { forwardOpts: opts } : {}) });
101
+ }
102
+ /** Run NIP-77 Negentropy reconciliation: here if this tab leads, else through the leader. */
103
+ async reconcile(filter, items, opts) {
104
+ const itemList = [...items];
105
+ if (this.role === 'leader') {
106
+ if (!this.leader)
107
+ throw new Error('the leader is not connected');
108
+ if (!this.leader.reconcile)
109
+ throw new Error('this leader does not support reconcile');
110
+ return this.leader.reconcile(filter, itemList, opts);
111
+ }
112
+ return this.call('reconcile', { filter, items: itemList, ...(opts ? { reconcileOpts: opts } : {}) });
113
+ }
74
114
  /** The leader's status, asked of it (a follower's own copy may be stale). */
75
115
  async leaderStatus() {
76
116
  return this.role === 'leader' ? this.status : this.call('status');
77
117
  }
78
- call(op) {
118
+ call(op, extra) {
79
119
  const id = rid();
80
120
  return new Promise((resolve, reject) => {
81
121
  const timer = setTimeout(() => {
@@ -83,7 +123,7 @@ export class LeafHub {
83
123
  reject(new Error(`no leader answered ${op} in ${this.opts.timeoutMs ?? 20000}ms`));
84
124
  }, this.opts.timeoutMs ?? 20000);
85
125
  this.calls.set(id, { resolve, reject, timer });
86
- this.channel.postMessage({ t: 'call', id, op });
126
+ this.channel.postMessage({ t: 'call', id, op, ...extra });
87
127
  });
88
128
  }
89
129
  async onWire(m) {
@@ -93,7 +133,15 @@ export class LeafHub {
93
133
  if (this.role !== 'leader')
94
134
  return;
95
135
  try {
96
- const value = m.op === 'pickup' ? await this.pickup() : this.status;
136
+ const value = m.op === 'pickup'
137
+ ? await this.pickup()
138
+ : m.op === 'keylist'
139
+ ? await this.updateKeylist(m.add ?? [], m.remove ?? [])
140
+ : m.op === 'forward'
141
+ ? await this.sendForward(m.recipientDid ?? '', m.message ?? {}, m.forwardOpts)
142
+ : m.op === 'reconcile'
143
+ ? await this.reconcile(m.filter ?? {}, m.items ?? [], m.reconcileOpts)
144
+ : this.status;
97
145
  this.channel.postMessage({ t: 'reply', id: m.id, ok: true, value });
98
146
  }
99
147
  catch (e) {
@@ -1,4 +1,5 @@
1
- import type { LeafClientState, OpenedDelivery } from '../mediation/leaf.ts';
1
+ import type { NostrEvent } from '../event.js';
2
+ import type { LeafClientState, OpenedDelivery } from '../mediation/leaf.js';
2
3
  export declare const DB_NAME = "fleetmesh-leaf";
3
4
  export interface LeafIdentity {
4
5
  nodeSk: string;
@@ -7,6 +8,7 @@ export interface LeafIdentity {
7
8
  export interface MediatorConfig {
8
9
  pubkey: string;
9
10
  endpoint: string;
11
+ descriptor?: NostrEvent;
10
12
  }
11
13
  export interface StoredDelivery extends OpenedDelivery {
12
14
  received_at: number;
package/dist/relay.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { NostrEvent } from './event.ts';
1
+ import type { NostrEvent } from './event.js';
2
+ import { type Item, type ReconcileReport } from './negentropy.js';
2
3
  /** The slice of the WHATWG WebSocket this module uses. */
3
4
  export interface SocketLike {
4
5
  readonly readyState: number;
@@ -43,6 +44,7 @@ export declare class RelayConnection {
43
44
  private authed;
44
45
  private readonly oks;
45
46
  private readonly subs;
47
+ private readonly negs;
46
48
  private seq;
47
49
  constructor(url: string, opts?: RelayOptions);
48
50
  get connected(): boolean;
@@ -57,6 +59,10 @@ export declare class RelayConnection {
57
59
  /** REQ. Events arrive on onEvent until close(); a relay that closes it for
58
60
  * auth-required is answered and asked once more. */
59
61
  subscribe(filters: Filter[], onEvent: (ev: NostrEvent) => void): Subscription;
62
+ /** NIP-77 Negentropy V1 range reconciliation over NEG-OPEN / NEG-MSG / NEG-CLOSE. */
63
+ reconcile(filter: Filter, items: Iterable<Item>, opts?: {
64
+ maxRounds?: number;
65
+ }): Promise<ReconcileReport>;
60
66
  /** Answer the relay's NIP-42 challenge; false if there is none or no signer. */
61
67
  authenticate(): Promise<boolean>;
62
68
  private publishAuth;
package/dist/relay.js CHANGED
@@ -1,3 +1,15 @@
1
+ // One NIP-01 relay connection over a standard WebSocket, which browsers and
2
+ // Node (22+) both provide as a global. EVENT/OK, REQ/EVENT/EOSE/CLOSED, CLOSE,
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).
5
+ //
6
+ // Deliberately one socket and no reconnect policy: a leaf holds exactly one
7
+ // connection, to its mediator (spec § "The leaf profile"), and when it drops
8
+ // the session decides what to do - mobile operating systems kill sockets on
9
+ // screen lock, so "reconnect and catch up" is the session's ordinary path,
10
+ // not this module's error handling.
11
+ import { bytesToHex, hexToBytes } from './encoding.js';
12
+ import { Negentropy } from './negentropy.js';
1
13
  export class RelayError extends Error {
2
14
  }
3
15
  const OPEN = 1;
@@ -15,6 +27,7 @@ export class RelayConnection {
15
27
  authed = null;
16
28
  oks = new Map();
17
29
  subs = new Map();
30
+ negs = new Map();
18
31
  seq = 0;
19
32
  constructor(url, opts = {}) {
20
33
  this.url = url;
@@ -74,6 +87,11 @@ export class RelayConnection {
74
87
  s.closed('error: connection closed');
75
88
  this.subs.delete(id);
76
89
  }
90
+ for (const [id, n] of this.negs) {
91
+ clearTimeout(n.timer);
92
+ n.reject(new RelayError('error: connection closed'));
93
+ this.negs.delete(id);
94
+ }
77
95
  this.challenge = null;
78
96
  this.authed = null;
79
97
  this.opts.onClose?.();
@@ -124,6 +142,54 @@ export class RelayConnection {
124
142
  },
125
143
  };
126
144
  }
145
+ /** NIP-77 Negentropy V1 range reconciliation over NEG-OPEN / NEG-MSG / NEG-CLOSE. */
146
+ reconcile(filter, items, opts = {}) {
147
+ if (!this.connected)
148
+ return Promise.reject(new RelayError('not connected to ' + this.url));
149
+ const id = 'neg-' + (++this.seq).toString(36);
150
+ const maxRounds = opts.maxRounds ?? 32;
151
+ let client;
152
+ let init;
153
+ try {
154
+ client = new Negentropy(items, true);
155
+ init = client.initiate();
156
+ }
157
+ catch (e) {
158
+ return Promise.reject(e);
159
+ }
160
+ return new Promise((resolve, reject) => {
161
+ const timer = setTimeout(() => {
162
+ this.negs.delete(id);
163
+ if (this.connected) {
164
+ try {
165
+ this.send(['NEG-CLOSE', id]);
166
+ }
167
+ catch { /* ignore */ }
168
+ }
169
+ reject(new RelayError(`no NEG-MSG answer in ${this.timeout}ms`));
170
+ }, this.timeout);
171
+ this.negs.set(id, {
172
+ client,
173
+ have: new Set(),
174
+ need: new Set(),
175
+ rounds: 0,
176
+ maxRounds,
177
+ bytesSent: init.length,
178
+ bytesReceived: 0,
179
+ resolve,
180
+ reject,
181
+ timer,
182
+ });
183
+ try {
184
+ this.send(['NEG-OPEN', id, filter, bytesToHex(init)]);
185
+ }
186
+ catch (e) {
187
+ clearTimeout(timer);
188
+ this.negs.delete(id);
189
+ reject(new RelayError('error: ' + e.message));
190
+ }
191
+ });
192
+ }
127
193
  /** Answer the relay's NIP-42 challenge; false if there is none or no signer. */
128
194
  authenticate() {
129
195
  if (this.authed)
@@ -200,6 +266,63 @@ export class RelayConnection {
200
266
  p.resolve({ ok: b === true, message: typeof c === 'string' ? c : '' });
201
267
  break;
202
268
  }
269
+ case 'NEG-MSG': {
270
+ if (typeof a !== 'string' || typeof b !== 'string')
271
+ break;
272
+ const n = this.negs.get(a);
273
+ if (!n)
274
+ break;
275
+ try {
276
+ const replyBytes = hexToBytes(b.toLowerCase());
277
+ n.bytesReceived += replyBytes.length;
278
+ n.rounds += 1;
279
+ const [next, have, need] = n.client.reconcile(replyBytes);
280
+ for (const h of have)
281
+ n.have.add(h);
282
+ for (const nd of need)
283
+ n.need.add(nd);
284
+ if (next === null || n.rounds >= n.maxRounds) {
285
+ clearTimeout(n.timer);
286
+ this.negs.delete(a);
287
+ if (this.connected)
288
+ this.send(['NEG-CLOSE', a]);
289
+ n.resolve({
290
+ have: [...n.have].sort(),
291
+ need: [...n.need].sort(),
292
+ rounds: n.rounds,
293
+ bytesSent: n.bytesSent,
294
+ bytesReceived: n.bytesReceived,
295
+ });
296
+ }
297
+ else {
298
+ n.bytesSent += next.length;
299
+ this.send(['NEG-MSG', a, bytesToHex(next)]);
300
+ }
301
+ }
302
+ catch (e) {
303
+ clearTimeout(n.timer);
304
+ this.negs.delete(a);
305
+ if (this.connected) {
306
+ try {
307
+ this.send(['NEG-CLOSE', a]);
308
+ }
309
+ catch { /* ignore */ }
310
+ }
311
+ n.reject(new RelayError('negentropy: ' + e.message));
312
+ }
313
+ break;
314
+ }
315
+ case 'NEG-ERR': {
316
+ if (typeof a !== 'string')
317
+ break;
318
+ const n = this.negs.get(a);
319
+ if (!n)
320
+ break;
321
+ clearTimeout(n.timer);
322
+ this.negs.delete(a);
323
+ n.reject(new RelayError('negentropy error: ' + (typeof b === 'string' ? b : 'rejected')));
324
+ break;
325
+ }
203
326
  case 'AUTH': {
204
327
  if (typeof a === 'string') {
205
328
  this.challenge = a;
package/dist/seal.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import * as didcomm from './didcomm.ts';
2
- import type { NostrEvent } from './event.ts';
1
+ import * as didcomm from './didcomm.js';
2
+ import type { NostrEvent } from './event.js';
3
3
  export declare const FRAGMENT_BYTES = 24000;
4
4
  export declare const MAX_FRAGMENTS = 64;
5
5
  export declare const ENVELOPE_MAX: number;