forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
217 lines (184 loc) · 6.72 KB
/
Copy pathapp.js
File metadata and controls
217 lines (184 loc) · 6.72 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
import express from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
import compression from "compression";
import dotenv from "dotenv";
import crypto from "crypto";
import "./src/jobs/handlers.js";
// Load env vars, except in tests where test/jest.setup.js has already loaded
// (and stripped) secrets — re-loading .env here would leak SMTP/REDIS creds
// back into the test process and cause real network calls.
if (process.env.NODE_ENV !== "test") {
dotenv.config();
}
import connectDB from "./src/config/db.js";
import validateEnv from "./src/config/validateEnv.js";
import logger from "./src/config/logger.js";
import { registry, metricsMiddleware, observeHttpDuration } from "./src/config/metrics.js";
import {
helmetMiddleware,
standardLimiter,
generousLimiter,
authLimiter,
mongoSanitizeMiddleware,
hppMiddleware,
customSecurityHeaders,
} from "./src/middlewares/security.js";
import { sanitizeInput } from "./src/middlewares/validate.js";
import {
errorHandler,
notFound,
handleUnhandledRejection,
handleUncaughtException,
} from "./src/middlewares/errorHandler.js";
import authRoutes from "./src/routes/authRoutes.js";
import courseRoutes from "./src/routes/courses/courseRoutes.js";
import reelsRoute from "./src/routes/reelsRoutes.js";
import userRoutes from "./src/routes/userRoutes.js";
import bookRoutes from "./src/routes/books/bookRoutes.js";
import recommendedBooksRoutes from "./src/routes/books/recommendedBooksRoutes.js";
import spacesRoutes from "./src/routes/spaceRoutes.js";
import emailRoutes from "./src/routes/emailRoutes.js";
import purchaseRoutes from "./src/routes/books/purchaseBookRoutes.js";
import searchRoutes from "./src/routes/searchRoutes.js";
import callRoutes from "./src/routes/callRoutes.js";
import stellarWalletRoutes from "./src/routes/stellar/walletRoutes.js";
import stellarPaymentRoutes from "./src/routes/stellar/paymentRoutes.js";
import stellarDonationRoutes from "./src/routes/stellar/donationRoutes.js";
import payoutRoutes from "./src/routes/payoutRoutes.js";
import uploadRoutes from "./src/routes/uploadRoutes.js";
import notificationRoutes from "./src/routes/notificationRoutes.js";
import jobsRoutes from "./src/routes/jobsRoutes.js";
import wellKnownRoutes from "./src/routes/wellKnownRoutes.js";
import auditRoutes from "./src/routes/admin/auditRoutes.js";
import educatorRoutes from "./src/routes/educatorRoutes.js";
handleUncaughtException();
validateEnv();
// Connect to MongoDB (skip during tests as tests handle their own connections)
if (process.env.NODE_ENV !== "test") {
connectDB();
}
const app = express();
app.set("trust proxy", 1);
// ======================
// REQUEST ID / LOGGING
// ======================
app.use((req, res, next) => {
req.id = req.headers["x-request-id"] || crypto.randomUUID();
req.log = logger.child({ reqId: req.id });
res.setHeader("X-Request-Id", req.id);
next();
});
app.use((req, res, next) => {
const start = Date.now();
res.on("finish", () => {
const duration = Date.now() - start;
const level = res.statusCode >= 400 ? "warn" : "info";
req.log[level](
{ method: req.method, url: req.originalUrl, status: res.statusCode, durationMs: duration },
`${req.method} ${req.originalUrl} ${res.statusCode}`
);
});
next();
});
// HTTP duration observation for Prometheus
app.use((req, res, next) => {
const start = Date.now();
res.on("finish", () => {
const route = req.route?.path || req.baseUrl || req.path;
observeHttpDuration(req.method, route, res.statusCode, Date.now() - start);
});
next();
});
// ======================
// METRICS (before rate limiter)
// ======================
app.get("/metrics", metricsMiddleware);
// ======================
// SECURITY MIDDLEWARE
// ======================
app.use(helmetMiddleware);
app.use(customSecurityHeaders);
const corsOptions = {
origin: function (origin, callback) {
const allowedOrigins = [
"https://dnb-frontend.vercel.app",
"http://localhost:3000",
"http://localhost:3001",
"https://deenbridge.vercel.app",
"http://deenbridge.vercel.app",
];
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) !== -1) {
callback(null, true);
} else {
logger.warn(`Blocked CORS request from origin: ${origin}`);
callback(new Error("Not allowed by CORS"));
}
},
credentials: true,
optionsSuccessStatus: 200,
methods: ["GET", "POST", "PUT", "DELETE", "PATCH"],
allowedHeaders: ["Content-Type", "Authorization"],
};
app.use(cors(corsOptions));
app.use(express.json({ limit: "10mb" }));
app.use(express.urlencoded({ extended: true, limit: "10mb" }));
app.use(cookieParser());
app.use(compression());
app.use(mongoSanitizeMiddleware);
app.use(hppMiddleware);
app.use(sanitizeInput);
// ======================
// ROUTES
// ======================
app.get("/", (req, res) => {
res.json({
success: true,
message: "Welcome to DeenBridge API",
version: "1.0.0",
environment: process.env.NODE_ENV,
});
});
app.get("/health", (req, res) => {
res.json({
success: true,
message: "pong",
timestamp: new Date().toISOString(),
});
});
// SEP-1 stellar.toml — must be outside /api rate limiter
app.use("/.well-known", wellKnownRoutes);
// Auth routes — strict
app.use("/api/auth", authLimiter, authRoutes);
// Mutation routes — standard limiter
app.use("/api/email", standardLimiter, emailRoutes);
app.use("/api/purchase", standardLimiter, purchaseRoutes);
app.use("/api/uploads", standardLimiter, uploadRoutes);
app.use("/api/payouts", standardLimiter, payoutRoutes);
// Read-heavy & content routes — generous limiter
app.use("/api/courses", generousLimiter, courseRoutes);
app.use("/api/reels", generousLimiter, reelsRoute);
app.use("/api/books", generousLimiter, bookRoutes);
app.use("/api/books", generousLimiter, recommendedBooksRoutes);
app.use("/api/spaces", generousLimiter, spacesRoutes);
app.use("/api/users", generousLimiter, userRoutes);
app.use("/api/search", generousLimiter, searchRoutes);
app.use("/api/calls", generousLimiter, callRoutes);
app.use("/api/educators", generousLimiter, educatorRoutes);
app.use("/api/stellar/wallet", generousLimiter, stellarWalletRoutes);
app.use("/api/stellar/payment", generousLimiter, stellarPaymentRoutes);
app.use("/api/stellar/donation", generousLimiter, stellarDonationRoutes);
app.use("/api/notifications", generousLimiter, notificationRoutes);
// Admin — no rate limit
app.use("/admin/jobs", jobsRoutes);
app.use("/api/admin/audit", auditRoutes);
// ======================
// ERROR HANDLING
// ======================
app.use(notFound);
app.use(errorHandler);
handleUnhandledRejection();
logger.info("DeenBridge API initialized");
logger.info(`Logging enabled - Level: ${logger.level}`);
export default app;