-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
439 lines (368 loc) · 14.1 KB
/
Copy pathserver.js
File metadata and controls
439 lines (368 loc) · 14.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
const express = require('express');
const path = require('path');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const cookieParser = require('cookie-parser');
const cors = require('cors');
require('dotenv').config();
// Import logger and Sentry
const logger = require('./src/utils/logger');
const { initSentry, getRequestHandler, getTracingHandler, getErrorHandler, captureException } = require('./src/utils/sentry');
// Import database (initializes tables)
require('./src/config/database');
// Import i18n
const i18n = require('./src/middleware/i18n');
// Import routes
const authRoutes = require('./src/routes/authRoutes');
const earningsRoutes = require('./src/routes/earningsRoutes');
const farmlabsRoutes = require('./src/routes/farmlabsRoutes');
const accountsRoutes = require('./src/routes/accountsRoutes');
const tasksRoutes = require('./src/routes/tasks');
const proxiesRoutes = require('./src/routes/proxiesRoutes');
const viewRoutes = require('./src/routes/viewRoutes');
const adminRoutes = require('./src/routes/adminRoutes');
// Import task queue service
const taskQueueService = require('./src/services/taskQueueService');
// Import task executor worker
const taskExecutor = require('./src/workers/taskExecutor');
const app = express();
const PORT = process.env.PORT || 5050;
// ==================== SENTRY INITIALIZATION ====================
// Initialize Sentry (must be before other middleware)
initSentry(app);
// Sentry request handler (must be first middleware)
app.use(getRequestHandler());
// Sentry tracing handler
app.use(getTracingHandler());
// ==================== SECURITY MIDDLEWARE ====================
// Helmet for security headers
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com", "https://unpkg.com"],
fontSrc: ["'self'", "https://fonts.gstatic.com", "https://unpkg.com"],
scriptSrc: ["'self'", "'unsafe-inline'", "https://cdn.jsdelivr.net", "https://static.cloudflareinsights.com"],
imgSrc: ["'self'", "data:", "https:"],
connectSrc: ["'self'", "https://cdn.jsdelivr.net", "https://cloudflareinsights.com"],
},
},
}));
// CORS
app.use(cors({
origin: process.env.CORS_ORIGIN || 'http://localhost:5050',
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
// ==================== GENERAL MIDDLEWARE (BEFORE RATE LIMITING) ====================
// Cookie parser MUST be before rate limiting to read cookies
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
// Request logging middleware
const requestLogger = require('./src/middleware/requestLogger');
app.use(requestLogger);
// ==================== RATE LIMITING ====================
// Rate limiting - Farklı kullanıcı tipleri için farklı limitler
const createRateLimiter = (windowMs, max, message) => {
return rateLimit({
windowMs,
max,
message: { success: false, message },
standardHeaders: true,
legacyHeaders: false,
});
};
// Anonim kullanıcılar için rate limiter (düşük limit)
const anonymousLimiter = createRateLimiter(
parseInt(process.env.RATE_LIMIT_ANONYMOUS_WINDOW_MS) || 15 * 60 * 1000, // 15 dakika
parseInt(process.env.RATE_LIMIT_ANONYMOUS_MAX) || 100, // 100 istek
'Çok fazla istek gönderildi. Lütfen giriş yapın veya daha sonra tekrar deneyin.'
);
// Login olan kullanıcılar için rate limiter (yüksek limit)
const authenticatedLimiter = createRateLimiter(
parseInt(process.env.RATE_LIMIT_AUTHENTICATED_WINDOW_MS) || 15 * 60 * 1000, // 15 dakika
parseInt(process.env.RATE_LIMIT_AUTHENTICATED_MAX) || 1000, // 1000 istek (10x daha fazla)
'Çok fazla istek gönderildi. Lütfen bir süre bekleyin.'
);
// Dinamik rate limiter - kullanıcı tipine göre limit uygula
const dynamicLimiter = (req, res, next) => {
const token = req.cookies.token ||
(req.headers.authorization && req.headers.authorization.split(' ')[1]);
// Token varsa authenticated limiter, yoksa anonymous limiter kullan
if (token) {
authenticatedLimiter(req, res, next);
} else {
anonymousLimiter(req, res, next);
}
};
// Apply dynamic rate limiting to API routes
app.use('/api/', dynamicLimiter);
// Stricter rate limiting for auth routes
const authLimiter = rateLimit({
windowMs: parseInt(process.env.RATE_LIMIT_AUTH_WINDOW_MS) || 15 * 60 * 1000, // 15 minutes
max: parseInt(process.env.RATE_LIMIT_AUTH_MAX) || 5, // 5 requests per window
message: {
success: false,
message: 'Çok fazla giriş denemesi. Lütfen 15 dakika sonra tekrar deneyin.'
}
});
// Kritik işlemler için rate limiter (şifre değiştirme, hesap silme vb.)
const criticalLimiter = rateLimit({
windowMs: parseInt(process.env.RATE_LIMIT_CRITICAL_WINDOW_MS) || 15 * 60 * 1000, // 15 dakika
max: parseInt(process.env.RATE_LIMIT_CRITICAL_MAX) || 10, // 10 istek
message: {
success: false,
message: 'Çok fazla işlem denemesi. Lütfen 15 dakika sonra tekrar deneyin.'
}
});
// Yazma işlemleri için rate limiter (POST/PUT/DELETE)
const writeLimiter = rateLimit({
windowMs: parseInt(process.env.RATE_LIMIT_WRITE_WINDOW_MS) || 1 * 60 * 1000, // 1 dakika
max: parseInt(process.env.RATE_LIMIT_WRITE_MAX) || 30, // 30 istek
message: {
success: false,
message: 'Çok fazla yazma işlemi. Lütfen bir dakika bekleyin.'
}
});
app.use('/api/auth/login', authLimiter);
app.use('/api/auth/register', authLimiter);
app.use('/api/auth/change-password', criticalLimiter);
// Yazma işlemleri için ekstra koruma
app.use('/api/accounts', (req, res, next) => {
if (['POST', 'PUT', 'DELETE'].includes(req.method)) {
writeLimiter(req, res, next);
} else {
next();
}
});
app.use('/api/tasks', (req, res, next) => {
if (['POST', 'PUT', 'DELETE'].includes(req.method)) {
writeLimiter(req, res, next);
} else {
next();
}
});
app.use('/api/proxies', (req, res, next) => {
if (['POST', 'PUT', 'DELETE'].includes(req.method)) {
writeLimiter(req, res, next);
} else {
next();
}
});
// ==================== STATIC FILES & i18n ====================
app.use(express.static('public'));
// i18n middleware
app.use(i18n.middleware());
// ==================== API ROUTES ====================
app.use('/api/auth', authRoutes);
app.use('/api/earnings', earningsRoutes);
app.use('/api/farmlabs', farmlabsRoutes);
app.use('/api/accounts', accountsRoutes);
app.use('/api/tasks', tasksRoutes);
app.use('/api/proxies', proxiesRoutes);
app.use('/api/admin', adminRoutes);
// Health check endpoint
app.get('/api/health', (req, res) => {
try {
const db = require('./src/config/database');
// Test database connection
db.prepare('SELECT 1').get();
res.json({
success: true,
message: 'Server is running',
timestamp: new Date().toISOString(),
database: 'connected',
environment: process.env.NODE_ENV || 'development'
});
} catch (error) {
logger.error('Health check failed', { error: error.message });
res.status(503).json({
success: false,
message: 'Service unavailable',
timestamp: new Date().toISOString(),
database: 'disconnected'
});
}
});
// Debug endpoint - Database info (only in development)
app.get('/api/debug/db', (req, res) => {
if (process.env.NODE_ENV === 'production') {
return res.status(403).json({
success: false,
message: 'Debug endpoint is disabled in production'
});
}
try {
const db = require('./src/config/database');
const users = db.prepare('SELECT id, email, created_at FROM users').all();
const accounts = db.prepare('SELECT id, username, user_id FROM accounts').all();
const sessions = db.prepare('SELECT user_id, expires_at FROM sessions WHERE expires_at > datetime("now")').all();
const proxies = db.prepare('SELECT id, host, port, user_id, is_locked, cooldown_until FROM proxies').all();
const tasks = db.prepare('SELECT id, type, status, user_id FROM tasks').all();
res.json({
success: true,
data: {
users: {
count: users.length,
list: users
},
accounts: {
count: accounts.length,
list: accounts
},
sessions: {
count: sessions.length,
list: sessions
},
proxies: {
count: proxies.length,
list: proxies
},
tasks: {
count: tasks.length,
list: tasks
}
}
});
} catch (error) {
res.status(500).json({
success: false,
message: error.message
});
}
});
// Language switching endpoint
app.post('/api/language', (req, res) => {
const { lang } = req.body;
const supportedLangs = ['tr', 'en'];
if (!lang || !supportedLangs.includes(lang)) {
return res.status(400).json({
success: false,
message: 'Invalid language code'
});
}
// Set language cookie (expires in 1 year)
res.cookie('lang', lang, {
maxAge: 365 * 24 * 60 * 60 * 1000,
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax'
});
res.json({
success: true,
message: 'Language updated',
lang: lang
});
});
// ==================== FRONTEND ROUTES ====================
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/newui', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'newui.html'));
});
// Redirect /panel to /panel/dashboard (must be before app.use)
app.get('/panel', (req, res) => {
res.redirect('/panel/dashboard');
});
// Panel routes - serve separate pages
app.use('/panel', viewRoutes);
// ==================== ERROR HANDLING ====================
// 404 handler for API routes
app.use('/api/*', (req, res) => {
logger.warn('API endpoint not found', {
method: req.method,
url: req.originalUrl,
ip: req.ip
});
res.status(404).json({
success: false,
message: 'API endpoint bulunamadı.'
});
});
// 404 handler for all other routes
app.use('*', (req, res) => {
logger.warn('Page not found', {
method: req.method,
url: req.originalUrl,
ip: req.ip
});
res.status(404).sendFile('404.html', { root: './public' });
});
// Sentry error handler (must be before other error handlers)
app.use(getErrorHandler());
// Global error handler
app.use((err, req, res, next) => {
// Log error
logger.error('Unhandled error', {
error: err.message,
stack: err.stack,
url: req.originalUrl,
method: req.method,
userId: req.user?.id
});
// Capture to Sentry if it's a 500+ error
if (!err.status || err.status >= 500) {
captureException(err, {
url: req.originalUrl,
method: req.method,
userId: req.user?.id
});
}
res.status(err.status || 500).json({
success: false,
message: process.env.NODE_ENV === 'production'
? 'Sunucu hatası.'
: err.message
});
});
// ==================== START SERVER ====================
app.listen(PORT, () => {
logger.info('╔════════════════════════════════════════╗');
logger.info('║ 🌟 SIRIUS STEAM AUTOMATION 🌟 ║');
logger.info('╠════════════════════════════════════════╣');
logger.info(`║ Server: http://localhost:${PORT} ║`);
logger.info(`║ Environment: ${process.env.NODE_ENV || 'development'} ║`);
logger.info('║ Database: SQLite (Local) ║');
logger.info('╠════════════════════════════════════════╣');
logger.info('║ 🔄 Task Queue: Active ║');
logger.info('║ 🔄 Task Executor: Active ║');
logger.info('╚════════════════════════════════════════╝');
// Start task queue processor
taskQueueService.startTaskQueueProcessor();
// Start task executor worker
taskExecutor.startTaskExecutor();
logger.info('║ Status: ✅ Running ║');
logger.info('╚════════════════════════════════════════╝');
logger.info('Server started successfully', {
port: PORT,
environment: process.env.NODE_ENV || 'development',
logLevel: process.env.LOG_LEVEL || 'info',
sentryEnabled: !!(process.env.SENTRY_DSN && process.env.NODE_ENV === 'production')
});
});
// Graceful shutdown
process.on('SIGINT', () => {
logger.info('🛑 Shutting down gracefully...');
process.exit(0);
});
// Unhandled rejection handler
process.on('unhandledRejection', (reason, promise) => {
logger.error('Unhandled Rejection', {
reason: reason,
promise: promise
});
captureException(new Error(`Unhandled Rejection: ${reason}`));
});
// Uncaught exception handler
process.on('uncaughtException', (error) => {
logger.error('Uncaught Exception', {
error: error.message,
stack: error.stack
});
captureException(error);
// Exit process after logging
process.exit(1);
});