Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
652 lines (561 loc) · 20.5 KB
/
Copy pathserver.js
File metadata and controls
652 lines (561 loc) · 20.5 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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
import express from 'express';
import cors from 'cors';
import {
upsertUser,
addWallet,
removeWallet,
listWallets,
setUserFilter,
getUserFilter,
getAlertsForWallet,
appendAlertForWallet,
upsertDeviceRegistration,
getDeviceRegistration,
setDeviceFilter,
getDeviceFilter,
listExpoPushTokensByWallet,
setAlertSettings,
getAlertSettings,
} from './storage.js';
import { appendAlert, getAlerts } from './alerts.js';
import { startPoller } from './poller.js';
const app = express();
app.set('trust proxy', Number(process.env.TRUST_PROXY ?? 1));
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Referrer-Policy', 'no-referrer');
res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
next();
});
app.use(express.json({ limit: '1mb' }));
const corsOrigins = String(process.env.CORS_ORIGIN || '')
.split(',')
.map((s) => s.trim())
.filter(Boolean);
app.use(
cors({
origin: (origin, cb) => {
if (!origin || corsOrigins.length === 0) return cb(null, true);
if (corsOrigins.includes(origin)) return cb(null, true);
return cb(new Error('CORS blocked'), false);
},
credentials: false,
methods: ['GET', 'POST', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'X-Notify-Token', 'X-Telegram-Bot-Api-Secret-Token'],
})
);
app.options('*', cors());
app.use(rateLimit);
const BOT_TOKEN = process.env.BOT_TOKEN;
const HELIUS_API_KEY = process.env.HELIUS_API_KEY;
const RPC_URL = process.env.RPC_URL || (HELIUS_API_KEY ? `https://mainnet.helius-rpc.com/?api-key=${HELIUS_API_KEY}` : undefined);
const POLL_INTERVAL_MS = Math.max(1000, Number(process.env.POLL_INTERVAL_MS || 3000));
const PORT = Number(process.env.PORT || 3000);
const TOKEN_MINT = process.env.TOKEN_MINT || '';
const TG_API = BOT_TOKEN ? `https://api.telegram.org/bot${BOT_TOKEN}` : null;
const serverState = {
startedAt: Date.now(),
pollerStarted: false,
version: process.env.RENDER_GIT_COMMIT || process.env.VERCEL_GIT_COMMIT_SHA || 'local',
};
const WALLET_REGEX = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
const RATE_LIMIT_WINDOW_MS = Number(process.env.RATE_LIMIT_WINDOW_MS || 60_000);
const RATE_LIMIT_MAX = Number(process.env.RATE_LIMIT_MAX || 120);
const MAX_NOTIFY_CHARS = Number(process.env.MAX_NOTIFY_CHARS || 800);
const NOTIFY_TOKEN = process.env.NOTIFY_TOKEN || '';
const TELEGRAM_WEBHOOK_SECRET = process.env.TELEGRAM_WEBHOOK_SECRET || '';
const rateLimitState = new Map();
function rateLimit(req, res, next) {
const key = String(req.ip || 'unknown');
const now = Date.now();
const entry = rateLimitState.get(key) || { count: 0, resetAt: now + RATE_LIMIT_WINDOW_MS };
if (now > entry.resetAt) {
entry.count = 0;
entry.resetAt = now + RATE_LIMIT_WINDOW_MS;
}
entry.count += 1;
rateLimitState.set(key, entry);
if (entry.count > RATE_LIMIT_MAX) {
return res.status(429).json({ ok: false, error: 'rate limit' });
}
return next();
}
function normalizeChatId(obj) {
const raw = obj?.chatId ?? obj?.chat_id ?? obj?.chatID ?? obj?.cid;
const chatId = typeof raw === 'string' || typeof raw === 'number' ? String(raw).trim() : '';
if (!chatId || !/^[-]?\d+$/.test(chatId)) return null;
return chatId;
}
function normalizeWallet(value) {
const wallet = typeof value === 'string' ? value.trim() : '';
if (!wallet || !WALLET_REGEX.test(wallet)) return null;
return wallet;
}
function normalizeDeviceToken(value) {
const token = typeof value === 'string' ? value.trim() : '';
if (!token || token.length < 8) return null;
return token;
}
function authorizeNotify(req, res) {
if (!NOTIFY_TOKEN) return true;
const token = req.get('X-Notify-Token');
if (token && token === NOTIFY_TOKEN) return true;
res.status(401).json({ ok: false, error: 'unauthorized' });
return false;
}
function authorizeTelegram(req, res) {
if (!TELEGRAM_WEBHOOK_SECRET) return true;
const token = req.get('X-Telegram-Bot-Api-Secret-Token');
if (token && token === TELEGRAM_WEBHOOK_SECRET) return true;
res.status(401).json({ ok: false, error: 'unauthorized' });
return false;
}
function ok(res, payload = {}) {
return res.json({ ok: true, ...payload });
}
function badRequest(res, error) {
return res.status(400).json({ ok: false, error });
}
function serverError(res, error = 'server error') {
return res.status(500).json({ ok: false, error });
}
async function sendMessage(chatId, text, options = {}) {
if (!TG_API) return { ok: false, reason: 'missing BOT_TOKEN' };
const html = options?.html !== false;
const payload = {
chat_id: String(chatId),
text: String(text),
disable_web_page_preview: true,
};
if (html) payload.parse_mode = 'HTML';
const resp = await fetch(`${TG_API}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
const data = await resp.json().catch(() => null);
return { ok: !!(resp.ok && data?.ok), status: resp.status, data };
}
async function storeMobileAlert(chatId, text) {
// only used for mobile app alerts; Telegram can be disabled if not needed
await appendAlert(String(chatId), String(text));
}
async function sendExpoPush(expoPushToken, title, body) {
try {
const resp = await fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
to: expoPushToken,
sound: 'default',
title,
body,
priority: 'high',
}),
});
const data = await resp.json().catch(() => null);
return { ok: !!resp.ok, data };
} catch (err) {
return { ok: false, error: String(err?.message || err) };
}
}
async function fetchTokenMetadata(mint) {
if (!HELIUS_API_KEY) return null;
try {
const resp = await fetch(`https://api.helius.xyz/v0/token-metadata?api-key=${HELIUS_API_KEY}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mintAccounts: [mint] }),
});
const data = await resp.json().catch(() => null);
const item = Array.isArray(data) ? data[0] : null;
const onChain = item?.onChainMetadata?.metadata || {};
const offChain = item?.offChainMetadata || {};
return {
name: onChain?.name || offChain?.name || null,
symbol: onChain?.symbol || offChain?.symbol || null,
image: offChain?.image || offChain?.imageUrl || null,
description: offChain?.description || null,
};
} catch {
return null;
}
}
async function fetchDexScreenerToken(mint) {
try {
const resp = await fetch(`https://api.dexscreener.com/latest/dex/tokens/${mint}`);
const data = await resp.json().catch(() => null);
const pairs = Array.isArray(data?.pairs) ? data.pairs : [];
if (!pairs.length) return null;
const best = pairs
.filter((p) => p?.chainId === 'solana')
.sort((a, b) => Number(b?.liquidity?.usd || 0) - Number(a?.liquidity?.usd || 0))[0];
if (!best) return null;
return {
pairAddress: best?.pairAddress || null,
dexId: best?.dexId || null,
priceUsd: best?.priceUsd || null,
volume24h: best?.volume?.h24 || null,
url: best?.url || null,
};
} catch {
return null;
}
}
app.get('/', (_req, res) => res.send('OK'));
app.get('/health', (_req, res) => {
return ok(res, {
service: 'sanamesolbot-backend',
uptimeSec: Math.floor((Date.now() - serverState.startedAt) / 1000),
pollerStarted: serverState.pollerStarted,
env: {
bot: !!BOT_TOKEN,
helius: !!HELIUS_API_KEY,
rpc: !!RPC_URL,
},
version: serverState.version,
pollIntervalMs: POLL_INTERVAL_MS,
});
});
app.get('/api/token-info', async (req, res) => {
try {
const mint = normalizeWallet(req.query?.mint) || normalizeWallet(TOKEN_MINT);
if (!mint) return badRequest(res, 'invalid mint');
const [meta, dex] = await Promise.all([
fetchTokenMetadata(mint),
fetchDexScreenerToken(mint),
]);
const buyUrl = dex?.url || (mint ? `https://jup.ag/swap/SOL-${mint}` : null);
return ok(res, {
mint,
name: meta?.name || null,
symbol: meta?.symbol || null,
image: meta?.image || null,
description: meta?.description || null,
priceUsd: dex?.priceUsd || null,
volume24h: dex?.volume24h || null,
dexUrl: dex?.url || null,
dexId: dex?.dexId || null,
buyUrl,
});
} catch (err) {
console.error('token-info error:', err);
return serverError(res);
}
});
app.post('/api/register', async (req, res) => {
try {
const chatId = normalizeChatId(req.body);
if (!chatId) return badRequest(res, 'invalid chatId');
await upsertUser(chatId);
return ok(res, { chatId });
} catch (err) {
console.error('register error:', err);
return serverError(res);
}
});
app.post('/api/activate', async (req, res) => {
try {
const chatId = normalizeChatId(req.body);
if (!chatId) return badRequest(res, 'invalid chatId');
await upsertUser(chatId);
const tg = await sendMessage(chatId, '✅ Activation completed. You will receive alerts here.');
return ok(res, { chatId, telegramOk: tg.ok });
} catch (err) {
console.error('activate error:', err);
return serverError(res);
}
});
app.post('/api/add-wallet', async (req, res) => {
try {
const chatId = normalizeChatId(req.body);
const wallet = normalizeWallet(req.body?.wallet);
if (!chatId) return badRequest(res, 'invalid chatId');
if (!wallet) return badRequest(res, 'invalid wallet');
const user = await addWallet(chatId, wallet);
return ok(res, { wallets: user.wallets || [] });
} catch (err) {
console.error('add-wallet error:', err);
return serverError(res);
}
});
app.post('/api/remove-wallet', async (req, res) => {
try {
const chatId = normalizeChatId(req.body);
const wallet = normalizeWallet(req.body?.wallet);
if (!chatId) return badRequest(res, 'invalid chatId');
if (!wallet) return badRequest(res, 'invalid wallet');
const user = await removeWallet(chatId, wallet);
return ok(res, { wallets: user?.wallets || [] });
} catch (err) {
console.error('remove-wallet error:', err);
return serverError(res);
}
});
app.get('/api/list-wallets', async (req, res) => {
try {
const chatId = normalizeChatId(req.query);
if (!chatId) return badRequest(res, 'invalid chatId');
const wallets = await listWallets(chatId);
return ok(res, { wallets });
} catch (err) {
console.error('list-wallets error:', err);
return serverError(res);
}
});
app.post('/api/set-filter', async (req, res) => {
try {
const chatId = normalizeChatId(req.body);
if (!chatId) return badRequest(res, 'invalid chatId');
const filter = await setUserFilter(chatId, req.body?.filter || {});
return ok(res, { chatId, filter });
} catch (err) {
console.error('set-filter error:', err);
return serverError(res);
}
});
app.get('/api/get-filter', async (req, res) => {
try {
const chatId = normalizeChatId(req.query);
if (!chatId) return badRequest(res, 'invalid chatId');
const filter = await getUserFilter(chatId);
return ok(res, { chatId, filter });
} catch (err) {
console.error('get-filter error:', err);
return serverError(res);
}
});
app.post('/api/set-alert-settings', async (req, res) => {
try {
const chatId = normalizeChatId(req.body);
if (!chatId) return badRequest(res, 'invalid chatId');
const settings = await setAlertSettings(chatId, req.body?.settings || {});
return ok(res, { chatId, settings });
} catch (err) {
console.error('set-alert-settings error:', err);
return serverError(res);
}
});
app.get('/api/get-alert-settings', async (req, res) => {
try {
const chatId = normalizeChatId(req.query);
if (!chatId) return badRequest(res, 'invalid chatId');
const settings = await getAlertSettings(chatId);
return ok(res, { chatId, settings });
} catch (err) {
console.error('get-alert-settings error:', err);
return serverError(res);
}
});
app.post('/notify', async (req, res) => {
try {
if (!authorizeNotify(req, res)) return;
const chatId = normalizeChatId(req.body);
const text = typeof req.body?.text === 'string' ? req.body.text.trim() : '';
if (!chatId) return badRequest(res, 'invalid chatId');
if (!text) return badRequest(res, 'text missing');
if (text.length > MAX_NOTIFY_CHARS) return badRequest(res, 'text too long');
// Store alert for mobile app consumption
await storeMobileAlert(chatId, text);
const settings = await getAlertSettings(chatId);
if (settings?.notifyTelegram) {
const tg = await sendMessage(chatId, text, { html: false });
return ok(res, { stored: true, telegramOk: tg.ok });
}
return ok(res, { stored: true });
} catch (err) {
console.error('notify error:', err);
return serverError(res);
}
});
app.get('/api/alerts', async (req, res) => {
try {
const chatId = normalizeChatId(req.query);
if (!chatId) return badRequest(res, 'invalid chatId');
const alerts = await getAlerts(chatId);
return ok(res, { chatId, alerts });
} catch (err) {
console.error('get-alerts error:', err);
return serverError(res);
}
});
app.get('/api/alerts-by-wallet', async (req, res) => {
try {
const wallet = normalizeWallet(req.query?.wallet);
if (!wallet) return badRequest(res, 'invalid wallet');
const alerts = await getAlertsForWallet(wallet);
return ok(res, { wallet, alerts });
} catch (err) {
console.error('get-alerts-by-wallet error:', err);
return serverError(res);
}
});
// Alias for mobile app compatibility
app.get('/api/alerts/by-wallet', async (req, res) => {
try {
const wallet = normalizeWallet(req.query?.wallet);
if (!wallet) return badRequest(res, 'invalid wallet');
const alerts = await getAlertsForWallet(wallet);
return ok(res, { wallet, alerts });
} catch (err) {
console.error('get-alerts-by-wallet(alias) error:', err);
return serverError(res);
}
});
app.post('/api/device/register', async (req, res) => {
try {
const deviceToken = normalizeDeviceToken(req.body?.deviceToken);
const walletAddress = normalizeWallet(req.body?.walletAddress);
const platform = typeof req.body?.platform === 'string' ? req.body.platform : 'unknown';
const expoPushToken = typeof req.body?.expoPushToken === 'string' ? req.body.expoPushToken.trim() : '';
if (!deviceToken) return badRequest(res, 'invalid deviceToken');
if (!walletAddress) return badRequest(res, 'invalid walletAddress');
const device = await upsertDeviceRegistration(deviceToken, walletAddress, platform, expoPushToken);
return ok(res, { device });
} catch (err) {
console.error('device-register error:', err);
return serverError(res);
}
});
app.get('/api/device/alerts', async (req, res) => {
try {
const deviceToken = normalizeDeviceToken(req.query?.deviceToken);
if (!deviceToken) return badRequest(res, 'invalid deviceToken');
const reg = await getDeviceRegistration(deviceToken);
if (!reg?.walletAddress) return ok(res, { deviceToken, alerts: [] });
const alerts = await getAlertsForWallet(reg.walletAddress);
return ok(res, { deviceToken, wallet: reg.walletAddress, alerts });
} catch (err) {
console.error('device-alerts error:', err);
return serverError(res);
}
});
app.get('/api/device/filter', async (req, res) => {
try {
const deviceToken = normalizeDeviceToken(req.query?.deviceToken);
if (!deviceToken) return badRequest(res, 'invalid deviceToken');
const filter = await getDeviceFilter(deviceToken);
return ok(res, { deviceToken, filter });
} catch (err) {
console.error('device-filter get error:', err);
return serverError(res);
}
});
app.post('/api/device/filter', async (req, res) => {
try {
const deviceToken = normalizeDeviceToken(req.body?.deviceToken);
if (!deviceToken) return badRequest(res, 'invalid deviceToken');
const filter = await setDeviceFilter(deviceToken, req.body?.filter || {});
return ok(res, { deviceToken, filter });
} catch (err) {
console.error('device-filter set error:', err);
return serverError(res);
}
});
app.get('/api/device/registration', async (req, res) => {
try {
const deviceToken = normalizeDeviceToken(req.query?.deviceToken);
if (!deviceToken) return badRequest(res, 'invalid deviceToken');
const reg = await getDeviceRegistration(deviceToken);
return ok(res, { deviceToken, registration: reg || null, hasExpoPushToken: !!reg?.expoPushToken });
} catch (err) {
console.error('device-registration get error:', err);
return serverError(res);
}
});
app.post('/api/device/test-push', async (req, res) => {
try {
const deviceToken = normalizeDeviceToken(req.body?.deviceToken);
const message = typeof req.body?.message === 'string' && req.body.message.trim() ? req.body.message.trim() : 'WatchSol test push';
if (!deviceToken) return badRequest(res, 'invalid deviceToken');
if (message.length > MAX_NOTIFY_CHARS) return badRequest(res, 'message too long');
const reg = await getDeviceRegistration(deviceToken);
if (!reg?.expoPushToken) return badRequest(res, 'missing expoPushToken for this device');
const result = await sendExpoPush(reg.expoPushToken, 'WatchSol Test', message);
return ok(res, { deviceToken, expoPushToken: reg.expoPushToken, result });
} catch (err) {
console.error('device-test-push error:', err);
return serverError(res);
}
});
app.post('/telegram', async (req, res) => {
try {
if (!authorizeTelegram(req, res)) return;
const msg = req.body?.message?.text;
const chatId = req.body?.message?.chat?.id;
if (!chatId) return res.sendStatus(200);
const cid = String(chatId);
await upsertUser(cid);
if (typeof msg !== 'string') return res.sendStatus(200);
if (msg.startsWith('/start')) {
await sendMessage(cid, `✅ Bot connected.\n\nYour <b>chat_id</b> is:\n<b>${cid}</b>\n\nCommands:\n/add WALLET\n/remove WALLET\n/list\n/test`);
return res.sendStatus(200);
}
if (msg.startsWith('/add ')) {
const wallet = normalizeWallet(msg.replace('/add', '').trim());
if (!wallet) await sendMessage(cid, '❌ Usage: /add WALLET');
else {
const u = await addWallet(cid, wallet);
await sendMessage(cid, `✅ Added.\nNow tracking:\n${u.wallets.map((w) => `• <code>${w}</code>`).join('\n')}`);
}
return res.sendStatus(200);
}
if (msg.startsWith('/remove ')) {
const wallet = normalizeWallet(msg.replace('/remove', '').trim());
if (!wallet) await sendMessage(cid, '❌ Usage: /remove WALLET');
else {
const u = await removeWallet(cid, wallet);
await sendMessage(cid, `✅ Removed.\nNow tracking:\n${(u?.wallets || []).map((w) => `• <code>${w}</code>`).join('\n') || '(none)'}`);
}
return res.sendStatus(200);
}
if (msg === '/list') {
const wallets = await listWallets(cid);
await sendMessage(cid, wallets.length ? `📌 Tracked wallets:\n${wallets.map((w) => `• <code>${w}</code>`).join('\n')}` : '📭 No wallets tracked. Use /add WALLET');
return res.sendStatus(200);
}
if (msg === '/test') {
await sendMessage(cid, '✅ TEST OK — bot is working.');
return res.sendStatus(200);
}
return res.sendStatus(200);
} catch (err) {
console.error('telegram webhook error:', err);
return res.sendStatus(200);
}
});
const server = app.listen(PORT, () => {
console.log('Server listening on port', PORT);
if (BOT_TOKEN && HELIUS_API_KEY && RPC_URL) {
startPoller({
pollIntervalMs: POLL_INTERVAL_MS,
rpcUrl: RPC_URL,
heliusApiKey: HELIUS_API_KEY,
onAlert: async (chatId, msg, wallet) => {
// Salva gli alert indicizzati per wallet per la mobile app
if (!wallet) {
console.warn('onAlert: missing wallet, skipping appendAlertForWallet');
return;
}
await appendAlertForWallet(wallet, msg, chatId);
const pushTokens = await listExpoPushTokensByWallet(wallet);
for (const token of pushTokens) {
const r = await sendExpoPush(token, 'WatchSol Alert', msg);
if (!r.ok) console.warn('expo push failed', token, r?.data || r?.error);
}
},
});
serverState.pollerStarted = true;
console.log('Poller started:', POLL_INTERVAL_MS, 'ms');
} else {
console.log('Poller not started: missing env vars');
}
});
server.on('error', (err) => {
console.error('Server listen error:', err);
process.exit(1);
});