-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend.js
More file actions
303 lines (258 loc) · 13.5 KB
/
Copy pathbackend.js
File metadata and controls
303 lines (258 loc) · 13.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
'use strict';
// =============================================================================
// Runewager Endpoint — companion HTTP service on port 3001
//
// Responsibilities:
// - Autofix AI webhook receiver (POST /autofix/webhook)
// - GET /autofix/test — signature self-test
// - GET /health — basic liveness
// - GET /health/full — detailed diagnostic snapshot
// - Telegram admin broadcast helper (sendAdmin)
// - Structured request/event logging to logs/backend.log
// - Graceful SIGTERM/SIGINT shutdown
//
// This service does NOT run Telegram polling (index.js owns that).
// =============================================================================
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');
const fs = require('fs');
const https = require('https');
const os = require('os');
const path = require('path');
const { globalThrottle, stats: rlStats } = require('./rateLimiter');
const { getActivePromoFromDb, invalidateActivePromoCache, normalizePromoAudience } = require('./promo-message');
// ─── Config ──────────────────────────────────────────────────────────────────
const PORT = parseInt(process.env.ENDPOINT_PORT ?? '3001', 10);
const AUTOFIX_SECRET = process.env.AUTOFIX_SECRET ?? '';
const TG_TOKEN = process.env.TELEGRAM_BOT_TOKEN ?? process.env.BOT_TOKEN ?? '';
const ADMIN_CHAT_IDS = (process.env.ADMIN_IDS ?? '')
.split(',').map(s => s.trim()).filter(Boolean);
// ─── Structured Logging ──────────────────────────────────────────────────────
const LOG_DIR = path.join(__dirname, 'logs');
const LOG_FILE = path.join(LOG_DIR, 'backend.log');
const ERR_FILE = path.join(LOG_DIR, 'backend-error.log');
let _logStream = null;
let _errStream = null;
try {
if (!fs.existsSync(LOG_DIR)) fs.mkdirSync(LOG_DIR, { recursive: true });
_logStream = fs.createWriteStream(LOG_FILE, { flags: 'a' });
_errStream = fs.createWriteStream(ERR_FILE, { flags: 'a' });
_logStream.on('error', (e) => { _logStream = null; console.error(`[backend] log stream error: ${e.message}`); });
_errStream.on('error', (e) => { _errStream = null; console.error(`[backend] err stream error: ${e.message}`); });
} catch (e) {
console.error(`[backend] Cannot open log files in ${LOG_DIR}: ${e.message}`);
}
const logger = {
_entry(level, eventType, msg, extra) {
return { ts: new Date().toISOString(), level, eventType, msg, ...extra };
},
_write(streams, obj) {
const line = JSON.stringify(obj) + '\n';
const writable = streams.filter((s) => s && !s.destroyed && s.writable);
if (writable.length > 0) {
for (const s of writable) {
try { s.write(line); } catch (e) { console.error(`[backend] stream write error: ${e.message}`); }
}
} else {
console.log(line.trimEnd());
}
},
info(eventType, msg, extra = {}) {
this._write([_logStream], this._entry('info', eventType, msg, extra));
},
error(eventType, msg, extra = {}) {
this._write([_logStream, _errStream], this._entry('error', eventType, msg, extra));
},
event(eventType, msg, extra = {}) {
this._write([_logStream], this._entry('event', eventType, msg, extra));
},
};
// ─── Telegram Admin Broadcast ─────────────────────────────────────────────────
/**
* Send a plain-text message to every chat ID listed in ADMIN_CHAT_IDS.
* Failures per-chat are swallowed so one bad ID never blocks the others.
* @param {string} msg
* @returns {Promise<void>}
*/
function sendAdmin(msg) {
if (!TG_TOKEN || ADMIN_CHAT_IDS.length === 0) return Promise.resolve();
const sendOne = (chatId) =>
globalThrottle(() => new Promise((resolve) => {
const body = JSON.stringify({ chat_id: chatId, text: String(msg) });
const req = https.request({
hostname: 'api.telegram.org',
path: `/bot${TG_TOKEN}/sendMessage`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body),
},
}, () => resolve());
req.setTimeout(10_000, () => { req.destroy(); resolve(); });
req.on('error', () => resolve());
req.write(body);
req.end();
}));
return Promise.all(ADMIN_CHAT_IDS.map(sendOne)).then(() => {}).catch((err) => {
console.error('[sendAdmin] broadcast error:', err && err.message);
});
}
// ─── HMAC Signature Verification ─────────────────────────────────────────────
/**
* Verify an HMAC-SHA256 signature against the raw request body.
* Accepts both bare hex and "sha256=<hex>" prefixed forms.
* Uses timing-safe comparison to prevent timing attacks.
* @param {Buffer} rawBody
* @param {string} signature
* @returns {boolean}
*/
function verifySignature(rawBody, signature) {
if (!AUTOFIX_SECRET) return false;
const expected = crypto
.createHmac('sha256', AUTOFIX_SECRET)
.update(rawBody)
.digest('hex');
const sig = (signature ?? '').replace(/^sha256=/, '');
if (sig.length !== expected.length) return false;
try {
return crypto.timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(sig, 'hex'));
} catch {
return false;
}
}
// ─── Express App ──────────────────────────────────────────────────────────────
const app = express();
// requestId middleware — every request gets a short unique ID for log correlation
app.use((req, _res, next) => {
req.id = crypto.randomBytes(5).toString('hex');
next();
});
// Capture raw body for HMAC verification on /autofix routes.
// Must run before express.json() so rawBody is available to the webhook handler.
app.use('/autofix', (req, res, next) => {
express.raw({ type: '*/*', limit: '1mb' })(req, res, (err) => {
if (err) return next(err);
if (Buffer.isBuffer(req.body)) req.rawBody = req.body;
next();
});
});
app.use(express.json({ limit: '2mb' }));
// ─── GET /health ──────────────────────────────────────────────────────────────
app.get('/health', (req, res) => {
logger.info('http.health', 'Health check', { requestId: req.id });
res.json({
ok: true,
service: 'runewager-endpoint',
uptimeSec: Math.floor(process.uptime()),
});
});
// ─── GET /health/full ─────────────────────────────────────────────────────────
app.get('/health/full', (req, res) => {
const mem = process.memoryUsage();
const [load1] = os.loadavg();
logger.info('http.health.full', 'Full health check', { requestId: req.id });
res.json({
ok: true,
service: 'runewager-endpoint',
uptimeSec: Math.floor(process.uptime()),
nodeVersion: process.version,
memoryMB: {
rss: +(mem.rss / 1_048_576).toFixed(1),
heapUsed: +(mem.heapUsed / 1_048_576).toFixed(1),
},
cpuLoad: +load1.toFixed(2),
activeTelegramPolling: false,
autofixWebhookRegistered: Boolean(AUTOFIX_SECRET),
adminChatIdsConfigured: ADMIN_CHAT_IDS.length,
rateLimiter: rlStats(),
});
});
// ─── Promo routes ─────────────────────────────────────────────────────────────
app.get('/promo/active', (req, res) => {
const audience = normalizePromoAudience(req.query.audience || 'new_user');
const promo = getActivePromoFromDb(audience, { logger });
logger.info('http.promo.active', 'Active promo lookup', { requestId: req.id, audience, promoId: promo && promo.promo_id });
res.json({
ok: true,
audience,
cacheKey: audience === 'existing_user' ? 'active_existing_user_promo' : 'active_new_user_promo',
promo: promo ? {
promo_id: promo.promo_id,
code: promo.code,
amount: promo.amount,
name: promo.name,
description: promo.description,
casino_base_url: promo.casino_base_url,
} : null,
});
});
app.post('/promo/cache/invalidate', (req, res) => {
const audience = req.body && req.body.audience ? normalizePromoAudience(req.body.audience) : null;
invalidateActivePromoCache(audience, { logger, reason: 'backend_route' });
res.json({ ok: true, audience: audience || 'all' });
});
// ─── GET /autofix/test ────────────────────────────────────────────────────────
app.get('/autofix/test', (req, res) => {
const timestamp = new Date().toISOString();
const payload = JSON.stringify({ event: 'test', ts: timestamp, requestId: req.id });
const sig = AUTOFIX_SECRET
? 'sha256=' + crypto.createHmac('sha256', AUTOFIX_SECRET).update(payload).digest('hex')
: '';
const signatureValid = AUTOFIX_SECRET ? verifySignature(Buffer.from(payload), sig) : false;
logger.event('autofix.test', 'Signature self-test', { requestId: req.id, signatureValid });
res.json({ ok: true, signatureValid, timestamp, requestId: req.id, secretConfigured: Boolean(AUTOFIX_SECRET) });
});
// ─── POST /autofix/webhook ────────────────────────────────────────────────────
app.post('/autofix/webhook', async (req, res) => {
const requestId = req.id;
try {
const sig = req.headers['x-autofix-signature'] ?? req.headers['x-hub-signature-256'] ?? '';
const rawBody = req.rawBody;
if (!rawBody || !Buffer.isBuffer(rawBody)) {
logger.error('autofix.webhook', 'Missing rawBody — raw-body middleware did not run', { requestId });
return res.status(400).json({ ok: false, error: 'Bad request: missing body', requestId });
}
if (!AUTOFIX_SECRET || !verifySignature(rawBody, sig)) {
const reason = !AUTOFIX_SECRET ? 'AUTOFIX_SECRET not configured' : 'Signature mismatch';
logger.error('autofix.webhook', `${reason} — request rejected`, { requestId });
return res.status(401).json({ ok: false, error: 'Invalid signature', requestId });
}
let payload;
try { payload = JSON.parse(rawBody.toString('utf8')); } catch { payload = {}; }
const eventName = payload.event ?? payload.action ?? 'unknown';
logger.event('autofix.webhook', 'Autofix event received', { requestId, event: eventName });
await sendAdmin(`🤖 Autofix [${requestId}]: ${eventName}`);
res.json({ ok: true, requestId, received: true });
} catch (err) {
const summary = err?.message ?? String(err);
logger.error('autofix.webhook', 'Handler error', { requestId, error: summary });
await sendAdmin(`⚠️ Autofix webhook error [${requestId}]: ${summary}`).catch(() => {});
res.status(500).json({ ok: false, error: 'Internal server error', requestId });
}
});
// ─── Start ────────────────────────────────────────────────────────────────────
const server = app.listen(PORT, '127.0.0.1', () => {
logger.info('server.start', 'runewager-endpoint listening', { port: PORT });
});
// ─── Graceful Shutdown ────────────────────────────────────────────────────────
function shutdown(signal) {
logger.info('server.shutdown', `${signal} received — shutting down gracefully`);
server.close(() => {
logger.info('server.shutdown', 'HTTP server closed — exiting cleanly');
process.exit(0);
});
setTimeout(() => {
logger.error('server.shutdown', 'Graceful shutdown timeout — forcing exit');
process.exit(1);
}, 10_000).unref();
}
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('uncaughtException', err => {
logger.error('process.uncaughtException', err.message, { stack: err.stack });
sendAdmin(`💀 runewager-endpoint crash: ${err.message}`).finally(() => process.exit(1));
});
process.on('unhandledRejection', reason => {
logger.error('process.unhandledRejection', String(reason));
});