-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathapp.js
More file actions
209 lines (167 loc) · 5.96 KB
/
Copy pathapp.js
File metadata and controls
209 lines (167 loc) · 5.96 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
const dotenv = require('dotenv');
const path = require('path');
dotenv.config({ path: path.join(__dirname, '../../../.env') });
const { validateEnv } = require('@urbackend/common');
if (process.env.NODE_ENV !== 'test') {
validateEnv();
}
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const cookieParser = require('cookie-parser');
const csurf = require('csurf');
const rateLimit = require('express-rate-limit');
const app = express();
app.set('trust proxy', 1);
const {garbageCollect, storageGarbageCollect, getPublicIp, standardizeApiResponse} = require('@urbackend/common');
const { capture } = require('@kiroo/sdk');
const { emailQueue, authEmailQueue } = require('@urbackend/common');
const dashboardLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 1000,
message: { error: "Dashboard usage limit exceeded. Slow down!" },
skip: (req) => process.env.NODE_ENV === 'development',
});
const whitelist = (function() {
// Default allowed origins
const allowed = [process.env.FRONTEND_URL];
// Support comma-separated list of origins in .env
if (process.env.ALLOWED_ORIGINS) {
const extraOrigins = process.env.ALLOWED_ORIGINS.split(',').map(o => o.trim());
allowed.push(...extraOrigins);
}
if (process.env.NODE_ENV === 'development') {
allowed.push('http://localhost:5173');
allowed.push('http://localhost:3000');
}
// Filter out duplicates and empty values
const uniqueAllowed = [...new Set(allowed.filter(Boolean))];
return {
get: () => uniqueAllowed
};
})()
app.use(cors({
origin: whitelist.get(),
credentials: true,
}));
app.use(express.json({
verify: (req, res, buf) => {
req.rawBody = buf.toString();
}
}));
app.use(express.urlencoded({ extended: true }));
app.use(standardizeApiResponse);
app.use(cookieParser());
const csrfProtection = csurf({
cookie: {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax'
}
});
app.use((req, res, next) => {
// Exclude Razorpay webhook from CSRF protection since it's an external POST request
if (req.path === '/api/billing/webhook') {
return next();
}
csrfProtection(req, res, next);
});
if (process.env.NODE_ENV !== 'test') {
garbageCollect();
storageGarbageCollect();
}
app.use(capture({
supabaseUrl: process.env.SUPABASE_URL,
supabaseKey: process.env.SUPABASE_KEY,
bucket: process.env.SUPABASE_BUCKET,
sampleRate: 0
}));
const authRoute = require('./routes/auth');
const projectRoute = require('./routes/projects');
const releaseRoute = require('./routes/releases');
const webhookRoute = require('./routes/webhooks');
const analyticsRoute = require('./routes/analytics');
const billingRoute = require('./routes/billing');
const eventsRoute = require('./routes/events');
const adminMetricsRoute = require('./routes/admin.metrics');
app.use('/api/auth', authRoute);
app.use('/api/projects', dashboardLimiter, projectRoute);
app.use('/api/projects', dashboardLimiter, webhookRoute);
app.use('/api/releases', releaseRoute);
app.use('/api/analytics', dashboardLimiter, analyticsRoute);
app.use('/api/billing', billingRoute);
app.use('/api/events', dashboardLimiter, eventsRoute);
app.use('/api/admin/metrics', dashboardLimiter, adminMetricsRoute);
app.get('/api/server-ip', async (req, res) => {
const ip = await getPublicIp();
res.json({ ip });
});
app.get('/', (req, res) => {
res.status(200).json({ status: "success", message: "urBackend API is running 🚀" })
});
// Global Error Handler
app.use((err, req, res, next) => {
// CSRF Error Handling
if (err.code === 'EBADCSRFTOKEN') {
return res.status(403).json({
success: false,
error: "Invalid CSRF token",
message: "The form has expired or the CSRF token is invalid. Please refresh the page and try again."
});
}
if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
return res.status(400).json({
success: false,
error: "Invalid JSON format",
message: "Check your request body syntax. Stray characters outside the JSON object are not allowed."
});
}
const statusCode = err.statusCode || 500;
const message = err.message || "Something went wrong!";
// Only log actual server errors (500), not expected operational errors (4xx)
if (statusCode >= 500) {
console.error("🔥 Server Error:", err.stack);
}
res.status(statusCode).json({
success: false,
error: statusCode >= 500 ? "Internal Server Error" : message,
message: message
});
});
app.use((req, res) => {
const id = res.get("X-Kiroo-Replay-ID");
res.json({error: "Not Found", replayId: id})
})
if (process.env.NODE_ENV !== 'test') {
const PORT = process.env.PORT || 1234;
const { connectDB } = require('@urbackend/common');
// Start DB & Server
connectDB();
const server = app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
// SHUTDOWN
const gracefulShutdown = async () => {
console.log('🛑 SIGTERM/SIGINT received. Shutting down gracefully...');
server.close(async () => {
console.log('✅ HTTP server closed.');
try {
await mongoose.connection.close(false);
console.log('✅ MongoDB connection closed.');
process.exit(0);
} catch (err) {
console.error('❌ Error closing MongoDB connection:', err);
process.exit(1);
}
});
// Force close after 10s
setTimeout(() => {
console.error('Force shutting down...');
process.exit(1);
}, 10000);
};
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);
}
// Export for Testing
module.exports = app;