node-red-contrib-nostr 0.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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +222 -0
  3. package/dist/core/event.d.ts +6 -0
  4. package/dist/core/event.js +58 -0
  5. package/dist/core/filter.d.ts +14 -0
  6. package/dist/core/filter.js +52 -0
  7. package/dist/crypto/keys.d.ts +38 -0
  8. package/dist/crypto/keys.js +124 -0
  9. package/dist/nips/nip01.d.ts +22 -0
  10. package/dist/nips/nip01.js +65 -0
  11. package/dist/nips/nip02.d.ts +15 -0
  12. package/dist/nips/nip02.js +35 -0
  13. package/dist/nips/nip04.d.ts +8 -0
  14. package/dist/nips/nip04.js +89 -0
  15. package/dist/nips/nip05.d.ts +8 -0
  16. package/dist/nips/nip05.js +42 -0
  17. package/dist/nodes/example/example.d.ts +1 -0
  18. package/dist/nodes/example/example.html +27 -0
  19. package/dist/nodes/example/example.js +14 -0
  20. package/dist/nodes/index.d.ts +3 -0
  21. package/dist/nodes/index.js +20 -0
  22. package/dist/nodes/nostr-filter/nostr-filter.d.ts +2 -0
  23. package/dist/nodes/nostr-filter/nostr-filter.html +142 -0
  24. package/dist/nodes/nostr-filter/nostr-filter.js +174 -0
  25. package/dist/nodes/nostr-npub-filter/nostr-npub-filter.d.ts +2 -0
  26. package/dist/nodes/nostr-npub-filter/nostr-npub-filter.html +130 -0
  27. package/dist/nodes/nostr-npub-filter/nostr-npub-filter.js +104 -0
  28. package/dist/nodes/nostr-relay/nostr-relay.d.ts +2 -0
  29. package/dist/nodes/nostr-relay/nostr-relay.html +66 -0
  30. package/dist/nodes/nostr-relay/nostr-relay.js +49 -0
  31. package/dist/nodes/nostr-relay-config/nostr-relay-config.d.ts +9 -0
  32. package/dist/nodes/nostr-relay-config/nostr-relay-config.html +56 -0
  33. package/dist/nodes/nostr-relay-config/nostr-relay-config.js +106 -0
  34. package/dist/nodes/shared/types.d.ts +26 -0
  35. package/dist/nodes/shared/types.js +2 -0
  36. package/dist/nodes/shared/utils.d.ts +28 -0
  37. package/dist/nodes/shared/utils.js +86 -0
  38. package/dist/types.d.ts +34 -0
  39. package/dist/types.js +2 -0
  40. package/dist/utils/nip19.d.ts +8 -0
  41. package/dist/utils/nip19.js +34 -0
  42. package/dist/utils/validation.d.ts +8 -0
  43. package/dist/utils/validation.js +31 -0
  44. package/examples/basic-relay.json +48 -0
  45. package/examples/jack-monitor.json +69 -0
  46. package/examples/multi-user-monitor.json +129 -0
  47. package/locales/en-US/messages.json +63 -0
  48. package/package.json +86 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Humanjava Enterprises
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,222 @@
1
+ # node-red-contrib-nostr
2
+
3
+ [![npm version](https://badge.fury.io/js/node-red-contrib-nostr.svg)](https://badge.fury.io/js/node-red-contrib-nostr)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![Node-RED](https://img.shields.io/badge/Node--RED-Contribution-red.svg)](https://flows.nodered.org/node/node-red-contrib-nostr)
6
+ [![Tests](https://github.com/HumanjavaEnterprises/node-red-contrib-nostr/actions/workflows/test.yml/badge.svg)](https://github.com/HumanjavaEnterprises/node-red-contrib-nostr/actions/workflows/test.yml)
7
+ [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)
8
+ [![Known Vulnerabilities](https://snyk.io/test/github/HumanJavaEnterprise/node-red-contrib-nostr/badge.svg)](https://snyk.io/test/github/HumanJavaEnterprise/node-red-contrib-nostr)
9
+
10
+ A [Node-RED](http://nodered.org) node for integrating with the Nostr protocol. This node allows you to connect to Nostr relays, publish events, and subscribe to events in the Nostr network.
11
+
12
+ ## ⚠️ Security Note
13
+
14
+ A private key is **only required** if you want to:
15
+ - Publish events to relays
16
+ - Send encrypted direct messages
17
+ - Perform any action that requires signing
18
+
19
+ For just listening to relays or subscribing to events, **no private key is needed**.
20
+
21
+ If you do need to publish events, follow these security guidelines:
22
+
23
+ 1. Generate a separate key pair specifically for your Node-RED automation using services like:
24
+ - [nsec.app](https://nsec.app/)
25
+ - [Alby](https://getalby.com/)
26
+ - [Nostr.band](https://nostr.band/)
27
+
28
+ 2. Keep the scope of this automation key limited:
29
+ - Only give it permissions it actually needs
30
+ - Consider it like a "bot account"
31
+ - Regularly rotate the key if possible
32
+
33
+ 3. Store the private key securely:
34
+ - Use Node-RED's encrypted credentials
35
+ - Never share or expose the key
36
+ - Don't commit it to version control
37
+
38
+ ## Description
39
+
40
+ This package provides nodes for interacting with Nostr relays, allowing you to:
41
+ - Connect to multiple relays simultaneously
42
+ - Monitor specific NPUBs for events
43
+ - Filter events by type (text notes, DMs, etc.)
44
+ - Post events to relays (using a dedicated automation key)
45
+ - Support for multiple NIPs (see Supported NIPs section)
46
+ - TypeScript support with full type definitions
47
+ - Secure credential management
48
+ - Automatic reconnection handling
49
+
50
+ ## Technical Architecture
51
+
52
+ ### Module System
53
+ This package uses a hybrid approach to module systems to ensure maximum compatibility:
54
+ - Built as CommonJS for Node-RED compatibility
55
+ - Handles ESM dependencies through dynamic imports
56
+ - Supports both modern and legacy Node.js environments
57
+
58
+ ### WebSocket Management
59
+ Built on [nostr-websocket-utils](https://github.com/yourusername/nostr-websocket-utils) for enterprise-grade reliability:
60
+ - **Automatic Reconnection**: Smart backoff strategy for connection drops
61
+ - **Connection Health**: Built-in heartbeat monitoring
62
+ - **Type Safety**: Full TypeScript support
63
+ - **Error Resilience**: Comprehensive error handling
64
+ - **Memory Efficient**: Proper cleanup of resources
65
+ - **Debug Support**: Detailed logging
66
+
67
+ ## Install
68
+
69
+ ### From npm (Recommended)
70
+ Run the following command in your Node-RED user directory - typically `~/.node-red`
71
+
72
+ ```bash
73
+ npm install node-red-contrib-nostr
74
+ ```
75
+
76
+ ### From Source
77
+ ```bash
78
+ cd ~/.node-red
79
+ git clone https://github.com/HumanjavaEnterprises/node-red-contrib-nostr.git
80
+ cd node-red-contrib-nostr
81
+ npm install
82
+ npm run build
83
+ ```
84
+
85
+ ### Using Docker
86
+ ```bash
87
+ git clone https://github.com/HumanjavaEnterprises/node-red-contrib-nostr.git
88
+ cd node-red-contrib-nostr
89
+ docker compose up -d
90
+ ```
91
+
92
+ ## Nodes
93
+
94
+ ### 1. Nostr Relay Config Node
95
+ Configuration node for managing relay connections:
96
+ - Multiple relay support
97
+ - Secure private key storage
98
+ - Automatic reconnection handling
99
+ - Connection status monitoring
100
+ - Dynamic import of ESM dependencies
101
+
102
+ ### 2. Nostr Filter Node
103
+ Specialized node for event filtering:
104
+ - Filter by event kinds
105
+ - Filter by authors (NPUBs)
106
+ - Filter by tags
107
+ - Time-based filtering
108
+ - Custom filter combinations
109
+ - Real-time event processing
110
+
111
+ ### 3. Nostr NPUB Filter Node
112
+ Dedicated node for NPUB-based filtering:
113
+ - Monitor specific NPUBs
114
+ - Filter by event types
115
+ - Real-time NPUB event tracking
116
+ - Automatic hex key conversion
117
+
118
+ ## Example Flows
119
+
120
+ ### Basic Event Monitoring
121
+ ```json
122
+ {
123
+ "id": "basic-monitor",
124
+ "type": "nostr-filter",
125
+ "relay": "wss://relay.example.com",
126
+ "filterType": "kind",
127
+ "eventKinds": [1],
128
+ "wires": [["debug"]]
129
+ }
130
+ ```
131
+
132
+ ### NPUB Tracking
133
+ ```json
134
+ {
135
+ "id": "npub-track",
136
+ "type": "nostr-npub-filter",
137
+ "relay": "wss://relay.example.com",
138
+ "npubValue": "npub1...",
139
+ "eventKinds": [1, 6],
140
+ "wires": [["debug"]]
141
+ }
142
+ ```
143
+
144
+ ## Error Handling
145
+
146
+ The nodes implement comprehensive error handling:
147
+ - Invalid private key detection
148
+ - Relay connection failures
149
+ - Message parsing errors
150
+ - NPUB validation
151
+ - WebSocket connection issues
152
+
153
+ ## Development
154
+
155
+ ### Building from Source
156
+ ```bash
157
+ npm install
158
+ npm run build
159
+ ```
160
+
161
+ ### Running Tests
162
+ ```bash
163
+ npm test
164
+ ```
165
+
166
+ Test coverage includes:
167
+ - Unit tests for all nodes
168
+ - WebSocket connection handling
169
+ - Event filtering logic
170
+ - Error handling
171
+
172
+ ### Docker Development
173
+ ```bash
174
+ docker compose -f docker-compose.dev.yml up
175
+ ```
176
+
177
+ ## Supported NIPs
178
+
179
+ | NIP | Description | Status |
180
+ |-----|------------|--------|
181
+ | [NIP-01](https://github.com/nostr-protocol/nips/blob/master/01.md) | Basic Protocol | ✅ Implemented |
182
+ | [NIP-02](https://github.com/nostr-protocol/nips/blob/master/02.md) | Contact List and Petnames | ✅ Implemented |
183
+ | [NIP-03](https://github.com/nostr-protocol/nips/blob/master/03.md) | OpenTimestamps Attestations | 🚧 Planned |
184
+ | [NIP-04](https://github.com/nostr-protocol/nips/blob/master/04.md) | Encrypted Direct Messages | 🚧 Planned |
185
+ | [NIP-09](https://github.com/nostr-protocol/nips/blob/master/09.md) | Event Deletion | 🚧 Planned |
186
+ | [NIP-11](https://github.com/nostr-protocol/nips/blob/master/11.md) | Relay Information Document | ✅ Implemented |
187
+ | [NIP-15](https://github.com/nostr-protocol/nips/blob/master/15.md) | End of Stored Events Notice | ✅ Implemented |
188
+ | [NIP-20](https://github.com/nostr-protocol/nips/blob/master/20.md) | Command Results | ✅ Implemented |
189
+ | [NIP-28](https://github.com/nostr-protocol/nips/blob/master/28.md) | Public Chat | 🚧 Planned |
190
+ | [NIP-40](https://github.com/nostr-protocol/nips/blob/master/40.md) | Expiration Timestamp | 🚧 Planned |
191
+
192
+ Legend:
193
+ - ✅ Implemented: Fully supported
194
+ - 🚧 Planned: On the roadmap
195
+ - ❌ Not Planned: Not currently planned for implementation
196
+
197
+ ## Contributing
198
+
199
+ 1. Fork the repository
200
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
201
+ 3. Commit your changes (`git commit -m 'feat: add amazing feature'`)
202
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
203
+ 5. Open a Pull Request
204
+
205
+ ## License
206
+
207
+ This project is licensed under the MIT License - see the LICENSE file for details.
208
+
209
+ ## Node-RED Specific Tags
210
+
211
+ This module provides nodes for working with Nostr protocol in Node-RED.
212
+
213
+ ### Node Properties
214
+
215
+ * Category: network
216
+ * Name: node-red-contrib-nostr
217
+ * Types: nostr-relay-config, nostr-filter, nostr-npub-filter
218
+ * Description: Node-RED nodes for interacting with Nostr protocol
219
+ * Author: Vveerrgg
220
+ * Keywords: node-red,nostr,websocket,relay,filter,npub
221
+ * Dependencies: @humanjavaenterprises/nostr-tools,nostr-websocket-utils
222
+ * Node-RED: >= 2.0.0
@@ -0,0 +1,6 @@
1
+ import { NostrEvent } from '../nodes/shared/types';
2
+ export declare class EventBuilder {
3
+ private static keyManager;
4
+ static createEvent(kind: number, content: string, privateKey: string, tags?: string[][]): Promise<NostrEvent>;
5
+ static validateEvent(event: NostrEvent): Promise<boolean>;
6
+ }
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EventBuilder = void 0;
4
+ const sha256_1 = require("@noble/hashes/sha256");
5
+ const utils_1 = require("@noble/hashes/utils");
6
+ const keys_1 = require("../crypto/keys");
7
+ class EventBuilder {
8
+ static async createEvent(kind, content, privateKey, tags = []) {
9
+ const pubkey = await this.keyManager.getPublicKey(privateKey);
10
+ const created_at = Math.floor(Date.now() / 1000);
11
+ const event = {
12
+ kind,
13
+ content,
14
+ created_at,
15
+ pubkey,
16
+ tags,
17
+ id: '',
18
+ sig: ''
19
+ };
20
+ // Calculate event ID
21
+ const serialized = JSON.stringify([
22
+ 0,
23
+ event.pubkey,
24
+ event.created_at,
25
+ event.kind,
26
+ event.tags,
27
+ event.content
28
+ ]);
29
+ event.id = (0, utils_1.bytesToHex)((0, sha256_1.sha256)(Buffer.from(serialized)));
30
+ // Sign the event
31
+ event.sig = await this.keyManager.sign(privateKey, event.id);
32
+ return event;
33
+ }
34
+ static async validateEvent(event) {
35
+ // Verify all required fields exist
36
+ if (!event.id || !event.pubkey || !event.created_at ||
37
+ !event.kind || !event.tags || !event.content || !event.sig) {
38
+ return false;
39
+ }
40
+ // Verify event ID
41
+ const serialized = JSON.stringify([
42
+ 0,
43
+ event.pubkey,
44
+ event.created_at,
45
+ event.kind,
46
+ event.tags,
47
+ event.content
48
+ ]);
49
+ const id = (0, utils_1.bytesToHex)((0, sha256_1.sha256)(Buffer.from(serialized)));
50
+ if (id !== event.id) {
51
+ return false;
52
+ }
53
+ // Verify signature
54
+ return await this.keyManager.verify(event.pubkey, event.id, event.sig);
55
+ }
56
+ }
57
+ exports.EventBuilder = EventBuilder;
58
+ EventBuilder.keyManager = new keys_1.KeyManager();
@@ -0,0 +1,14 @@
1
+ import { NostrFilter } from '../nodes/shared/types';
2
+ export declare class FilterBuilder {
3
+ private filter;
4
+ withIds(ids: string[]): FilterBuilder;
5
+ withAuthors(authors: string[]): FilterBuilder;
6
+ withKinds(kinds: number[]): FilterBuilder;
7
+ withSince(timestamp: number): FilterBuilder;
8
+ withUntil(timestamp: number): FilterBuilder;
9
+ withLimit(limit: number): FilterBuilder;
10
+ withSearch(search: string): FilterBuilder;
11
+ build(): NostrFilter;
12
+ static createTextNoteFilter(limit?: number): NostrFilter;
13
+ static createUserMetadataFilter(pubkeys: string[]): NostrFilter;
14
+ }
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FilterBuilder = void 0;
4
+ class FilterBuilder {
5
+ constructor() {
6
+ this.filter = {};
7
+ }
8
+ withIds(ids) {
9
+ this.filter.ids = ids;
10
+ return this;
11
+ }
12
+ withAuthors(authors) {
13
+ this.filter.authors = authors;
14
+ return this;
15
+ }
16
+ withKinds(kinds) {
17
+ this.filter.kinds = kinds;
18
+ return this;
19
+ }
20
+ withSince(timestamp) {
21
+ this.filter.since = timestamp;
22
+ return this;
23
+ }
24
+ withUntil(timestamp) {
25
+ this.filter.until = timestamp;
26
+ return this;
27
+ }
28
+ withLimit(limit) {
29
+ this.filter.limit = limit;
30
+ return this;
31
+ }
32
+ withSearch(search) {
33
+ this.filter.search = search;
34
+ return this;
35
+ }
36
+ build() {
37
+ return { ...this.filter };
38
+ }
39
+ static createTextNoteFilter(limit = 10) {
40
+ return new FilterBuilder()
41
+ .withKinds([1])
42
+ .withLimit(limit)
43
+ .build();
44
+ }
45
+ static createUserMetadataFilter(pubkeys) {
46
+ return new FilterBuilder()
47
+ .withKinds([0])
48
+ .withAuthors(pubkeys)
49
+ .build();
50
+ }
51
+ }
52
+ exports.FilterBuilder = FilterBuilder;
@@ -0,0 +1,38 @@
1
+ export declare const DEFAULT_READER_KEYS: {
2
+ privateKey: string;
3
+ publicKey: string;
4
+ };
5
+ /**
6
+ * Generate a new Nostr key pair
7
+ * @returns {Promise<Object>} Object containing private and public keys
8
+ */
9
+ export declare function generateKeyPair(): Promise<{
10
+ privateKey: string;
11
+ publicKey: string;
12
+ }>;
13
+ /**
14
+ * Convert a hex public key to npub format
15
+ * @param {string} publicKeyHex - Public key in hex format
16
+ * @returns {string} npub formatted public key
17
+ */
18
+ export declare function hexToNpub(publicKeyHex: string): string;
19
+ /**
20
+ * Convert an npub to hex format
21
+ * @param {string} npub - npub formatted public key
22
+ * @returns {string} Public key in hex format
23
+ */
24
+ export declare function npubToHex(npub: string): string;
25
+ /**
26
+ * Get public key from private key
27
+ * @param {string} privateKeyHex - Private key in hex format
28
+ * @returns {Promise<string>} Public key in hex format
29
+ */
30
+ export declare function getPublicKey(privateKeyHex: string): Promise<string>;
31
+ export declare class KeyManager {
32
+ private secp256k1Promise;
33
+ constructor();
34
+ generatePrivateKey(): Promise<string>;
35
+ getPublicKey(privateKey: string): Promise<string>;
36
+ sign(privateKey: string, message: string): Promise<string>;
37
+ verify(publicKey: string, message: string, signature: string): Promise<boolean>;
38
+ }
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.KeyManager = exports.DEFAULT_READER_KEYS = void 0;
37
+ exports.generateKeyPair = generateKeyPair;
38
+ exports.hexToNpub = hexToNpub;
39
+ exports.npubToHex = npubToHex;
40
+ exports.getPublicKey = getPublicKey;
41
+ const bech32_1 = require("bech32");
42
+ const utils_1 = require("@noble/hashes/utils");
43
+ const sha256_1 = require("@noble/hashes/sha256");
44
+ // Default read-only key pair for basic operations
45
+ // This is a dedicated key for node-red-contrib-nostr that's only used for reading events
46
+ exports.DEFAULT_READER_KEYS = {
47
+ privateKey: '5acf32b3374c8c0aa6e483e0f7c6ba8c4b2d2f35d1d5854f08c8c9555d81903b',
48
+ publicKey: '04dbc5c6c357e5f33e19c89a2c0b2c1c41f7b15cc3e8f6a63f5e0e8c5d5c5c5c',
49
+ };
50
+ let secp256k1;
51
+ async function initSecp256k1() {
52
+ if (!secp256k1) {
53
+ secp256k1 = await Promise.resolve().then(() => __importStar(require('@noble/secp256k1')));
54
+ }
55
+ return secp256k1;
56
+ }
57
+ /**
58
+ * Generate a new Nostr key pair
59
+ * @returns {Promise<Object>} Object containing private and public keys
60
+ */
61
+ async function generateKeyPair() {
62
+ const secp = await initSecp256k1();
63
+ const privateKey = secp.utils.randomPrivateKey();
64
+ const publicKey = secp.getPublicKey(privateKey, true);
65
+ return {
66
+ privateKey: Buffer.from(privateKey).toString('hex'),
67
+ publicKey: Buffer.from(publicKey).toString('hex')
68
+ };
69
+ }
70
+ /**
71
+ * Convert a hex public key to npub format
72
+ * @param {string} publicKeyHex - Public key in hex format
73
+ * @returns {string} npub formatted public key
74
+ */
75
+ function hexToNpub(publicKeyHex) {
76
+ const words = bech32_1.bech32.toWords(Buffer.from(publicKeyHex, 'hex'));
77
+ return bech32_1.bech32.encode('npub', words);
78
+ }
79
+ /**
80
+ * Convert an npub to hex format
81
+ * @param {string} npub - npub formatted public key
82
+ * @returns {string} Public key in hex format
83
+ */
84
+ function npubToHex(npub) {
85
+ const { words } = bech32_1.bech32.decode(npub);
86
+ return Buffer.from(bech32_1.bech32.fromWords(words)).toString('hex');
87
+ }
88
+ /**
89
+ * Get public key from private key
90
+ * @param {string} privateKeyHex - Private key in hex format
91
+ * @returns {Promise<string>} Public key in hex format
92
+ */
93
+ async function getPublicKey(privateKeyHex) {
94
+ const secp = await initSecp256k1();
95
+ const publicKey = secp.getPublicKey(privateKeyHex, true);
96
+ return Buffer.from(publicKey).toString('hex');
97
+ }
98
+ class KeyManager {
99
+ constructor() {
100
+ this.secp256k1Promise = initSecp256k1();
101
+ }
102
+ async generatePrivateKey() {
103
+ const secp = await this.secp256k1Promise;
104
+ const privateKey = secp.utils.randomPrivateKey();
105
+ return Buffer.from(privateKey).toString('hex');
106
+ }
107
+ async getPublicKey(privateKey) {
108
+ const secp = await this.secp256k1Promise;
109
+ const publicKey = secp.getPublicKey(privateKey, true);
110
+ return Buffer.from(publicKey).toString('hex');
111
+ }
112
+ async sign(privateKey, message) {
113
+ const secp = await this.secp256k1Promise;
114
+ const messageHash = (0, sha256_1.sha256)(Buffer.from(message));
115
+ const signature = await secp.sign(messageHash, privateKey);
116
+ return (0, utils_1.bytesToHex)(signature.toCompactRawBytes());
117
+ }
118
+ async verify(publicKey, message, signature) {
119
+ const secp = await this.secp256k1Promise;
120
+ const messageHash = (0, sha256_1.sha256)(Buffer.from(message));
121
+ return secp.verify(signature, messageHash, publicKey);
122
+ }
123
+ }
124
+ exports.KeyManager = KeyManager;
@@ -0,0 +1,22 @@
1
+ import { NostrEvent, NostrFilter } from '../nodes/shared/types';
2
+ export declare enum MessageType {
3
+ EVENT = "EVENT",
4
+ REQ = "REQ",
5
+ CLOSE = "CLOSE",
6
+ NOTICE = "NOTICE",
7
+ EOSE = "EOSE",
8
+ OK = "OK"
9
+ }
10
+ export interface RelayMessage {
11
+ type: MessageType;
12
+ subscriptionId?: string;
13
+ event?: NostrEvent;
14
+ message?: string;
15
+ filters?: NostrFilter[];
16
+ success?: boolean;
17
+ error?: string;
18
+ }
19
+ export declare function parseRelayMessage(message: string): RelayMessage | null;
20
+ export declare function createEventMessage(event: NostrEvent): string;
21
+ export declare function createSubscriptionMessage(subscriptionId: string, filters: NostrFilter[]): string;
22
+ export declare function createCloseMessage(subscriptionId: string): string;
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MessageType = void 0;
4
+ exports.parseRelayMessage = parseRelayMessage;
5
+ exports.createEventMessage = createEventMessage;
6
+ exports.createSubscriptionMessage = createSubscriptionMessage;
7
+ exports.createCloseMessage = createCloseMessage;
8
+ var MessageType;
9
+ (function (MessageType) {
10
+ MessageType["EVENT"] = "EVENT";
11
+ MessageType["REQ"] = "REQ";
12
+ MessageType["CLOSE"] = "CLOSE";
13
+ MessageType["NOTICE"] = "NOTICE";
14
+ MessageType["EOSE"] = "EOSE";
15
+ MessageType["OK"] = "OK";
16
+ })(MessageType || (exports.MessageType = MessageType = {}));
17
+ function parseRelayMessage(message) {
18
+ try {
19
+ const parsed = JSON.parse(message);
20
+ if (!Array.isArray(parsed))
21
+ return null;
22
+ const [type, ...params] = parsed;
23
+ switch (type) {
24
+ case MessageType.EVENT:
25
+ const [subscriptionId, event] = params;
26
+ return {
27
+ type: MessageType.EVENT,
28
+ subscriptionId,
29
+ event
30
+ };
31
+ case MessageType.NOTICE:
32
+ return {
33
+ type: MessageType.NOTICE,
34
+ message: params[0]
35
+ };
36
+ case MessageType.EOSE:
37
+ return {
38
+ type: MessageType.EOSE,
39
+ subscriptionId: params[0]
40
+ };
41
+ case MessageType.OK:
42
+ const [eventId, success, message] = params;
43
+ return {
44
+ type: MessageType.OK,
45
+ message: eventId,
46
+ success,
47
+ error: message
48
+ };
49
+ default:
50
+ return null;
51
+ }
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ }
57
+ function createEventMessage(event) {
58
+ return JSON.stringify([MessageType.EVENT, event]);
59
+ }
60
+ function createSubscriptionMessage(subscriptionId, filters) {
61
+ return JSON.stringify([MessageType.REQ, subscriptionId, ...filters]);
62
+ }
63
+ function createCloseMessage(subscriptionId) {
64
+ return JSON.stringify([MessageType.CLOSE, subscriptionId]);
65
+ }
@@ -0,0 +1,15 @@
1
+ import { NostrEvent } from '../nodes/shared/types';
2
+ export interface Contact {
3
+ pubkey: string;
4
+ relayUrl: string;
5
+ petname?: string;
6
+ }
7
+ export declare class ContactList {
8
+ static parseContactList(event: NostrEvent): Contact[];
9
+ static createContactListEvent(contacts: Contact[], privateKey: string): Promise<NostrEvent>;
10
+ static getContactListFilter(pubkey: string): {
11
+ kinds: number[];
12
+ authors: string[];
13
+ limit: number;
14
+ };
15
+ }
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ContactList = void 0;
4
+ const event_1 = require("../core/event");
5
+ class ContactList {
6
+ static parseContactList(event) {
7
+ if (event.kind !== 3)
8
+ throw new Error('Not a contact list event');
9
+ return event.tags
10
+ .filter(tag => tag[0] === 'p')
11
+ .map(tag => ({
12
+ pubkey: tag[1],
13
+ relayUrl: tag[2] || '',
14
+ petname: tag[3]
15
+ }));
16
+ }
17
+ static async createContactListEvent(contacts, privateKey) {
18
+ const tags = contacts.map(contact => [
19
+ 'p',
20
+ contact.pubkey,
21
+ contact.relayUrl,
22
+ contact.petname || ''
23
+ ]);
24
+ return await event_1.EventBuilder.createEvent(3, '', // Content can be empty or contain additional metadata
25
+ privateKey, tags);
26
+ }
27
+ static getContactListFilter(pubkey) {
28
+ return {
29
+ kinds: [3],
30
+ authors: [pubkey],
31
+ limit: 1
32
+ };
33
+ }
34
+ }
35
+ exports.ContactList = ContactList;