@fleetmesh/leaf 0.0.0-stage → 0.1.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.
Files changed (59) hide show
  1. package/README.md +103 -2
  2. package/dist/constants.d.ts +27 -0
  3. package/dist/constants.js +32 -0
  4. package/dist/descriptor.d.ts +29 -0
  5. package/dist/descriptor.js +73 -0
  6. package/dist/did.d.ts +59 -0
  7. package/dist/did.js +221 -0
  8. package/dist/didcomm.d.ts +59 -0
  9. package/dist/didcomm.js +176 -0
  10. package/dist/encoding.d.ts +14 -0
  11. package/dist/encoding.js +68 -0
  12. package/dist/event.d.ts +22 -0
  13. package/dist/event.js +42 -0
  14. package/dist/giftwrap.d.ts +29 -0
  15. package/dist/giftwrap.js +100 -0
  16. package/dist/index.d.ts +17 -0
  17. package/dist/index.js +20 -0
  18. package/dist/keys.d.ts +6 -0
  19. package/dist/keys.js +31 -0
  20. package/dist/mediation/leaf.d.ts +121 -0
  21. package/dist/mediation/leaf.js +238 -0
  22. package/dist/mediation/messages.d.ts +96 -0
  23. package/dist/mediation/messages.js +79 -0
  24. package/dist/negentropy.d.ts +81 -0
  25. package/dist/negentropy.js +352 -0
  26. package/dist/nip44.d.ts +18 -0
  27. package/dist/nip44.js +119 -0
  28. package/dist/pwa/browser-leaf.d.ts +15 -0
  29. package/dist/pwa/browser-leaf.js +91 -0
  30. package/dist/pwa/hub.d.ts +51 -0
  31. package/dist/pwa/hub.js +137 -0
  32. package/dist/pwa/store.d.ts +39 -0
  33. package/dist/pwa/store.js +157 -0
  34. package/dist/relay.d.ts +67 -0
  35. package/dist/relay.js +232 -0
  36. package/dist/seal.d.ts +56 -0
  37. package/dist/seal.js +146 -0
  38. package/dist/session.d.ts +75 -0
  39. package/dist/session.js +230 -0
  40. package/package.json +45 -4
  41. package/src/constants.ts +36 -0
  42. package/src/descriptor.ts +88 -0
  43. package/src/did.ts +222 -0
  44. package/src/didcomm.ts +196 -0
  45. package/src/encoding.ts +67 -0
  46. package/src/event.ts +56 -0
  47. package/src/giftwrap.ts +108 -0
  48. package/src/index.ts +20 -0
  49. package/src/keys.ts +33 -0
  50. package/src/mediation/leaf.ts +292 -0
  51. package/src/mediation/messages.ts +124 -0
  52. package/src/negentropy.ts +357 -0
  53. package/src/nip44.ts +110 -0
  54. package/src/pwa/browser-leaf.ts +99 -0
  55. package/src/pwa/hub.ts +173 -0
  56. package/src/pwa/store.ts +173 -0
  57. package/src/relay.ts +273 -0
  58. package/src/seal.ts +154 -0
  59. package/src/session.ts +255 -0
package/src/pwa/hub.ts ADDED
@@ -0,0 +1,173 @@
1
+ // One mediator connection per origin, however many tabs are open.
2
+ //
3
+ // Every tab asks the Web Locks API for the same exclusive lock. The tab that
4
+ // holds it is the leader: it alone runs the session (the leaf profile's one
5
+ // wss:// connection). The others wait in the lock's queue, which is the
6
+ // failover - when the leader's tab closes, crashes or stop()s, the browser
7
+ // grants the lock to the next tab, which becomes leader and connects.
8
+ // Followers reach the leader over a BroadcastChannel: they call it (pickup,
9
+ // status) and hear what it hears (deliveries, status changes).
10
+ //
11
+ // Why not a service worker: browsers stop an idle worker within about thirty
12
+ // seconds and an open WebSocket does not keep it alive, so a worker cannot
13
+ // hold this connection. The worker's job is push-to-wake and the app shell.
14
+ import type { OpenedDelivery } from '../mediation/leaf.ts';
15
+
16
+ export type LeafStatus = 'idle' | 'connecting' | 'connected' | 'offline' | 'error';
17
+
18
+ /** What the leader tab runs. */
19
+ export interface Leader {
20
+ pickup(): Promise<OpenedDelivery[]>;
21
+ close(): void;
22
+ }
23
+
24
+ export type HubEvent =
25
+ | { t: 'role'; role: 'leader' | 'follower' }
26
+ | { t: 'status'; status: LeafStatus; detail?: string }
27
+ | { t: 'delivered'; deliveries: OpenedDelivery[] };
28
+
29
+ type Wire =
30
+ | { t: 'call'; id: string; op: 'pickup' | 'status' }
31
+ | { t: 'reply'; id: string; ok: boolean; value?: unknown; error?: string }
32
+ | Extract<HubEvent, { t: 'status' | 'delivered' }>;
33
+
34
+ export interface HubOptions {
35
+ /** Builds the leader's session; called only in the tab that holds the lock. */
36
+ lead: (hub: LeafHub) => Promise<Leader>;
37
+ name?: string;
38
+ timeoutMs?: number;
39
+ }
40
+
41
+ const rid = () => Math.random().toString(36).slice(2) + Date.now().toString(36);
42
+
43
+ export class LeafHub {
44
+ role: 'leader' | 'follower' = 'follower';
45
+ status: LeafStatus = 'idle';
46
+ private readonly opts: HubOptions;
47
+ private readonly channel: BroadcastChannel;
48
+ private readonly listeners = new Set<(e: HubEvent) => void>();
49
+ private readonly calls = new Map<string, { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> }>();
50
+ private leader: Leader | null = null;
51
+ private release: (() => void) | null = null;
52
+ private readonly abort = new AbortController();
53
+
54
+ constructor(opts: HubOptions) {
55
+ this.opts = opts;
56
+ const name = opts.name ?? 'fleetmesh-leaf';
57
+ this.channel = new BroadcastChannel(name);
58
+ this.channel.onmessage = (e) => this.onWire(e.data as Wire);
59
+ if (!('locks' in navigator)) throw new Error('this browser has no Web Locks API');
60
+ navigator.locks.request(name + ':connection', { signal: this.abort.signal }, () => this.becomeLeader())
61
+ .catch((e) => { if ((e as Error).name !== 'AbortError') this.setStatus('error', String(e)); });
62
+ }
63
+
64
+ on(fn: (e: HubEvent) => void): () => void {
65
+ this.listeners.add(fn);
66
+ return () => this.listeners.delete(fn);
67
+ }
68
+
69
+ private emit(e: HubEvent): void {
70
+ for (const fn of this.listeners) fn(e);
71
+ }
72
+
73
+ /** The leader reports status; every tab hears it. */
74
+ setStatus(status: LeafStatus, detail?: string): void {
75
+ this.status = status;
76
+ const e: HubEvent = detail === undefined ? { t: 'status', status } : { t: 'status', status, detail };
77
+ this.emit(e);
78
+ if (this.role === 'leader') this.channel.postMessage(e);
79
+ }
80
+
81
+ /** The leader announces deliveries; every tab hears them. */
82
+ announce(deliveries: OpenedDelivery[]): void {
83
+ if (!deliveries.length) return;
84
+ const e: HubEvent = { t: 'delivered', deliveries };
85
+ this.emit(e);
86
+ this.channel.postMessage(e);
87
+ }
88
+
89
+ private async becomeLeader(): Promise<void> {
90
+ this.role = 'leader';
91
+ this.emit({ t: 'role', role: 'leader' });
92
+ const held = new Promise<void>((r) => (this.release = r));
93
+ try {
94
+ this.setStatus('connecting');
95
+ this.leader = await this.opts.lead(this);
96
+ this.setStatus('connected');
97
+ } catch (e) {
98
+ this.setStatus('error', (e as Error).message);
99
+ }
100
+ await held; // the lock is ours until stop() or the tab goes
101
+ this.leader?.close();
102
+ this.leader = null;
103
+ }
104
+
105
+ /** Drain the mediator: here if this tab leads, else through the leader. */
106
+ async pickup(): Promise<OpenedDelivery[]> {
107
+ if (this.role === 'leader') {
108
+ if (!this.leader) throw new Error('the leader is not connected');
109
+ const got = await this.leader.pickup();
110
+ this.announce(got);
111
+ return got;
112
+ }
113
+ return this.call('pickup') as Promise<OpenedDelivery[]>;
114
+ }
115
+
116
+ /** The leader's status, asked of it (a follower's own copy may be stale). */
117
+ async leaderStatus(): Promise<LeafStatus> {
118
+ return this.role === 'leader' ? this.status : (this.call('status') as Promise<LeafStatus>);
119
+ }
120
+
121
+ private call(op: 'pickup' | 'status'): Promise<unknown> {
122
+ const id = rid();
123
+ return new Promise((resolve, reject) => {
124
+ const timer = setTimeout(() => {
125
+ this.calls.delete(id);
126
+ reject(new Error(`no leader answered ${op} in ${this.opts.timeoutMs ?? 20000}ms`));
127
+ }, this.opts.timeoutMs ?? 20000);
128
+ this.calls.set(id, { resolve, reject, timer });
129
+ this.channel.postMessage({ t: 'call', id, op } satisfies Wire);
130
+ });
131
+ }
132
+
133
+ private async onWire(m: Wire): Promise<void> {
134
+ if (!m || typeof m !== 'object') return;
135
+ if (m.t === 'call') {
136
+ if (this.role !== 'leader') return;
137
+ try {
138
+ const value = m.op === 'pickup' ? await this.pickup() : this.status;
139
+ this.channel.postMessage({ t: 'reply', id: m.id, ok: true, value } satisfies Wire);
140
+ } catch (e) {
141
+ this.channel.postMessage({ t: 'reply', id: m.id, ok: false, error: (e as Error).message } satisfies Wire);
142
+ }
143
+ } else if (m.t === 'reply') {
144
+ const c = this.calls.get(m.id);
145
+ if (!c) return;
146
+ clearTimeout(c.timer);
147
+ this.calls.delete(m.id);
148
+ if (m.ok) c.resolve(m.value);
149
+ else c.reject(new Error(m.error));
150
+ } else if (m.t === 'status') {
151
+ if (this.role === 'follower') {
152
+ this.status = m.status;
153
+ this.emit(m);
154
+ }
155
+ } else if (m.t === 'delivered') {
156
+ this.emit(m);
157
+ }
158
+ }
159
+
160
+ /** Leave: a leader gives up the lock (the next tab takes over), a follower its place in line. */
161
+ stop(): void {
162
+ this.abort.abort();
163
+ this.release?.();
164
+ this.release = null;
165
+ this.role = 'follower';
166
+ for (const c of this.calls.values()) {
167
+ clearTimeout(c.timer);
168
+ c.reject(new Error('hub stopped'));
169
+ }
170
+ this.calls.clear();
171
+ this.channel.close();
172
+ }
173
+ }
@@ -0,0 +1,173 @@
1
+ // What a browser leaf keeps between launches, in IndexedDB:
2
+ //
3
+ // identity the node key and agreement key, AES-GCM-encrypted under a
4
+ // non-extractable WebCrypto key stored beside them. Script on
5
+ // this origin can still use that key - nothing in a browser can
6
+ // stop that - but the raw secrets are never at rest in the
7
+ // clear, and nothing can export them.
8
+ // state LeafClient.snapshot(): grants, denials, keylists.
9
+ // config which mediator, at which endpoint.
10
+ // inbox opened deliveries, a rolling window by age (constants.json
11
+ // leaf.store_window_days). Eviction is by age, never by request.
12
+ //
13
+ // A leaf's node key is its network identity, kept apart from any personal
14
+ // social key (spec: "keys in the OS keystore"); in a browser the closest
15
+ // thing is a key the page can use and not read.
16
+ import { schnorr } from '@noble/curves/secp256k1.js';
17
+ import { LEAF } from '../constants.ts';
18
+ import { bytesToHex, fromUtf8, hexToBytes, utf8 } from '../encoding.ts';
19
+ import type { LeafClientState, OpenedDelivery } from '../mediation/leaf.ts';
20
+
21
+ export const DB_NAME = 'fleetmesh-leaf';
22
+ const VERSION = 1;
23
+ const KV = 'kv', INBOX = 'inbox';
24
+
25
+ export interface LeafIdentity { nodeSk: string; agreementSk: Uint8Array }
26
+ export interface MediatorConfig { pubkey: string; endpoint: string }
27
+ export interface StoredDelivery extends OpenedDelivery { received_at: number }
28
+
29
+ function req<T>(r: IDBRequest<T>): Promise<T> {
30
+ return new Promise((resolve, reject) => {
31
+ r.onsuccess = () => resolve(r.result);
32
+ r.onerror = () => reject(r.error);
33
+ });
34
+ }
35
+
36
+ function done(tx: IDBTransaction): Promise<void> {
37
+ return new Promise((resolve, reject) => {
38
+ tx.oncomplete = () => resolve();
39
+ tx.onerror = () => reject(tx.error);
40
+ tx.onabort = () => reject(tx.error ?? new Error('transaction aborted'));
41
+ });
42
+ }
43
+
44
+ export class LeafStore {
45
+ readonly db: IDBDatabase;
46
+ private readonly now: () => number;
47
+
48
+ private constructor(db: IDBDatabase, now: () => number) {
49
+ this.db = db;
50
+ this.now = now;
51
+ }
52
+
53
+ static async open(name = DB_NAME, now: () => number = () => Math.floor(Date.now() / 1000)): Promise<LeafStore> {
54
+ const r = indexedDB.open(name, VERSION);
55
+ r.onupgradeneeded = () => {
56
+ const db = r.result;
57
+ if (!db.objectStoreNames.contains(KV)) db.createObjectStore(KV);
58
+ if (!db.objectStoreNames.contains(INBOX)) db.createObjectStore(INBOX, { keyPath: 'id' }).createIndex('received_at', 'received_at');
59
+ };
60
+ return new LeafStore(await req(r), now);
61
+ }
62
+
63
+ close(): void {
64
+ this.db.close();
65
+ }
66
+
67
+ /** Ask the browser not to evict this origin's storage under pressure. */
68
+ static async persist(): Promise<boolean> {
69
+ try {
70
+ return (await navigator.storage?.persist?.()) ?? false;
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+
76
+ private async get<T>(key: string): Promise<T | undefined> {
77
+ return req(this.db.transaction(KV).objectStore(KV).get(key)) as Promise<T | undefined>;
78
+ }
79
+
80
+ private async put(key: string, value: unknown): Promise<void> {
81
+ const tx = this.db.transaction(KV, 'readwrite');
82
+ tx.objectStore(KV).put(value, key);
83
+ await done(tx);
84
+ }
85
+
86
+ // ---- identity ----------------------------------------------------------
87
+ private async wrappingKey(): Promise<CryptoKey> {
88
+ const have = await this.get<CryptoKey>('wrapping-key');
89
+ if (have) return have;
90
+ const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
91
+ // Two tabs racing here would each make a key; add() lets only one win.
92
+ const tx = this.db.transaction(KV, 'readwrite');
93
+ tx.objectStore(KV).add(key, 'wrapping-key');
94
+ try {
95
+ await done(tx);
96
+ return key;
97
+ } catch {
98
+ return (await this.get<CryptoKey>('wrapping-key'))!;
99
+ }
100
+ }
101
+
102
+ /** This leaf's keys, created on first use. Only the encrypted form is stored. */
103
+ async identity(): Promise<LeafIdentity> {
104
+ const key = await this.wrappingKey();
105
+ const sealed = await this.get<{ iv: Uint8Array; ct: ArrayBuffer }>('identity');
106
+ if (sealed) {
107
+ const plain = JSON.parse(fromUtf8(new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: sealed.iv as BufferSource }, key, sealed.ct))));
108
+ return { nodeSk: plain.nodeSk, agreementSk: hexToBytes(plain.agreementSk) };
109
+ }
110
+ const id: LeafIdentity = {
111
+ nodeSk: bytesToHex(schnorr.utils.randomSecretKey()),
112
+ agreementSk: crypto.getRandomValues(new Uint8Array(32)),
113
+ };
114
+ const iv = crypto.getRandomValues(new Uint8Array(12));
115
+ const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key,
116
+ utf8(JSON.stringify({ nodeSk: id.nodeSk, agreementSk: bytesToHex(id.agreementSk) })) as BufferSource);
117
+ const tx = this.db.transaction(KV, 'readwrite');
118
+ tx.objectStore(KV).add({ iv, ct }, 'identity');
119
+ try {
120
+ await done(tx);
121
+ return id;
122
+ } catch {
123
+ return this.identity(); // another tab made it first; use theirs
124
+ }
125
+ }
126
+
127
+ /** Forget this leaf entirely: keys, grants, inbox. */
128
+ async reset(): Promise<void> {
129
+ const tx = this.db.transaction([KV, INBOX], 'readwrite');
130
+ tx.objectStore(KV).clear();
131
+ tx.objectStore(INBOX).clear();
132
+ await done(tx);
133
+ }
134
+
135
+ // ---- state and config --------------------------------------------------
136
+ state = () => this.get<LeafClientState>('state');
137
+ saveState = (s: LeafClientState) => this.put('state', s);
138
+ mediator = () => this.get<MediatorConfig>('mediator');
139
+ saveMediator = (m: MediatorConfig) => this.put('mediator', m);
140
+
141
+ // ---- inbox -------------------------------------------------------------
142
+ /** Keep deliveries and return the ones that were new; an id already held
143
+ * is kept as first received. Then evict past the window. */
144
+ async addToInbox(deliveries: OpenedDelivery[]): Promise<OpenedDelivery[]> {
145
+ const now = this.now();
146
+ const tx = this.db.transaction(INBOX, 'readwrite');
147
+ const os = tx.objectStore(INBOX);
148
+ const added: OpenedDelivery[] = [];
149
+ for (const d of deliveries) {
150
+ const r = os.add({ ...d, received_at: now });
151
+ r.onsuccess = () => added.push(d);
152
+ // Already held: not an error, and must not abort or fail the transaction.
153
+ r.onerror = (e) => { e.preventDefault(); e.stopPropagation(); };
154
+ }
155
+ await done(tx);
156
+ await this.evict();
157
+ return added;
158
+ }
159
+
160
+ async inbox(): Promise<StoredDelivery[]> {
161
+ return req(this.db.transaction(INBOX).objectStore(INBOX).index('received_at').getAll()) as Promise<StoredDelivery[]>;
162
+ }
163
+
164
+ /** Drop what is older than the leaf's store window. */
165
+ async evict(windowDays: number = LEAF.store_window_days): Promise<number> {
166
+ const cutoff = this.now() - windowDays * 86400;
167
+ const tx = this.db.transaction(INBOX, 'readwrite');
168
+ const keys = await req(tx.objectStore(INBOX).index('received_at').getAllKeys(IDBKeyRange.upperBound(cutoff, true)));
169
+ for (const k of keys) tx.objectStore(INBOX).delete(k);
170
+ await done(tx);
171
+ return keys.length;
172
+ }
173
+ }
package/src/relay.ts ADDED
@@ -0,0 +1,273 @@
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, and NIP-42 AUTH answered with the leaf's node key.
4
+ //
5
+ // Deliberately one socket and no reconnect policy: a leaf holds exactly one
6
+ // connection, to its mediator (spec § "The leaf profile"), and when it drops
7
+ // the session decides what to do - mobile operating systems kill sockets on
8
+ // screen lock, so "reconnect and catch up" is the session's ordinary path,
9
+ // not this module's error handling.
10
+ import type { NostrEvent } from './event.ts';
11
+
12
+ /** The slice of the WHATWG WebSocket this module uses. */
13
+ export interface SocketLike {
14
+ readonly readyState: number;
15
+ send(data: string): void;
16
+ close(code?: number, reason?: string): void;
17
+ onopen: ((ev: unknown) => void) | null;
18
+ onmessage: ((ev: { data: unknown }) => void) | null;
19
+ onclose: ((ev: unknown) => void) | null;
20
+ onerror: ((ev: unknown) => void) | null;
21
+ }
22
+ export type SocketFactory = (url: string) => SocketLike;
23
+
24
+ export type Filter = Record<string, unknown>;
25
+
26
+ export interface RelayOptions {
27
+ socket?: SocketFactory;
28
+ /** Sign a NIP-42 kind 22242 for this challenge; without it AUTH is never answered. */
29
+ signAuth?: (challenge: string, relayUrl: string) => NostrEvent;
30
+ timeoutMs?: number;
31
+ onNotice?: (message: string) => void;
32
+ onClose?: () => void;
33
+ }
34
+
35
+ export interface PublishResult { ok: boolean; message: string }
36
+
37
+ export interface Subscription {
38
+ readonly id: string;
39
+ /** Resolves on EOSE: the relay has registered the filters and replayed what it holds. */
40
+ readonly eose: Promise<void>;
41
+ /** Resolves with the reason if the relay closes it. */
42
+ readonly closed: Promise<string>;
43
+ close(): void;
44
+ }
45
+
46
+ export class RelayError extends Error {}
47
+
48
+ const OPEN = 1;
49
+ const defaultSocket: SocketFactory = (url) => {
50
+ const WS = (globalThis as { WebSocket?: new (u: string) => SocketLike }).WebSocket;
51
+ if (!WS) throw new RelayError('no WebSocket in this runtime; pass options.socket');
52
+ return new WS(url);
53
+ };
54
+
55
+ interface PendingOk { resolve: (r: PublishResult) => void; timer: ReturnType<typeof setTimeout> }
56
+ interface Sub { filters: Filter[]; onEvent: (ev: NostrEvent) => void; eose: () => void; closed: (why: string) => void; authRetried: boolean }
57
+
58
+ export class RelayConnection {
59
+ readonly url: string;
60
+ private readonly opts: RelayOptions;
61
+ private ws: SocketLike | null = null;
62
+ private challenge: string | null = null;
63
+ private authed: Promise<boolean> | null = null;
64
+ private readonly oks = new Map<string, PendingOk>();
65
+ private readonly subs = new Map<string, Sub>();
66
+ private seq = 0;
67
+
68
+ constructor(url: string, opts: RelayOptions = {}) {
69
+ this.url = url;
70
+ this.opts = opts;
71
+ }
72
+
73
+ get connected(): boolean {
74
+ return this.ws?.readyState === OPEN;
75
+ }
76
+
77
+ connect(): Promise<void> {
78
+ if (this.connected) return Promise.resolve();
79
+ const ws = (this.opts.socket ?? defaultSocket)(this.url);
80
+ this.ws = ws;
81
+ return new Promise((resolve, reject) => {
82
+ let opened = false;
83
+ const timer = setTimeout(() => {
84
+ reject(new RelayError(`no connection to ${this.url} in ${this.timeout}ms`));
85
+ ws.close();
86
+ }, this.timeout);
87
+ ws.onopen = () => {
88
+ opened = true;
89
+ clearTimeout(timer);
90
+ resolve();
91
+ };
92
+ ws.onerror = () => {
93
+ clearTimeout(timer);
94
+ reject(new RelayError('could not connect to ' + this.url));
95
+ };
96
+ ws.onclose = () => {
97
+ clearTimeout(timer);
98
+ if (!opened) reject(new RelayError('connection closed before opening'));
99
+ this.dropped();
100
+ };
101
+ ws.onmessage = (ev) => this.onFrame(ev.data);
102
+ });
103
+ }
104
+
105
+ close(): void {
106
+ const ws = this.ws;
107
+ this.ws = null;
108
+ if (ws) {
109
+ ws.onclose = null;
110
+ ws.close();
111
+ }
112
+ this.dropped();
113
+ }
114
+
115
+ private get timeout(): number {
116
+ return this.opts.timeoutMs ?? 5000;
117
+ }
118
+
119
+ private dropped(): void {
120
+ for (const [id, p] of this.oks) {
121
+ clearTimeout(p.timer);
122
+ p.resolve({ ok: false, message: 'error: connection closed' });
123
+ this.oks.delete(id);
124
+ }
125
+ for (const [id, s] of this.subs) {
126
+ s.closed('error: connection closed');
127
+ this.subs.delete(id);
128
+ }
129
+ this.challenge = null;
130
+ this.authed = null;
131
+ this.opts.onClose?.();
132
+ }
133
+
134
+ private send(frame: unknown[]): void {
135
+ if (!this.ws || !this.connected) throw new RelayError('not connected to ' + this.url);
136
+ this.ws.send(JSON.stringify(frame));
137
+ }
138
+
139
+ /** EVENT, resolved by the relay's OK. Retries once after AUTH when the relay says auth-required. */
140
+ async publish(ev: NostrEvent): Promise<PublishResult> {
141
+ const r = await this.publishOnce(ev);
142
+ if (!r.ok && r.message.startsWith('auth-required:') && (await this.authenticate())) return this.publishOnce(ev);
143
+ return r;
144
+ }
145
+
146
+ private publishOnce(ev: NostrEvent): Promise<PublishResult> {
147
+ return new Promise((resolve) => {
148
+ const timer = setTimeout(() => {
149
+ this.oks.delete(ev.id);
150
+ resolve({ ok: false, message: `error: no OK in ${this.timeout}ms` });
151
+ }, this.timeout);
152
+ this.oks.set(ev.id, { resolve, timer });
153
+ try {
154
+ this.send(['EVENT', ev]);
155
+ } catch (e) {
156
+ clearTimeout(timer);
157
+ this.oks.delete(ev.id);
158
+ resolve({ ok: false, message: 'error: ' + (e as Error).message });
159
+ }
160
+ });
161
+ }
162
+
163
+ /** REQ. Events arrive on onEvent until close(); a relay that closes it for
164
+ * auth-required is answered and asked once more. */
165
+ subscribe(filters: Filter[], onEvent: (ev: NostrEvent) => void): Subscription {
166
+ const id = 'leaf-' + (++this.seq).toString(36);
167
+ let eose!: () => void, closed!: (why: string) => void;
168
+ const eoseP = new Promise<void>((r) => (eose = r));
169
+ const closedP = new Promise<string>((r) => (closed = r));
170
+ this.subs.set(id, { filters, onEvent, eose, closed, authRetried: false });
171
+ this.send(['REQ', id, ...filters]);
172
+ return {
173
+ id, eose: eoseP, closed: closedP,
174
+ close: () => {
175
+ if (this.subs.delete(id) && this.connected) this.send(['CLOSE', id]);
176
+ },
177
+ };
178
+ }
179
+
180
+ /** Answer the relay's NIP-42 challenge; false if there is none or no signer. */
181
+ authenticate(): Promise<boolean> {
182
+ if (this.authed) return this.authed;
183
+ if (!this.challenge || !this.opts.signAuth) return Promise.resolve(false);
184
+ const ev = this.opts.signAuth(this.challenge, this.url);
185
+ this.authed = this.publishAuth(ev);
186
+ return this.authed;
187
+ }
188
+
189
+ private publishAuth(ev: NostrEvent): Promise<boolean> {
190
+ return new Promise((resolve) => {
191
+ const timer = setTimeout(() => {
192
+ this.oks.delete(ev.id);
193
+ resolve(false);
194
+ }, this.timeout);
195
+ this.oks.set(ev.id, { resolve: (r) => resolve(r.ok), timer });
196
+ this.send(['AUTH', ev]);
197
+ }).then((ok) => {
198
+ if (!ok) this.authed = null;
199
+ return ok as boolean;
200
+ });
201
+ }
202
+
203
+ private onFrame(data: unknown): void {
204
+ let msg: unknown;
205
+ try {
206
+ msg = JSON.parse(typeof data === 'string' ? data : String(data));
207
+ } catch {
208
+ return;
209
+ }
210
+ if (!Array.isArray(msg) || typeof msg[0] !== 'string') return;
211
+ const [verb, a, b, c] = msg as [string, unknown, unknown, unknown];
212
+ switch (verb) {
213
+ case 'EVENT': {
214
+ const s = typeof a === 'string' ? this.subs.get(a) : undefined;
215
+ if (s && b && typeof b === 'object') s.onEvent(b as NostrEvent);
216
+ break;
217
+ }
218
+ case 'EOSE': {
219
+ if (typeof a === 'string') this.subs.get(a)?.eose();
220
+ break;
221
+ }
222
+ case 'CLOSED': {
223
+ if (typeof a !== 'string') break;
224
+ const s = this.subs.get(a);
225
+ if (!s) break;
226
+ const why = typeof b === 'string' ? b : '';
227
+ if (why.startsWith('auth-required:') && !s.authRetried) {
228
+ s.authRetried = true;
229
+ void this.authenticate().then((ok) => {
230
+ if (ok && this.subs.has(a)) this.send(['REQ', a, ...s.filters]);
231
+ else this.endSub(a, why);
232
+ });
233
+ } else this.endSub(a, why);
234
+ break;
235
+ }
236
+ case 'OK': {
237
+ const p = typeof a === 'string' ? this.oks.get(a) : undefined;
238
+ if (!p) break;
239
+ clearTimeout(p.timer);
240
+ this.oks.delete(a as string);
241
+ p.resolve({ ok: b === true, message: typeof c === 'string' ? c : '' });
242
+ break;
243
+ }
244
+ case 'AUTH': {
245
+ if (typeof a === 'string') {
246
+ this.challenge = a;
247
+ this.authed = null;
248
+ // Answered up front when we can: a relay that requires AUTH refuses
249
+ // the first EVENT otherwise, and a live wrap refused is a wrap lost.
250
+ if (this.opts.signAuth) void this.authenticate();
251
+ }
252
+ break;
253
+ }
254
+ case 'NOTICE': {
255
+ if (typeof a === 'string') this.opts.onNotice?.(a);
256
+ break;
257
+ }
258
+ }
259
+ }
260
+
261
+ private endSub(id: string, why: string): void {
262
+ const s = this.subs.get(id);
263
+ if (!s) return;
264
+ this.subs.delete(id);
265
+ s.closed(why);
266
+ }
267
+ }
268
+
269
+ /** A NIP-42 auth event for a relay's challenge, signed by the leaf's node key. */
270
+ export function authEvent(sign: (createdAt: number, kind: number, tags: string[][], content: string) => NostrEvent,
271
+ challenge: string, relayUrl: string, now = Math.floor(Date.now() / 1000)): NostrEvent {
272
+ return sign(now, 22242, [['relay', relayUrl], ['challenge', challenge]], '');
273
+ }