-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
71 lines (60 loc) · 2.55 KB
/
index.js
File metadata and controls
71 lines (60 loc) · 2.55 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
require('dotenv').config({
path: require('fs').existsSync('.env.local') ? '.env.local' : '.env'
});
const express = require('express');
const cors = require('cors');
const matrixRoutes = require('./routes/matrixRoutes.route');
const connectDB = require('./config/db');
const cronService = require("./services/cron.service");
const guardian = require('./middleware/guardian');
const app = express();
const isDev = process.env.NODE_ENV === 'development';
app.set('trust proxy', !isDev);
const CORS_ORIGIN = process.env.CORS_ORIGIN;
const whitelist = CORS_ORIGIN ? CORS_ORIGIN.split(',').map(item => item.trim()) : [];
app.use(cors({
origin: (origin, callback) => {
if (!origin || whitelist.indexOf(origin) !== -1 || !CORS_ORIGIN) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
credentials: true,
allowedHeaders: ['Content-Type', 'x-ambastha-secret', 'x-ambastha-device-id', 'x-hub-signature-256', 'x-user-id', 'x-admin-api-key']
}));
app.use(express.json({
verify: (req, res, buf) => {
if (req.url.includes('/webhook')) req.rawBody = buf;
}
}));
app.use((req, res, next) => {
const forwarded = req.headers['x-forwarded-for'];
req.userRealIp = forwarded ? forwarded.split(',')[0].trim() : req.ip;
if (req.url.startsWith('/api/v1/matrix') || req.url === '/') {
const userId = req.headers['x-user-id'] || '-';
console.log(`[REQ] ${req.method} ${req.url} | IP: ${req.userRealIp} | User: ${userId}`);
}
next();
});
app.get('/health', (req, res) => res.status(200).json({ status: 'OK', uptime: process.uptime() }));
app.use('/api/v1/matrix', guardian, matrixRoutes);
connectDB().then(() => {
console.log('[DB]: Connected 🔗');
setTimeout(() => {
cronService.checkAndRunOptimization(true).catch(e => console.error('[OPT_ERR]:', e));
}, 5000);
}).catch(err => {
console.error('[FATAL]: DB Connection Failed 💀', err);
process.exit(1);
});
app.use((err, req, res, next) => {
if (err.message === 'Not allowed by CORS') return res.status(403).json({ error: 'CORS Blocked' });
console.error(`[CRITICAL_ERROR]: ${err.stack}`);
res.status(500).json({ success: false, message: 'Matrix glitch detected. Engine resetting...' });
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, '0.0.0.0', () => {
console.log(`[SERVER]: Ambastha API Online @ Port ${PORT} 🛡️✨🚀`);
});