Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
631 lines (535 loc) · 17.1 KB
/
Copy pathserver.js
File metadata and controls
631 lines (535 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
require('dotenv').config();
const express = require('express');
const WebSocket = require('ws');
const http = require('http');
const path = require('path');
const fs = require('fs');
const helmet = require('helmet');
const cors = require('cors');
const rateLimit = require('express-rate-limit');
const NodeCache = require('node-cache');
const { validateEvent, verifySignature, generatePrivateKey, getPublicKey, finishEvent, nip19 } = require('nostr-tools');
const ngeohash = require('ngeohash');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
// Cache for storing geohash data
const cache = new NodeCache({ stdTTL: process.env.CACHE_TTL || 300 });
// Security middleware
app.use(helmet());
app.use(cors());
// Rate limiting
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: { error: 'Too many requests from this IP' }
});
app.use('/api/', apiLimiter);
app.use(express.json());
// Serve React build files (when built)
app.use(express.static(path.join(__dirname, 'dist')));
// Fallback to public folder for legacy support
app.use('/legacy', express.static(path.join(__dirname, 'public')));
// Serve the React app for all non-API routes
app.get('*', (req, res, next) => {
if (req.path.startsWith('/api/')) {
return next();
}
// Try to serve from React build first
const reactIndexPath = path.join(__dirname, 'dist', 'index.html');
if (fs.existsSync(reactIndexPath)) {
res.sendFile(reactIndexPath);
} else {
// Fallback to legacy public folder during development
res.sendFile(path.join(__dirname, 'public', 'index.html'));
}
});
// Nostr relay connections
const RELAYS = process.env.NOSTR_RELAYS ?
process.env.NOSTR_RELAYS.split(',') : [
'wss://relay.damus.io',
'wss://nos.lol',
'wss://relay.primal.net',
'wss://offchain.pub',
'wss://nostr21.com',
'wss://nostr-pub.wellorder.net',
'wss://nostr.wine'
];
let relayConnections = new Map();
// Connect to Nostr relays
function connectToRelays() {
RELAYS.forEach(relayUrl => {
try {
const ws = new WebSocket(relayUrl);
ws.on('open', () => {
console.log(`Connected to ${relayUrl}`);
relayConnections.set(relayUrl, ws);
// Subscribe to kind 20000 events (geohash events)
const subscriptionId = `heatmap-${Math.random().toString(36).substring(2, 15)}`;
const subscription = JSON.stringify([
'REQ',
subscriptionId,
{
kinds: [20000],
limit: 100
}
]);
ws.send(subscription);
});
ws.on('message', (data) => {
try {
const message = JSON.parse(data.toString());
handleNostrMessage(message);
} catch (error) {
console.error('Error parsing message:', error);
}
});
ws.on('close', () => {
console.log(`Disconnected from ${relayUrl}`);
relayConnections.delete(relayUrl);
// Reconnect after 5 seconds
setTimeout(() => connectToRelays(), 5000);
});
ws.on('error', (error) => {
console.error(`Error with ${relayUrl}:`, error);
});
} catch (error) {
console.error(`Failed to connect to ${relayUrl}:`, error);
}
});
}
// Proper Nostr event verification function
function verifyEvent(event) {
// First validate the event structure
if (!validateEvent(event)) {
return false;
}
// Then verify the cryptographic signature
try {
return verifySignature(event);
} catch (error) {
console.warn('Signature verification failed:', error.message);
return false;
}
}
// Handle incoming Nostr messages
function handleNostrMessage(message) {
const [type, subscriptionId, event] = message;
if (type === 'EVENT' && event) {
// Validate event before processing
if (!verifyEvent(event)) {
console.warn('Invalid event, discarding:', event.id || 'unknown');
return;
}
const { kind, tags, content, created_at } = event;
if (kind === 20000) {
// Extract geohash and nickname from tags
const geohashTag = tags.find(tag => tag[0] === 'g');
const nicknameTag = tags.find(tag => tag[0] === 'n');
if (geohashTag && geohashTag[1]) {
const geohashData = {
geohash: geohashTag[1],
nickname: nicknameTag ? nicknameTag[1] : 'Anonymous',
message: content,
timestamp: created_at,
relay: 'unknown',
npub: (() => { try { return nip19.npubEncode(event.pubkey); } catch (_) { return undefined; } })()
};
// Store in cache
const cacheKey = `geohash_${geohashData.geohash}`;
const existingData = cache.get(cacheKey) || [];
existingData.push(geohashData);
// Keep only last 10 messages per geohash
if (existingData.length > 10) {
existingData.splice(0, existingData.length - 10);
}
cache.set(cacheKey, existingData);
// Broadcast to connected websocket clients
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
type: 'new_activity',
data: geohashData
}));
}
});
}
}
}
}
// API endpoints
app.get('/api/activity', (req, res) => {
const allData = cache.keys()
.filter(key => key.startsWith('geohash_'))
.map(key => {
const data = cache.get(key);
return data.map(item => ({
...item,
channel: `bc_${item.geohash}`,
coolrLinks: RELAYS.map(relay => ({
relay,
url: `https://www.coolr.chat/?relay=${encodeURIComponent(relay)}&channel=bc_${item.geohash}`
}))
}));
})
.flat();
res.json(allData);
});
app.get('/api/heatmap-data', (req, res) => {
const heatmapData = [];
const keys = cache.keys().filter(key => key.startsWith('geohash_'));
keys.forEach(key => {
const data = cache.get(key);
if (data && data.length > 0) {
const latest = data[data.length - 1];
const intensity = Math.min(data.length * 10, 100); // Scale intensity
// Generate coolr.chat URLs for each relay
const coolrLinks = RELAYS.map(relay => ({
relay,
url: `https://www.coolr.chat/?relay=${encodeURIComponent(relay)}&channel=bc_${latest.geohash}`
}));
heatmapData.push({
geohash: latest.geohash,
intensity: intensity,
count: data.length,
lastActivity: latest.timestamp,
coolrLinks,
channel: `bc_${latest.geohash}`
});
}
});
res.json(heatmapData);
});
// Get relay configuration
app.get('/api/relays', (req, res) => {
const relayData = RELAYS.map(relay => {
const relayName = relay.replace('wss://', '').replace('ws://', '');
const connection = relayConnections.get(relay);
return {
url: relay,
name: relayName,
coolrUrl: `https://www.coolr.chat/?relay=${encodeURIComponent(relay)}`,
status: connection && connection.readyState === 1 ? 'connected' : 'disconnected',
readyState: connection ? connection.readyState : null
};
});
res.json(relayData);
});
// Test coolr.chat URL format for a specific relay and channel
app.get('/api/coolr-test/:relay/:channel', (req, res) => {
try {
const { relay, channel } = req.params;
const relayUrl = decodeURIComponent(relay);
// Validate relay URL format
if (!relayUrl.startsWith('wss://') && !relayUrl.startsWith('ws://')) {
return res.status(400).json({ error: 'Invalid relay URL format' });
}
const coolrUrl = `https://www.coolr.chat/?relay=${encodeURIComponent(relayUrl)}&channel=${channel}`;
res.json({
relay: relayUrl,
channel,
coolrUrl,
encodedRelay: encodeURIComponent(relayUrl),
isConnected: relayConnections.has(relayUrl)
});
} catch (error) {
res.status(500).json({ error: 'Failed to generate coolr.chat URL' });
}
});
// Key management endpoints
app.post('/api/keys/generate', (req, res) => {
try {
const privateKey = generatePrivateKey();
const publicKey = getPublicKey(privateKey);
const nsec = nip19.nsecEncode(privateKey);
const npub = nip19.npubEncode(publicKey);
res.json({
privateKey: Buffer.from(privateKey).toString('hex'),
publicKey,
nsec,
npub
});
} catch (error) {
console.error('Error generating keys:', error);
res.status(500).json({ error: 'Failed to generate keys', details: error.message });
}
});
app.post('/api/keys/decode', (req, res) => {
try {
const { key } = req.body;
if (!key) {
return res.status(400).json({ error: 'Key is required' });
}
const decoded = nip19.decode(key);
if (decoded.type === 'npub') {
res.json({
type: 'npub',
publicKey: decoded.data,
npub: key
});
} else if (decoded.type === 'nsec') {
const publicKey = getPublicKey(decoded.data);
res.json({
type: 'nsec',
privateKey: Buffer.from(decoded.data).toString('hex'),
publicKey,
nsec: key,
npub: nip19.npubEncode(publicKey)
});
} else if (decoded.type === 'nprofile') {
res.json({
type: 'nprofile',
publicKey: decoded.data.pubkey,
relays: decoded.data.relays,
npub: nip19.npubEncode(decoded.data.pubkey)
});
} else {
res.json({
type: decoded.type,
data: decoded.data
});
}
} catch (error) {
res.status(400).json({ error: 'Invalid key format' });
}
});
// Lightning address validation endpoint
app.post('/api/lightning/validate', async (req, res) => {
try {
const { address } = req.body;
if (!address) {
return res.status(400).json({ error: 'Lightning address is required' });
}
// Validate lightning address format (user@domain.com)
const emailRegex = /^[a-z0-9\-_.+]+@[a-z0-9\-_.]+\.[a-z]{2,}$/i;
if (!emailRegex.test(address)) {
return res.status(400).json({ error: 'Invalid lightning address format' });
}
const [username, domain] = address.split('@');
const lnurlEndpoint = `https://${domain}/.well-known/lnurlp/${username}`;
try {
const response = await fetch(lnurlEndpoint);
const lnurlData = await response.json();
if (response.ok && lnurlData.callback) {
res.json({
valid: true,
address,
lnurlEndpoint,
callback: lnurlData.callback,
minSendable: lnurlData.minSendable,
maxSendable: lnurlData.maxSendable,
allowsNostr: lnurlData.allowsNostr || false,
nostrPubkey: lnurlData.nostrPubkey,
metadata: lnurlData.metadata
});
} else {
res.status(400).json({
valid: false,
error: 'Lightning address not found or invalid'
});
}
} catch (fetchError) {
res.status(400).json({
valid: false,
error: 'Failed to validate lightning address'
});
}
} catch (error) {
res.status(500).json({ error: 'Server error validating lightning address' });
}
});
// Create and publish geohash event endpoint
app.post('/api/events/publish', (req, res) => {
try {
const { privateKey, latitude, longitude, nickname, message, lightningAddress } = req.body;
if (!privateKey || !latitude || !longitude) {
return res.status(400).json({
error: 'privateKey, latitude, and longitude are required'
});
}
// Decode private key if it's in nsec format
let sk;
if (privateKey.startsWith('nsec')) {
const decoded = nip19.decode(privateKey);
if (decoded.type !== 'nsec') {
return res.status(400).json({ error: 'Invalid nsec format' });
}
sk = decoded.data;
} else {
// Assume hex format
sk = new Uint8Array(Buffer.from(privateKey, 'hex'));
}
const publicKey = getPublicKey(sk);
const geohash = ngeohash.encode(latitude, longitude, 8);
const tags = [
['g', geohash],
['n', nickname || 'Anonymous']
];
// Add lightning address tag if provided
if (lightningAddress) {
tags.push(['lud16', lightningAddress]);
}
const event = finishEvent({
kind: 20000,
created_at: Math.floor(Date.now() / 1000),
tags,
content: message || ''
}, sk);
// Store locally
const geohashData = {
geohash,
nickname: nickname || 'Anonymous',
message: message || '',
timestamp: event.created_at,
relay: 'local',
lightningAddress,
npub: nip19.npubEncode(publicKey)
};
const key = `geohash_${geohash}`;
let existing = cache.get(key) || [];
existing.push(geohashData);
cache.set(key, existing);
// Broadcast to connected WebSocket clients
wss.clients.forEach(client => {
if (client.readyState === client.OPEN) {
client.send(JSON.stringify({
type: 'new_activity',
data: geohashData
}));
}
});
res.json({
success: true,
event,
npub: nip19.npubEncode(publicKey),
geohash,
eventId: event.id
});
} catch (error) {
console.error('Error publishing event:', error);
res.status(500).json({ error: 'Failed to publish event' });
}
});
// Lightning Zap functionality
app.post('/api/zaps/create-request', (req, res) => {
try {
const {
senderPrivateKey,
recipientPubkey,
amount,
message,
eventId,
relays
} = req.body;
if (!senderPrivateKey || !recipientPubkey || !amount) {
return res.status(400).json({
error: 'senderPrivateKey, recipientPubkey, and amount are required'
});
}
// Decode sender private key if needed
let sk;
if (senderPrivateKey.startsWith('nsec')) {
const decoded = nip19.decode(senderPrivateKey);
if (decoded.type !== 'nsec') {
return res.status(400).json({ error: 'Invalid nsec format' });
}
sk = decoded.data;
} else {
sk = new Uint8Array(Buffer.from(senderPrivateKey, 'hex'));
}
const senderPubkey = getPublicKey(sk);
const zapRelays = relays || ['wss://relay.damus.io', 'wss://nos.lol'];
const tags = [
['relays', ...zapRelays],
['amount', amount.toString()],
['p', recipientPubkey]
];
// Add event tag if zapping a specific event
if (eventId) {
tags.push(['e', eventId]);
}
const zapRequest = finishEvent({
kind: 9734,
created_at: Math.floor(Date.now() / 1000),
tags,
content: message || ''
}, sk);
res.json({
success: true,
zapRequest,
senderNpub: nip19.npubEncode(senderPubkey),
recipientNpub: nip19.npubEncode(recipientPubkey)
});
} catch (error) {
console.error('Error creating zap request:', error);
res.status(500).json({ error: 'Failed to create zap request' });
}
});
// Get user profile with Lightning info
app.get('/api/users/:npub', async (req, res) => {
try {
const { npub } = req.params;
if (!npub.startsWith('npub')) {
return res.status(400).json({ error: 'Invalid npub format' });
}
const decoded = nip19.decode(npub);
if (decoded.type !== 'npub') {
return res.status(400).json({ error: 'Invalid npub' });
}
const publicKey = decoded.data;
// Get user's geohash activities
const userActivities = [];
const keys = cache.keys().filter(key => key.startsWith('geohash_'));
keys.forEach(key => {
const data = cache.get(key);
if (data && Array.isArray(data)) {
const userEvents = data.filter(event => {
return event.npub === npub ||
(event.publicKey && event.publicKey === publicKey);
});
userActivities.push(...userEvents);
}
});
res.json({
npub,
publicKey,
activities: userActivities.slice(0, 50), // Limit to recent 50
totalActivities: userActivities.length,
lastActivity: userActivities.length > 0 ?
Math.max(...userActivities.map(a => a.timestamp)) : null
});
} catch (error) {
console.error('Error fetching user profile:', error);
res.status(500).json({ error: 'Failed to fetch user profile' });
}
});
// WebSocket connection handling
wss.on('connection', (ws) => {
console.log('Client connected to heatmap');
ws.on('message', (message) => {
try {
const data = JSON.parse(message.toString());
// Handle client messages if needed
} catch (error) {
console.error('Error parsing WebSocket message:', error);
}
});
ws.on('close', () => {
console.log('Client disconnected from heatmap');
});
});
// Start server
const PORT = process.env.PORT || 3001;
server.listen(PORT, () => {
console.log(`Heatmap server running on port ${PORT}`);
connectToRelays();
});
// Graceful shutdown
process.on('SIGINT', () => {
console.log('Shutting down gracefully...');
relayConnections.forEach((ws, url) => {
ws.close();
});
server.close();
process.exit(0);
});