@toon-protocol/relay 2.0.1 → 2.1.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.
@@ -1,939 +0,0 @@
1
- // src/version.ts
2
- var VERSION = "0.1.0";
3
-
4
- // src/types.ts
5
- var DEFAULT_RELAY_CONFIG = {
6
- port: 7e3,
7
- host: "0.0.0.0",
8
- maxConnections: 100,
9
- maxSubscriptionsPerConnection: 20,
10
- maxFiltersPerSubscription: 10,
11
- databasePath: ":memory:"
12
- };
13
-
14
- // src/filters/matchFilter.ts
15
- function matchFilter(event, filter) {
16
- if (Object.keys(filter).length === 0) {
17
- return true;
18
- }
19
- if (filter.ids !== void 0 && filter.ids.length > 0) {
20
- const matches = filter.ids.some((id) => event.id.startsWith(id));
21
- if (!matches) return false;
22
- }
23
- if (filter.authors !== void 0 && filter.authors.length > 0) {
24
- const matches = filter.authors.some(
25
- (author) => event.pubkey.startsWith(author)
26
- );
27
- if (!matches) return false;
28
- }
29
- if (filter.kinds !== void 0 && filter.kinds.length > 0) {
30
- if (!filter.kinds.includes(event.kind)) return false;
31
- }
32
- if (filter.since !== void 0) {
33
- if (event.created_at < filter.since) return false;
34
- }
35
- if (filter.until !== void 0) {
36
- if (event.created_at > filter.until) return false;
37
- }
38
- for (const key of Object.keys(filter)) {
39
- if (key.startsWith("#") && key.length === 2) {
40
- const tagName = key.slice(1);
41
- const filterValues = filter[key];
42
- if (filterValues !== void 0 && filterValues.length > 0) {
43
- const eventTagValues = event.tags.filter((tag) => tag[0] === tagName).map((tag) => tag[1]);
44
- const hasMatch = filterValues.some((v) => eventTagValues.includes(v));
45
- if (!hasMatch) return false;
46
- }
47
- }
48
- }
49
- return true;
50
- }
51
-
52
- // src/storage/InMemoryEventStore.ts
53
- var InMemoryEventStore = class {
54
- events = /* @__PURE__ */ new Map();
55
- store(event) {
56
- this.events.set(event.id, event);
57
- }
58
- get(id) {
59
- return this.events.get(id);
60
- }
61
- query(filters) {
62
- const allEvents = Array.from(this.events.values());
63
- if (filters.length === 0) {
64
- return allEvents.sort((a, b) => b.created_at - a.created_at);
65
- }
66
- const matchingEvents = [];
67
- for (const event of allEvents) {
68
- for (const filter of filters) {
69
- if (matchFilter(event, filter)) {
70
- matchingEvents.push(event);
71
- break;
72
- }
73
- }
74
- }
75
- matchingEvents.sort((a, b) => b.created_at - a.created_at);
76
- const limitFilter = filters.find((f) => f.limit !== void 0);
77
- if (limitFilter?.limit !== void 0) {
78
- return matchingEvents.slice(0, limitFilter.limit);
79
- }
80
- return matchingEvents;
81
- }
82
- /**
83
- * Close the storage backend (no-op for in-memory store).
84
- */
85
- close() {
86
- }
87
- };
88
-
89
- // src/storage/SqliteEventStore.ts
90
- import Database from "better-sqlite3";
91
- var SCHEMA_SQL = `
92
- CREATE TABLE IF NOT EXISTS events (
93
- id TEXT PRIMARY KEY,
94
- pubkey TEXT NOT NULL,
95
- kind INTEGER NOT NULL,
96
- content TEXT NOT NULL,
97
- tags TEXT NOT NULL,
98
- created_at INTEGER NOT NULL,
99
- sig TEXT NOT NULL,
100
- received_at INTEGER NOT NULL
101
- )
102
- `;
103
- var INDEX_SQL = [
104
- "CREATE INDEX IF NOT EXISTS idx_events_pubkey ON events(pubkey)",
105
- "CREATE INDEX IF NOT EXISTS idx_events_kind ON events(kind)",
106
- "CREATE INDEX IF NOT EXISTS idx_events_created_at ON events(created_at)",
107
- "CREATE INDEX IF NOT EXISTS idx_events_pubkey_kind ON events(pubkey, kind)"
108
- ];
109
- function initializeSchema(db) {
110
- db.exec(SCHEMA_SQL);
111
- for (const indexSql of INDEX_SQL) {
112
- db.exec(indexSql);
113
- }
114
- }
115
- var RelayError = class extends Error {
116
- constructor(message, code) {
117
- super(message);
118
- this.code = code;
119
- this.name = "RelayError";
120
- }
121
- };
122
- function isReplaceableKind(kind) {
123
- return kind >= 1e4 && kind <= 19999 && !(kind >= 10032 && kind <= 10099);
124
- }
125
- function isParameterizedReplaceableKind(kind) {
126
- return kind >= 3e4 && kind <= 39999 || kind >= 10032 && kind <= 10099;
127
- }
128
- function getDTagValue(tags) {
129
- const dTag = tags.find((tag) => tag[0] === "d");
130
- return dTag?.[1] ?? "";
131
- }
132
- var SqliteEventStore = class {
133
- db;
134
- insertStmt;
135
- getStmt;
136
- deleteByPubkeyKindStmt;
137
- deleteByPubkeyKindDTagStmt;
138
- getByPubkeyKindStmt;
139
- getByPubkeyKindDTagStmt;
140
- /**
141
- * Create a new SqliteEventStore.
142
- * @param dbPath - Path to the database file. Use ':memory:' for in-memory database.
143
- */
144
- constructor(dbPath = ":memory:") {
145
- try {
146
- this.db = new Database(dbPath);
147
- initializeSchema(this.db);
148
- this.insertStmt = this.db.prepare(`
149
- INSERT OR REPLACE INTO events (id, pubkey, kind, content, tags, created_at, sig, received_at)
150
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
151
- `);
152
- this.getStmt = this.db.prepare("SELECT * FROM events WHERE id = ?");
153
- this.deleteByPubkeyKindStmt = this.db.prepare(
154
- "DELETE FROM events WHERE pubkey = ? AND kind = ?"
155
- );
156
- this.deleteByPubkeyKindDTagStmt = this.db.prepare(
157
- "DELETE FROM events WHERE pubkey = ? AND kind = ? AND json_extract(tags, '$') LIKE ?"
158
- );
159
- this.getByPubkeyKindStmt = this.db.prepare(
160
- "SELECT id, created_at FROM events WHERE pubkey = ? AND kind = ?"
161
- );
162
- this.getByPubkeyKindDTagStmt = this.db.prepare(
163
- "SELECT id, created_at FROM events WHERE pubkey = ? AND kind = ? AND tags LIKE ?"
164
- );
165
- } catch (error) {
166
- throw new RelayError(
167
- `Failed to initialize database: ${error instanceof Error ? error.message : String(error)}`,
168
- "STORAGE_ERROR"
169
- );
170
- }
171
- }
172
- /**
173
- * Store an event in the database.
174
- * Handles replaceable and parameterized replaceable events according to NIP-01.
175
- */
176
- store(event) {
177
- try {
178
- const tagsJson = JSON.stringify(event.tags);
179
- const receivedAt = Math.floor(Date.now() / 1e3);
180
- if (isReplaceableKind(event.kind)) {
181
- this.storeReplaceableEvent(event, tagsJson, receivedAt);
182
- } else if (isParameterizedReplaceableKind(event.kind)) {
183
- this.storeParameterizedReplaceableEvent(event, tagsJson, receivedAt);
184
- } else {
185
- const insertOrIgnore = this.db.prepare(`
186
- INSERT OR IGNORE INTO events (id, pubkey, kind, content, tags, created_at, sig, received_at)
187
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
188
- `);
189
- insertOrIgnore.run(
190
- event.id,
191
- event.pubkey,
192
- event.kind,
193
- event.content,
194
- tagsJson,
195
- event.created_at,
196
- event.sig,
197
- receivedAt
198
- );
199
- }
200
- } catch (error) {
201
- if (error instanceof RelayError) {
202
- throw error;
203
- }
204
- throw new RelayError(
205
- `Failed to store event: ${error instanceof Error ? error.message : String(error)}`,
206
- "STORAGE_ERROR"
207
- );
208
- }
209
- }
210
- /**
211
- * Store a replaceable event (kinds 10000-19999).
212
- * Only keeps the latest event per pubkey+kind.
213
- */
214
- storeReplaceableEvent(event, tagsJson, receivedAt) {
215
- const existing = this.getByPubkeyKindStmt.get(event.pubkey, event.kind);
216
- if (existing) {
217
- if (event.created_at > existing.created_at || event.created_at === existing.created_at && event.id < existing.id) {
218
- const transaction = this.db.transaction(() => {
219
- this.deleteByPubkeyKindStmt.run(event.pubkey, event.kind);
220
- this.insertStmt.run(
221
- event.id,
222
- event.pubkey,
223
- event.kind,
224
- event.content,
225
- tagsJson,
226
- event.created_at,
227
- event.sig,
228
- receivedAt
229
- );
230
- });
231
- transaction();
232
- }
233
- } else {
234
- this.insertStmt.run(
235
- event.id,
236
- event.pubkey,
237
- event.kind,
238
- event.content,
239
- tagsJson,
240
- event.created_at,
241
- event.sig,
242
- receivedAt
243
- );
244
- }
245
- }
246
- /**
247
- * Store a parameterized replaceable event (kinds 30000-39999).
248
- * Only keeps the latest event per pubkey+kind+d-tag.
249
- */
250
- storeParameterizedReplaceableEvent(event, tagsJson, receivedAt) {
251
- const dTagValue = getDTagValue(event.tags);
252
- let existing;
253
- if (dTagValue === "") {
254
- const candidates = this.db.prepare(
255
- "SELECT id, created_at, tags FROM events WHERE pubkey = ? AND kind = ?"
256
- ).all(event.pubkey, event.kind);
257
- for (const candidate of candidates) {
258
- const candidateTags = JSON.parse(candidate.tags);
259
- const candidateDTagValue = getDTagValue(candidateTags);
260
- if (candidateDTagValue === "") {
261
- existing = { id: candidate.id, created_at: candidate.created_at };
262
- break;
263
- }
264
- }
265
- } else {
266
- const dTagPattern = `%["d","${dTagValue}"%`;
267
- existing = this.getByPubkeyKindDTagStmt.get(
268
- event.pubkey,
269
- event.kind,
270
- dTagPattern
271
- );
272
- }
273
- if (existing) {
274
- if (event.created_at > existing.created_at || event.created_at === existing.created_at && event.id < existing.id) {
275
- const transaction = this.db.transaction(() => {
276
- this.db.prepare("DELETE FROM events WHERE id = ?").run(existing.id);
277
- this.insertStmt.run(
278
- event.id,
279
- event.pubkey,
280
- event.kind,
281
- event.content,
282
- tagsJson,
283
- event.created_at,
284
- event.sig,
285
- receivedAt
286
- );
287
- });
288
- transaction();
289
- }
290
- } else {
291
- this.insertStmt.run(
292
- event.id,
293
- event.pubkey,
294
- event.kind,
295
- event.content,
296
- tagsJson,
297
- event.created_at,
298
- event.sig,
299
- receivedAt
300
- );
301
- }
302
- }
303
- /**
304
- * Retrieve an event by its ID.
305
- */
306
- get(id) {
307
- try {
308
- const row = this.getStmt.get(id);
309
- if (!row) {
310
- return void 0;
311
- }
312
- return {
313
- id: row.id,
314
- pubkey: row.pubkey,
315
- kind: row.kind,
316
- content: row.content,
317
- tags: JSON.parse(row.tags),
318
- created_at: row.created_at,
319
- sig: row.sig
320
- };
321
- } catch (error) {
322
- throw new RelayError(
323
- `Failed to get event: ${error instanceof Error ? error.message : String(error)}`,
324
- "STORAGE_ERROR"
325
- );
326
- }
327
- }
328
- /**
329
- * Query events matching any of the provided filters.
330
- */
331
- query(filters) {
332
- try {
333
- const { sql, params } = this.buildQuerySql(filters);
334
- const stmt = this.db.prepare(sql);
335
- const rows = stmt.all(...params);
336
- return rows.map((row) => ({
337
- id: row.id,
338
- pubkey: row.pubkey,
339
- kind: row.kind,
340
- content: row.content,
341
- tags: JSON.parse(row.tags),
342
- created_at: row.created_at,
343
- sig: row.sig
344
- }));
345
- } catch (error) {
346
- throw new RelayError(
347
- `Failed to query events: ${error instanceof Error ? error.message : String(error)}`,
348
- "STORAGE_ERROR"
349
- );
350
- }
351
- }
352
- /**
353
- * Build SQL query from filters.
354
- */
355
- buildQuerySql(filters) {
356
- if (filters.length === 0) {
357
- return {
358
- sql: "SELECT * FROM events ORDER BY created_at DESC",
359
- params: []
360
- };
361
- }
362
- const conditions = [];
363
- const params = [];
364
- for (const filter of filters) {
365
- const filterConditions = [];
366
- if (filter.ids?.length) {
367
- const idConditions = filter.ids.map(() => "id LIKE ?");
368
- filterConditions.push(`(${idConditions.join(" OR ")})`);
369
- params.push(...filter.ids.map((id) => `${id}%`));
370
- }
371
- if (filter.authors?.length) {
372
- const authorConditions = filter.authors.map(() => "pubkey LIKE ?");
373
- filterConditions.push(`(${authorConditions.join(" OR ")})`);
374
- params.push(...filter.authors.map((a) => `${a}%`));
375
- }
376
- if (filter.kinds?.length) {
377
- filterConditions.push(
378
- `kind IN (${filter.kinds.map(() => "?").join(", ")})`
379
- );
380
- params.push(...filter.kinds);
381
- }
382
- if (filter.since !== void 0) {
383
- filterConditions.push("created_at >= ?");
384
- params.push(filter.since);
385
- }
386
- if (filter.until !== void 0) {
387
- filterConditions.push("created_at <= ?");
388
- params.push(filter.until);
389
- }
390
- for (const [key, values] of Object.entries(filter)) {
391
- if (key.startsWith("#") && Array.isArray(values) && values.length > 0) {
392
- const tagName = key.slice(1);
393
- const tagConditions = values.map(() => `tags LIKE ?`);
394
- filterConditions.push(`(${tagConditions.join(" OR ")})`);
395
- params.push(...values.map((v) => `%["${tagName}","${v}"%`));
396
- }
397
- }
398
- if (filterConditions.length > 0) {
399
- conditions.push(`(${filterConditions.join(" AND ")})`);
400
- }
401
- }
402
- let sql = "SELECT * FROM events";
403
- if (conditions.length > 0) {
404
- sql += ` WHERE ${conditions.join(" OR ")}`;
405
- }
406
- sql += " ORDER BY created_at DESC";
407
- const limitFilter = filters.find((f) => f.limit !== void 0);
408
- if (limitFilter?.limit !== void 0) {
409
- sql += " LIMIT ?";
410
- params.push(limitFilter.limit);
411
- }
412
- return { sql, params };
413
- }
414
- /**
415
- * Close the database connection.
416
- */
417
- close() {
418
- this.db.close();
419
- }
420
- };
421
-
422
- // src/websocket/ConnectionHandler.ts
423
- var ConnectionHandler = class {
424
- constructor(ws, eventStore, config = {}) {
425
- this.ws = ws;
426
- this.eventStore = eventStore;
427
- this.config = { ...DEFAULT_RELAY_CONFIG, ...config };
428
- }
429
- subscriptions = /* @__PURE__ */ new Map();
430
- config;
431
- /**
432
- * Handle an incoming message from the WebSocket.
433
- */
434
- handleMessage(data) {
435
- console.log(`[ConnectionHandler] Received message:`, data.slice(0, 150));
436
- let message;
437
- try {
438
- const parsed = JSON.parse(data);
439
- if (!Array.isArray(parsed)) {
440
- this.sendNotice("error: invalid message format, expected JSON array");
441
- return;
442
- }
443
- message = parsed;
444
- } catch {
445
- this.sendNotice("error: invalid JSON");
446
- return;
447
- }
448
- const messageType = message[0];
449
- console.log(`[ConnectionHandler] Message type: ${messageType}`);
450
- if (messageType === "REQ") {
451
- const subscriptionId = message[1];
452
- const filters = message.slice(2);
453
- this.handleReq(subscriptionId, filters);
454
- } else if (messageType === "EVENT") {
455
- const event = message[1];
456
- this.handleEvent(event);
457
- } else if (messageType === "CLOSE") {
458
- const subscriptionId = message[1];
459
- this.handleClose(subscriptionId);
460
- } else {
461
- this.sendNotice(`error: unknown message type: ${messageType}`);
462
- }
463
- }
464
- /**
465
- * Handle a REQ message to create/update a subscription.
466
- */
467
- handleReq(subscriptionId, filters) {
468
- if (typeof subscriptionId !== "string" || subscriptionId.length === 0) {
469
- this.sendNotice("error: invalid subscription id");
470
- return;
471
- }
472
- if (!this.subscriptions.has(subscriptionId)) {
473
- if (this.subscriptions.size >= this.config.maxSubscriptionsPerConnection) {
474
- this.sendNotice("error: too many subscriptions");
475
- return;
476
- }
477
- }
478
- if (filters.length > this.config.maxFiltersPerSubscription) {
479
- this.sendNotice("error: too many filters");
480
- return;
481
- }
482
- this.subscriptions.set(subscriptionId, {
483
- id: subscriptionId,
484
- filters
485
- });
486
- console.log(
487
- `[ConnectionHandler] REQ: ${subscriptionId}, filters:`,
488
- JSON.stringify(filters).slice(0, 100)
489
- );
490
- const events = this.eventStore.query(filters);
491
- console.log(
492
- `[ConnectionHandler] Query returned ${events.length} events for ${subscriptionId}`
493
- );
494
- for (const event of events) {
495
- console.log(
496
- `[ConnectionHandler] Sending event ${event.id.slice(0, 16)}... to ${subscriptionId}`
497
- );
498
- this.sendEvent(subscriptionId, event);
499
- }
500
- console.log(`[ConnectionHandler] Sending EOSE for ${subscriptionId}`);
501
- this.sendEose(subscriptionId);
502
- }
503
- /**
504
- * Handle an EVENT message from a WebSocket client.
505
- *
506
- * Rejects all external writes — the relay is ILP-gated (pay to write).
507
- * Events are only stored through the ILP packet handler which calls
508
- * eventStore.store() directly and then broadcastEvent() to notify subscribers.
509
- */
510
- handleEvent(event) {
511
- this.sendOk(event.id, false, "restricted: writes require ILP payment");
512
- }
513
- /**
514
- * Handle a CLOSE message to terminate a subscription.
515
- */
516
- handleClose(subscriptionId) {
517
- this.subscriptions.delete(subscriptionId);
518
- }
519
- /**
520
- * Push a new event to all matching subscriptions on this connection.
521
- * Used when events are stored outside the WebSocket flow (e.g., via ILP).
522
- */
523
- notifyNewEvent(event) {
524
- for (const sub of this.subscriptions.values()) {
525
- const matches = sub.filters.some((f) => matchFilter(event, f));
526
- if (matches) {
527
- this.sendEvent(sub.id, event);
528
- }
529
- }
530
- }
531
- /**
532
- * Clean up all subscriptions for this connection.
533
- */
534
- cleanup() {
535
- this.subscriptions.clear();
536
- }
537
- /**
538
- * Get the number of active subscriptions.
539
- */
540
- getSubscriptionCount() {
541
- return this.subscriptions.size;
542
- }
543
- /**
544
- * Emit an outbound NIP-01 EVENT frame.
545
- *
546
- * The event MUST go on the wire as canonical NIP-01 JSON —
547
- * `["EVENT", <subId>, {id, pubkey, created_at, kind, tags, content, sig}]`
548
- * with the event as a plain JSON object — so any standard nostr client can
549
- * parse it and verify `id`/`sig` from the wire bytes (#46). Never re-encode
550
- * the event (TOON text, double-JSON-stringify, etc.) at this boundary.
551
- */
552
- sendEvent(subscriptionId, event) {
553
- this.send(["EVENT", subscriptionId, event]);
554
- }
555
- sendEose(subscriptionId) {
556
- this.send(["EOSE", subscriptionId]);
557
- }
558
- sendOk(eventId, success, message) {
559
- this.send(["OK", eventId, success, message]);
560
- }
561
- sendNotice(message) {
562
- this.send(["NOTICE", message]);
563
- }
564
- send(message) {
565
- if (this.ws.readyState === 1) {
566
- this.ws.send(JSON.stringify(message));
567
- }
568
- }
569
- };
570
-
571
- // src/websocket/NostrRelayServer.ts
572
- import { WebSocketServer } from "ws";
573
- var NostrRelayServer = class {
574
- constructor(config = {}, eventStore) {
575
- this.eventStore = eventStore;
576
- this.config = { ...DEFAULT_RELAY_CONFIG, ...config };
577
- }
578
- wss = null;
579
- handlers = /* @__PURE__ */ new Map();
580
- config;
581
- /**
582
- * Start the WebSocket server.
583
- */
584
- async start() {
585
- return new Promise((resolve, reject) => {
586
- try {
587
- this.wss = new WebSocketServer({
588
- port: this.config.port,
589
- host: this.config.host
590
- });
591
- this.wss.on("connection", (ws) => {
592
- this.handleConnection(ws);
593
- });
594
- this.wss.on("error", (error) => {
595
- console.error("[NostrRelayServer] Server error:", error.message);
596
- });
597
- this.wss.on("listening", () => {
598
- const address = this.wss?.address();
599
- if (address && typeof address === "object") {
600
- console.log(`[NostrRelayServer] Listening on port ${address.port}`);
601
- }
602
- resolve();
603
- });
604
- } catch (error) {
605
- reject(error);
606
- }
607
- });
608
- }
609
- /**
610
- * Stop the WebSocket server and close all connections.
611
- */
612
- async stop() {
613
- return new Promise((resolve) => {
614
- if (!this.wss) {
615
- resolve();
616
- return;
617
- }
618
- for (const [ws, handler] of this.handlers) {
619
- handler.cleanup();
620
- ws.close();
621
- }
622
- this.handlers.clear();
623
- this.wss.close(() => {
624
- this.wss = null;
625
- resolve();
626
- });
627
- });
628
- }
629
- /**
630
- * Get the port the server is listening on.
631
- * Returns 0 if the server is not started.
632
- */
633
- getPort() {
634
- if (!this.wss) return 0;
635
- const address = this.wss.address();
636
- if (address && typeof address === "object") {
637
- return address.port;
638
- }
639
- return 0;
640
- }
641
- /**
642
- * Get the number of connected clients.
643
- */
644
- getClientCount() {
645
- return this.handlers.size;
646
- }
647
- /**
648
- * Broadcast an event to all connected clients with matching subscriptions.
649
- * Call this after storing an event outside the WebSocket flow (e.g., via ILP)
650
- * so that discovery subscribers are notified.
651
- */
652
- broadcastEvent(event) {
653
- for (const handler of this.handlers.values()) {
654
- handler.notifyNewEvent(event);
655
- }
656
- }
657
- handleConnection(ws) {
658
- if (this.handlers.size >= this.config.maxConnections) {
659
- ws.close(1013, "max connections reached");
660
- return;
661
- }
662
- console.log("[NostrRelayServer] Client connected");
663
- const handler = new ConnectionHandler(ws, this.eventStore, this.config);
664
- this.handlers.set(ws, handler);
665
- ws.on("message", (data) => {
666
- const message = typeof data === "string" ? data : data.toString();
667
- handler.handleMessage(message);
668
- });
669
- ws.on("close", () => {
670
- console.log("[NostrRelayServer] Client disconnected");
671
- handler.cleanup();
672
- this.handlers.delete(ws);
673
- });
674
- ws.on("error", (error) => {
675
- console.error("[NostrRelayServer] Client error:", error.message);
676
- handler.cleanup();
677
- this.handlers.delete(ws);
678
- });
679
- }
680
- };
681
-
682
- // src/subscriber/RelaySubscriber.ts
683
- import { SimplePool } from "nostr-tools/pool";
684
- import { verifyEvent } from "nostr-tools/pure";
685
- var RelaySubscriber = class {
686
- config;
687
- eventStore;
688
- pool;
689
- started = false;
690
- /**
691
- * @param config - Subscriber configuration
692
- * @param eventStore - Storage backend to write events into
693
- * @param pool - Optional SimplePool instance (creates new one if not provided)
694
- */
695
- constructor(config, eventStore, pool) {
696
- this.config = config;
697
- this.eventStore = eventStore;
698
- this.pool = pool ?? new SimplePool();
699
- }
700
- /**
701
- * Start subscribing to the configured upstream relays.
702
- *
703
- * @returns Handle with unsubscribe() to stop the subscription
704
- * @throws Error if already started
705
- */
706
- start() {
707
- if (this.started) {
708
- throw new Error("RelaySubscriber already started");
709
- }
710
- this.started = true;
711
- const shouldVerify = this.config.verifySignatures !== false;
712
- let isUnsubscribed = false;
713
- const subCloser = this.pool.subscribeMany(
714
- this.config.relayUrls,
715
- this.config.filter,
716
- {
717
- onevent: (event) => {
718
- if (isUnsubscribed) return;
719
- if (shouldVerify && !verifyEvent(event)) {
720
- return;
721
- }
722
- try {
723
- this.eventStore.store(event);
724
- } catch (error) {
725
- console.warn(
726
- "[RelaySubscriber] Failed to store event:",
727
- error instanceof Error ? error.message : "Unknown error"
728
- );
729
- }
730
- }
731
- }
732
- );
733
- return {
734
- unsubscribe: () => {
735
- if (!isUnsubscribed) {
736
- isUnsubscribed = true;
737
- subCloser.close();
738
- this.started = false;
739
- }
740
- }
741
- };
742
- }
743
- };
744
-
745
- // src/launcher/handlers/write-handler.ts
746
- import { verifyEvent as verifyEvent2 } from "nostr-tools/pure";
747
- function createWriteHandler(config) {
748
- return {
749
- async handleWrite(c) {
750
- let body;
751
- try {
752
- body = await c.req.json();
753
- } catch {
754
- return c.json({ error: "Invalid request body" }, 400);
755
- }
756
- if (!body.event) {
757
- return c.json({ error: "Missing required field: event" }, 400);
758
- }
759
- const event = body.event;
760
- const payer = c.req.header("X-TOON-Payer");
761
- const amount = c.req.header("X-TOON-Amount");
762
- const chain = c.req.header("X-TOON-Chain");
763
- console.log(
764
- `[write] event=${event.id} payer=${payer ?? "-"} amount=${amount ?? "-"} chain=${chain ?? "-"}`
765
- );
766
- if (!config.devMode && !verifyEvent2(event)) {
767
- return c.json({ error: "Invalid event signature" }, 422);
768
- }
769
- config.eventStore.store(event);
770
- config.onStored?.(event);
771
- return c.json(
772
- {
773
- eventId: event.id,
774
- storedAt: Math.floor(Date.now() / 1e3),
775
- payer,
776
- amount,
777
- chain
778
- },
779
- 200
780
- );
781
- }
782
- };
783
- }
784
-
785
- // src/launcher/health.ts
786
- function createHealthResponse(config) {
787
- return {
788
- status: "healthy",
789
- pubkey: config.pubkey,
790
- capabilities: ["relay"],
791
- version: VERSION,
792
- timestamp: Date.now()
793
- };
794
- }
795
-
796
- // src/launcher/relay.ts
797
- import { mkdirSync } from "fs";
798
- import { join } from "path";
799
- import { serve } from "@hono/node-server";
800
- import { Hono } from "hono";
801
- import { getPublicKey } from "nostr-tools/pure";
802
- import { privateKeyFromSeedWords } from "nostr-tools/nip06";
803
- function deriveIdentity(config) {
804
- const hasMnemonic = config.mnemonic !== void 0;
805
- const hasSecretKey = config.secretKey !== void 0;
806
- if (hasMnemonic && hasSecretKey) {
807
- throw new Error(
808
- "RelayConfig: provide either mnemonic or secretKey, not both"
809
- );
810
- }
811
- if (!hasMnemonic && !hasSecretKey) {
812
- throw new Error("RelayConfig: one of mnemonic or secretKey is required");
813
- }
814
- const secretKey = hasMnemonic ? privateKeyFromSeedWords(config.mnemonic) : config.secretKey;
815
- return { secretKey, pubkey: getPublicKey(secretKey) };
816
- }
817
- function createSubscription(relayUrl, filter, eventStore, activeSubscriptions) {
818
- if (!relayUrl.startsWith("ws://") && !relayUrl.startsWith("wss://")) {
819
- throw new Error(
820
- "Invalid relay URL -- must use WebSocket scheme (ws or wss)"
821
- );
822
- }
823
- const subscriber = new RelaySubscriber(
824
- { relayUrls: [relayUrl], filter },
825
- eventStore
826
- );
827
- const handle = subscriber.start();
828
- let active = true;
829
- const subscription = {
830
- close() {
831
- if (!active) return;
832
- active = false;
833
- handle.unsubscribe();
834
- activeSubscriptions.delete(subscription);
835
- },
836
- relayUrl,
837
- isActive() {
838
- return active;
839
- }
840
- };
841
- activeSubscriptions.add(subscription);
842
- return subscription;
843
- }
844
- async function startRelay(config) {
845
- const identity = deriveIdentity(config);
846
- const relayPort = config.relayPort ?? 7100;
847
- const blsPort = config.blsPort ?? 3100;
848
- const host = config.host ?? "0.0.0.0";
849
- const dataDir = config.dataDir ?? "./data";
850
- const devMode = config.devMode ?? false;
851
- const resolvedConfig = {
852
- relayPort,
853
- blsPort,
854
- host,
855
- dataDir,
856
- devMode
857
- };
858
- let eventStore;
859
- if (config.eventStore) {
860
- eventStore = config.eventStore;
861
- } else {
862
- mkdirSync(dataDir, { recursive: true });
863
- eventStore = new SqliteEventStore(join(dataDir, "events.db"));
864
- }
865
- const wsRelay = new NostrRelayServer({ port: relayPort, host }, eventStore);
866
- const app = new Hono();
867
- app.get(
868
- "/health",
869
- (c) => c.json(createHealthResponse({ pubkey: identity.pubkey }))
870
- );
871
- const writeHandler = createWriteHandler({
872
- eventStore,
873
- devMode,
874
- onStored: (event) => {
875
- try {
876
- wsRelay.broadcastEvent(event);
877
- } catch {
878
- }
879
- }
880
- });
881
- app.post("/write", (c) => writeHandler.handleWrite(c));
882
- const blsServer = await new Promise((resolve) => {
883
- const server = serve(
884
- { fetch: app.fetch, port: blsPort },
885
- () => resolve(server)
886
- );
887
- });
888
- await wsRelay.start();
889
- let running = true;
890
- const activeSubscriptions = /* @__PURE__ */ new Set();
891
- const instance = {
892
- isRunning() {
893
- return running;
894
- },
895
- subscribe(subscribeRelayUrl, filter) {
896
- if (!running) {
897
- throw new Error("Cannot subscribe: relay is not running");
898
- }
899
- return createSubscription(
900
- subscribeRelayUrl,
901
- filter,
902
- eventStore,
903
- activeSubscriptions
904
- );
905
- },
906
- async stop() {
907
- if (!running) return;
908
- running = false;
909
- for (const sub of activeSubscriptions) {
910
- sub.close();
911
- }
912
- activeSubscriptions.clear();
913
- await wsRelay.stop();
914
- blsServer.close();
915
- if (!config.eventStore) {
916
- eventStore.close?.();
917
- }
918
- },
919
- pubkey: identity.pubkey,
920
- config: resolvedConfig
921
- };
922
- return instance;
923
- }
924
-
925
- export {
926
- VERSION,
927
- DEFAULT_RELAY_CONFIG,
928
- matchFilter,
929
- InMemoryEventStore,
930
- RelayError,
931
- SqliteEventStore,
932
- ConnectionHandler,
933
- NostrRelayServer,
934
- RelaySubscriber,
935
- createWriteHandler,
936
- createHealthResponse,
937
- startRelay
938
- };
939
- //# sourceMappingURL=chunk-FXQSNOCG.js.map