@toon-protocol/relay 1.3.3 → 2.0.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.
@@ -0,0 +1,1027 @@
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/toon/codec.ts
423
+ import { encode, decode } from "@toon-format/toon";
424
+ var ToonEncodeError = class extends Error {
425
+ code = "TOON_ENCODE_ERROR";
426
+ constructor(message, cause) {
427
+ super(message, { cause });
428
+ this.name = "ToonEncodeError";
429
+ }
430
+ };
431
+ var ToonDecodeError = class extends Error {
432
+ code = "TOON_DECODE_ERROR";
433
+ constructor(message, cause) {
434
+ super(message, { cause });
435
+ this.name = "ToonDecodeError";
436
+ }
437
+ };
438
+ function encodeEventToToon(event) {
439
+ return new TextEncoder().encode(encodeEventToToonString(event));
440
+ }
441
+ function encodeEventToToonString(event) {
442
+ try {
443
+ return encode(event);
444
+ } catch (error) {
445
+ throw new ToonEncodeError(
446
+ `Failed to encode event to TOON: ${error instanceof Error ? error.message : String(error)}`,
447
+ error instanceof Error ? error : void 0
448
+ );
449
+ }
450
+ }
451
+ function isValidHex(value, length) {
452
+ return typeof value === "string" && value.length === length && /^[0-9a-f]+$/i.test(value);
453
+ }
454
+ function validateNostrEvent(obj) {
455
+ if (typeof obj !== "object" || obj === null) {
456
+ throw new ToonDecodeError("Decoded value is not an object");
457
+ }
458
+ const event = obj;
459
+ if (!isValidHex(event["id"], 64)) {
460
+ throw new ToonDecodeError(
461
+ "Invalid event id: must be a 64-character hex string"
462
+ );
463
+ }
464
+ if (!isValidHex(event["pubkey"], 64)) {
465
+ throw new ToonDecodeError(
466
+ "Invalid event pubkey: must be a 64-character hex string"
467
+ );
468
+ }
469
+ if (typeof event["kind"] !== "number" || !Number.isInteger(event["kind"])) {
470
+ throw new ToonDecodeError("Invalid event kind: must be an integer");
471
+ }
472
+ if (typeof event["content"] !== "string") {
473
+ throw new ToonDecodeError("Invalid event content: must be a string");
474
+ }
475
+ const tags = event["tags"];
476
+ if (!Array.isArray(tags)) {
477
+ throw new ToonDecodeError("Invalid event tags: must be an array");
478
+ }
479
+ for (let i = 0; i < tags.length; i++) {
480
+ const tag = tags[i];
481
+ if (!Array.isArray(tag)) {
482
+ throw new ToonDecodeError(`Invalid event tags[${i}]: must be an array`);
483
+ }
484
+ for (let j = 0; j < tag.length; j++) {
485
+ if (typeof tag[j] !== "string") {
486
+ throw new ToonDecodeError(
487
+ `Invalid event tags[${i}][${j}]: must be a string`
488
+ );
489
+ }
490
+ }
491
+ }
492
+ if (typeof event["created_at"] !== "number" || !Number.isInteger(event["created_at"])) {
493
+ throw new ToonDecodeError("Invalid event created_at: must be an integer");
494
+ }
495
+ if (!isValidHex(event["sig"], 128)) {
496
+ throw new ToonDecodeError(
497
+ "Invalid event sig: must be a 128-character hex string"
498
+ );
499
+ }
500
+ }
501
+ function decodeEventFromToon(data) {
502
+ let decoded;
503
+ try {
504
+ decoded = decode(new TextDecoder().decode(data));
505
+ } catch (error) {
506
+ throw new ToonDecodeError(
507
+ `Failed to decode TOON data: ${error instanceof Error ? error.message : String(error)}`,
508
+ error instanceof Error ? error : void 0
509
+ );
510
+ }
511
+ validateNostrEvent(decoded);
512
+ return decoded;
513
+ }
514
+
515
+ // src/websocket/ConnectionHandler.ts
516
+ var ConnectionHandler = class {
517
+ constructor(ws, eventStore, config = {}) {
518
+ this.ws = ws;
519
+ this.eventStore = eventStore;
520
+ this.config = { ...DEFAULT_RELAY_CONFIG, ...config };
521
+ }
522
+ subscriptions = /* @__PURE__ */ new Map();
523
+ config;
524
+ /**
525
+ * Handle an incoming message from the WebSocket.
526
+ */
527
+ handleMessage(data) {
528
+ console.log(`[ConnectionHandler] Received message:`, data.slice(0, 150));
529
+ let message;
530
+ try {
531
+ const parsed = JSON.parse(data);
532
+ if (!Array.isArray(parsed)) {
533
+ this.sendNotice("error: invalid message format, expected JSON array");
534
+ return;
535
+ }
536
+ message = parsed;
537
+ } catch {
538
+ this.sendNotice("error: invalid JSON");
539
+ return;
540
+ }
541
+ const messageType = message[0];
542
+ console.log(`[ConnectionHandler] Message type: ${messageType}`);
543
+ if (messageType === "REQ") {
544
+ const subscriptionId = message[1];
545
+ const filters = message.slice(2);
546
+ this.handleReq(subscriptionId, filters);
547
+ } else if (messageType === "EVENT") {
548
+ const event = message[1];
549
+ this.handleEvent(event);
550
+ } else if (messageType === "CLOSE") {
551
+ const subscriptionId = message[1];
552
+ this.handleClose(subscriptionId);
553
+ } else {
554
+ this.sendNotice(`error: unknown message type: ${messageType}`);
555
+ }
556
+ }
557
+ /**
558
+ * Handle a REQ message to create/update a subscription.
559
+ */
560
+ handleReq(subscriptionId, filters) {
561
+ if (typeof subscriptionId !== "string" || subscriptionId.length === 0) {
562
+ this.sendNotice("error: invalid subscription id");
563
+ return;
564
+ }
565
+ if (!this.subscriptions.has(subscriptionId)) {
566
+ if (this.subscriptions.size >= this.config.maxSubscriptionsPerConnection) {
567
+ this.sendNotice("error: too many subscriptions");
568
+ return;
569
+ }
570
+ }
571
+ if (filters.length > this.config.maxFiltersPerSubscription) {
572
+ this.sendNotice("error: too many filters");
573
+ return;
574
+ }
575
+ this.subscriptions.set(subscriptionId, {
576
+ id: subscriptionId,
577
+ filters
578
+ });
579
+ console.log(
580
+ `[ConnectionHandler] REQ: ${subscriptionId}, filters:`,
581
+ JSON.stringify(filters).slice(0, 100)
582
+ );
583
+ const events = this.eventStore.query(filters);
584
+ console.log(
585
+ `[ConnectionHandler] Query returned ${events.length} events for ${subscriptionId}`
586
+ );
587
+ for (const event of events) {
588
+ console.log(
589
+ `[ConnectionHandler] Sending event ${event.id.slice(0, 16)}... to ${subscriptionId}`
590
+ );
591
+ this.sendEvent(subscriptionId, event);
592
+ }
593
+ console.log(`[ConnectionHandler] Sending EOSE for ${subscriptionId}`);
594
+ this.sendEose(subscriptionId);
595
+ }
596
+ /**
597
+ * Handle an EVENT message from a WebSocket client.
598
+ *
599
+ * Rejects all external writes — the relay is ILP-gated (pay to write).
600
+ * Events are only stored through the ILP packet handler which calls
601
+ * eventStore.store() directly and then broadcastEvent() to notify subscribers.
602
+ */
603
+ handleEvent(event) {
604
+ this.sendOk(event.id, false, "restricted: writes require ILP payment");
605
+ }
606
+ /**
607
+ * Handle a CLOSE message to terminate a subscription.
608
+ */
609
+ handleClose(subscriptionId) {
610
+ this.subscriptions.delete(subscriptionId);
611
+ }
612
+ /**
613
+ * Push a new event to all matching subscriptions on this connection.
614
+ * Used when events are stored outside the WebSocket flow (e.g., via ILP).
615
+ */
616
+ notifyNewEvent(event) {
617
+ for (const sub of this.subscriptions.values()) {
618
+ const matches = sub.filters.some((f) => matchFilter(event, f));
619
+ if (matches) {
620
+ this.sendEvent(sub.id, event);
621
+ }
622
+ }
623
+ }
624
+ /**
625
+ * Clean up all subscriptions for this connection.
626
+ */
627
+ cleanup() {
628
+ this.subscriptions.clear();
629
+ }
630
+ /**
631
+ * Get the number of active subscriptions.
632
+ */
633
+ getSubscriptionCount() {
634
+ return this.subscriptions.size;
635
+ }
636
+ sendEvent(subscriptionId, event) {
637
+ this.send(["EVENT", subscriptionId, encodeEventToToonString(event)]);
638
+ }
639
+ sendEose(subscriptionId) {
640
+ this.send(["EOSE", subscriptionId]);
641
+ }
642
+ sendOk(eventId, success, message) {
643
+ this.send(["OK", eventId, success, message]);
644
+ }
645
+ sendNotice(message) {
646
+ this.send(["NOTICE", message]);
647
+ }
648
+ send(message) {
649
+ if (this.ws.readyState === 1) {
650
+ this.ws.send(JSON.stringify(message));
651
+ }
652
+ }
653
+ };
654
+
655
+ // src/websocket/NostrRelayServer.ts
656
+ import { WebSocketServer } from "ws";
657
+ var NostrRelayServer = class {
658
+ constructor(config = {}, eventStore) {
659
+ this.eventStore = eventStore;
660
+ this.config = { ...DEFAULT_RELAY_CONFIG, ...config };
661
+ }
662
+ wss = null;
663
+ handlers = /* @__PURE__ */ new Map();
664
+ config;
665
+ /**
666
+ * Start the WebSocket server.
667
+ */
668
+ async start() {
669
+ return new Promise((resolve, reject) => {
670
+ try {
671
+ this.wss = new WebSocketServer({
672
+ port: this.config.port,
673
+ host: this.config.host
674
+ });
675
+ this.wss.on("connection", (ws) => {
676
+ this.handleConnection(ws);
677
+ });
678
+ this.wss.on("error", (error) => {
679
+ console.error("[NostrRelayServer] Server error:", error.message);
680
+ });
681
+ this.wss.on("listening", () => {
682
+ const address = this.wss?.address();
683
+ if (address && typeof address === "object") {
684
+ console.log(`[NostrRelayServer] Listening on port ${address.port}`);
685
+ }
686
+ resolve();
687
+ });
688
+ } catch (error) {
689
+ reject(error);
690
+ }
691
+ });
692
+ }
693
+ /**
694
+ * Stop the WebSocket server and close all connections.
695
+ */
696
+ async stop() {
697
+ return new Promise((resolve) => {
698
+ if (!this.wss) {
699
+ resolve();
700
+ return;
701
+ }
702
+ for (const [ws, handler] of this.handlers) {
703
+ handler.cleanup();
704
+ ws.close();
705
+ }
706
+ this.handlers.clear();
707
+ this.wss.close(() => {
708
+ this.wss = null;
709
+ resolve();
710
+ });
711
+ });
712
+ }
713
+ /**
714
+ * Get the port the server is listening on.
715
+ * Returns 0 if the server is not started.
716
+ */
717
+ getPort() {
718
+ if (!this.wss) return 0;
719
+ const address = this.wss.address();
720
+ if (address && typeof address === "object") {
721
+ return address.port;
722
+ }
723
+ return 0;
724
+ }
725
+ /**
726
+ * Get the number of connected clients.
727
+ */
728
+ getClientCount() {
729
+ return this.handlers.size;
730
+ }
731
+ /**
732
+ * Broadcast an event to all connected clients with matching subscriptions.
733
+ * Call this after storing an event outside the WebSocket flow (e.g., via ILP)
734
+ * so that discovery subscribers are notified.
735
+ */
736
+ broadcastEvent(event) {
737
+ for (const handler of this.handlers.values()) {
738
+ handler.notifyNewEvent(event);
739
+ }
740
+ }
741
+ handleConnection(ws) {
742
+ if (this.handlers.size >= this.config.maxConnections) {
743
+ ws.close(1013, "max connections reached");
744
+ return;
745
+ }
746
+ console.log("[NostrRelayServer] Client connected");
747
+ const handler = new ConnectionHandler(ws, this.eventStore, this.config);
748
+ this.handlers.set(ws, handler);
749
+ ws.on("message", (data) => {
750
+ const message = typeof data === "string" ? data : data.toString();
751
+ handler.handleMessage(message);
752
+ });
753
+ ws.on("close", () => {
754
+ console.log("[NostrRelayServer] Client disconnected");
755
+ handler.cleanup();
756
+ this.handlers.delete(ws);
757
+ });
758
+ ws.on("error", (error) => {
759
+ console.error("[NostrRelayServer] Client error:", error.message);
760
+ handler.cleanup();
761
+ this.handlers.delete(ws);
762
+ });
763
+ }
764
+ };
765
+
766
+ // src/subscriber/RelaySubscriber.ts
767
+ import { SimplePool } from "nostr-tools/pool";
768
+ import { verifyEvent } from "nostr-tools/pure";
769
+ var RelaySubscriber = class {
770
+ config;
771
+ eventStore;
772
+ pool;
773
+ started = false;
774
+ /**
775
+ * @param config - Subscriber configuration
776
+ * @param eventStore - Storage backend to write events into
777
+ * @param pool - Optional SimplePool instance (creates new one if not provided)
778
+ */
779
+ constructor(config, eventStore, pool) {
780
+ this.config = config;
781
+ this.eventStore = eventStore;
782
+ this.pool = pool ?? new SimplePool();
783
+ }
784
+ /**
785
+ * Start subscribing to the configured upstream relays.
786
+ *
787
+ * @returns Handle with unsubscribe() to stop the subscription
788
+ * @throws Error if already started
789
+ */
790
+ start() {
791
+ if (this.started) {
792
+ throw new Error("RelaySubscriber already started");
793
+ }
794
+ this.started = true;
795
+ const shouldVerify = this.config.verifySignatures !== false;
796
+ let isUnsubscribed = false;
797
+ const subCloser = this.pool.subscribeMany(
798
+ this.config.relayUrls,
799
+ this.config.filter,
800
+ {
801
+ onevent: (event) => {
802
+ if (isUnsubscribed) return;
803
+ if (shouldVerify && !verifyEvent(event)) {
804
+ return;
805
+ }
806
+ try {
807
+ this.eventStore.store(event);
808
+ } catch (error) {
809
+ console.warn(
810
+ "[RelaySubscriber] Failed to store event:",
811
+ error instanceof Error ? error.message : "Unknown error"
812
+ );
813
+ }
814
+ }
815
+ }
816
+ );
817
+ return {
818
+ unsubscribe: () => {
819
+ if (!isUnsubscribed) {
820
+ isUnsubscribed = true;
821
+ subCloser.close();
822
+ this.started = false;
823
+ }
824
+ }
825
+ };
826
+ }
827
+ };
828
+
829
+ // src/launcher/handlers/write-handler.ts
830
+ import { verifyEvent as verifyEvent2 } from "nostr-tools/pure";
831
+ function createWriteHandler(config) {
832
+ return {
833
+ async handleWrite(c) {
834
+ let body;
835
+ try {
836
+ body = await c.req.json();
837
+ } catch {
838
+ return c.json({ error: "Invalid request body" }, 400);
839
+ }
840
+ if (!body.event) {
841
+ return c.json({ error: "Missing required field: event" }, 400);
842
+ }
843
+ const event = body.event;
844
+ const payer = c.req.header("X-TOON-Payer");
845
+ const amount = c.req.header("X-TOON-Amount");
846
+ const chain = c.req.header("X-TOON-Chain");
847
+ console.log(
848
+ `[write] event=${event.id} payer=${payer ?? "-"} amount=${amount ?? "-"} chain=${chain ?? "-"}`
849
+ );
850
+ if (!config.devMode && !verifyEvent2(event)) {
851
+ return c.json({ error: "Invalid event signature" }, 422);
852
+ }
853
+ config.eventStore.store(event);
854
+ config.onStored?.(event);
855
+ return c.json(
856
+ {
857
+ eventId: event.id,
858
+ storedAt: Math.floor(Date.now() / 1e3),
859
+ payer,
860
+ amount,
861
+ chain
862
+ },
863
+ 200
864
+ );
865
+ }
866
+ };
867
+ }
868
+
869
+ // src/launcher/health.ts
870
+ function createHealthResponse(config) {
871
+ return {
872
+ status: "healthy",
873
+ pubkey: config.pubkey,
874
+ capabilities: ["relay"],
875
+ version: VERSION,
876
+ timestamp: Date.now()
877
+ };
878
+ }
879
+
880
+ // src/launcher/relay.ts
881
+ import { mkdirSync } from "fs";
882
+ import { join } from "path";
883
+ import { serve } from "@hono/node-server";
884
+ import { Hono } from "hono";
885
+ import { getPublicKey } from "nostr-tools/pure";
886
+ import { privateKeyFromSeedWords } from "nostr-tools/nip06";
887
+ function deriveIdentity(config) {
888
+ const hasMnemonic = config.mnemonic !== void 0;
889
+ const hasSecretKey = config.secretKey !== void 0;
890
+ if (hasMnemonic && hasSecretKey) {
891
+ throw new Error(
892
+ "RelayConfig: provide either mnemonic or secretKey, not both"
893
+ );
894
+ }
895
+ if (!hasMnemonic && !hasSecretKey) {
896
+ throw new Error("RelayConfig: one of mnemonic or secretKey is required");
897
+ }
898
+ const secretKey = hasMnemonic ? privateKeyFromSeedWords(config.mnemonic) : config.secretKey;
899
+ return { secretKey, pubkey: getPublicKey(secretKey) };
900
+ }
901
+ function createSubscription(relayUrl, filter, eventStore, activeSubscriptions) {
902
+ if (!relayUrl.startsWith("ws://") && !relayUrl.startsWith("wss://")) {
903
+ throw new Error(
904
+ "Invalid relay URL -- must use WebSocket scheme (ws or wss)"
905
+ );
906
+ }
907
+ const subscriber = new RelaySubscriber(
908
+ { relayUrls: [relayUrl], filter },
909
+ eventStore
910
+ );
911
+ const handle = subscriber.start();
912
+ let active = true;
913
+ const subscription = {
914
+ close() {
915
+ if (!active) return;
916
+ active = false;
917
+ handle.unsubscribe();
918
+ activeSubscriptions.delete(subscription);
919
+ },
920
+ relayUrl,
921
+ isActive() {
922
+ return active;
923
+ }
924
+ };
925
+ activeSubscriptions.add(subscription);
926
+ return subscription;
927
+ }
928
+ async function startRelay(config) {
929
+ const identity = deriveIdentity(config);
930
+ const relayPort = config.relayPort ?? 7100;
931
+ const blsPort = config.blsPort ?? 3100;
932
+ const host = config.host ?? "0.0.0.0";
933
+ const dataDir = config.dataDir ?? "./data";
934
+ const devMode = config.devMode ?? false;
935
+ const resolvedConfig = {
936
+ relayPort,
937
+ blsPort,
938
+ host,
939
+ dataDir,
940
+ devMode
941
+ };
942
+ let eventStore;
943
+ if (config.eventStore) {
944
+ eventStore = config.eventStore;
945
+ } else {
946
+ mkdirSync(dataDir, { recursive: true });
947
+ eventStore = new SqliteEventStore(join(dataDir, "events.db"));
948
+ }
949
+ const wsRelay = new NostrRelayServer({ port: relayPort, host }, eventStore);
950
+ const app = new Hono();
951
+ app.get(
952
+ "/health",
953
+ (c) => c.json(createHealthResponse({ pubkey: identity.pubkey }))
954
+ );
955
+ const writeHandler = createWriteHandler({
956
+ eventStore,
957
+ devMode,
958
+ onStored: (event) => {
959
+ try {
960
+ wsRelay.broadcastEvent(event);
961
+ } catch {
962
+ }
963
+ }
964
+ });
965
+ app.post("/write", (c) => writeHandler.handleWrite(c));
966
+ const blsServer = await new Promise((resolve) => {
967
+ const server = serve(
968
+ { fetch: app.fetch, port: blsPort },
969
+ () => resolve(server)
970
+ );
971
+ });
972
+ await wsRelay.start();
973
+ let running = true;
974
+ const activeSubscriptions = /* @__PURE__ */ new Set();
975
+ const instance = {
976
+ isRunning() {
977
+ return running;
978
+ },
979
+ subscribe(subscribeRelayUrl, filter) {
980
+ if (!running) {
981
+ throw new Error("Cannot subscribe: relay is not running");
982
+ }
983
+ return createSubscription(
984
+ subscribeRelayUrl,
985
+ filter,
986
+ eventStore,
987
+ activeSubscriptions
988
+ );
989
+ },
990
+ async stop() {
991
+ if (!running) return;
992
+ running = false;
993
+ for (const sub of activeSubscriptions) {
994
+ sub.close();
995
+ }
996
+ activeSubscriptions.clear();
997
+ await wsRelay.stop();
998
+ blsServer.close();
999
+ if (!config.eventStore) {
1000
+ eventStore.close?.();
1001
+ }
1002
+ },
1003
+ pubkey: identity.pubkey,
1004
+ config: resolvedConfig
1005
+ };
1006
+ return instance;
1007
+ }
1008
+
1009
+ export {
1010
+ VERSION,
1011
+ DEFAULT_RELAY_CONFIG,
1012
+ matchFilter,
1013
+ InMemoryEventStore,
1014
+ RelayError,
1015
+ SqliteEventStore,
1016
+ ToonEncodeError,
1017
+ ToonDecodeError,
1018
+ encodeEventToToon,
1019
+ decodeEventFromToon,
1020
+ ConnectionHandler,
1021
+ NostrRelayServer,
1022
+ RelaySubscriber,
1023
+ createWriteHandler,
1024
+ createHealthResponse,
1025
+ startRelay
1026
+ };
1027
+ //# sourceMappingURL=chunk-745ADETR.js.map