-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.js
More file actions
228 lines (199 loc) · 6.53 KB
/
Copy pathserver.js
File metadata and controls
228 lines (199 loc) · 6.53 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
import dotenv from "dotenv";
if (process.env.NODE_ENV !== "production") {
dotenv.config();
}
import fs from "node:fs/promises";
import express from "express";
import mongoose from "mongoose";
import cookieParser from "cookie-parser";
import session from "express-session";
import path from "path";
import MongoStore from "connect-mongo";
import startScheduler, { processRecurringTransactions } from "./utils/scheduler.js";
import errorHandler from "./middleware/errorHandler.js";
import { sendMonthlyAlerts } from "./utils/monthlyAlerts.js";
import cron from "node-cron";
const MONGO_URL = process.env.MONGODB_URI;
async function main() {
await mongoose.connect(MONGO_URL);
console.log("Database connected successfully");
}
main().catch(console.error);
const isProduction = process.env.NODE_ENV === "production";
const port = process.env.PORT || 3000;
const base = process.env.BASE || "/";
const app = express();
app.set("trust proxy", 1); // Trust first proxy (Vercel)
// Traffic Advice for Chrome prefetch proxy (registered early to bypass static files middleware)
app.get("/.well-known/traffic-advice", (req, res) => {
res.setHeader("Content-Type", "application/trafficadvice+json");
res.json([
{
user_agent: "prefetch-proxy",
fraction: 1.0,
},
]);
});
app.use(express.json({ limit: "5mb" }));
app.use(cookieParser());
app.use(express.urlencoded({ limit: "5mb", extended: true }));
app.use(express.static(path.join(process.cwd(), "dist"), {
maxAge: '1y',
immutable: true
}));
/** @type {import('vite').ViteDevServer | undefined} */
let vite;
if (!isProduction) {
const { createServer } = await import("vite");
vite = await createServer({
server: { middlewareMode: true },
appType: "custom",
base,
});
app.use(vite.middlewares);
} else {
const compression = (await import("compression")).default;
const sirv = (await import("sirv")).default;
app.use(compression());
app.use(base, sirv("./dist/client", {
extensions: [],
maxAge: 31536000, // 1 year cache
immutable: true
}));
}
const sessionSecret = process.env.SESSION_SECRET;
const store = MongoStore.create({
mongoUrl: MONGO_URL,
crypto: { secret: sessionSecret },
touchAfter: 24 * 3600,
stringify: false,
});
store.decryptSession = async function (session) {
if (this.crypto && session) {
const plaintext = await this.cryptoGet(this.options.crypto.secret, session.session).catch((err) => {
throw new Error(err);
});
if (typeof plaintext === "object" && plaintext !== null) {
session.session = plaintext;
} else {
session.session = JSON.parse(plaintext);
}
}
};
store.on("error", (error) => {
console.error("Error in Mongo Session Store", error);
});
const sessionOptions = {
store,
secret: sessionSecret,
resave: false,
saveUninitialized: false,
cookie: {
expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
maxAge: 7 * 24 * 60 * 60 * 1000,
httpOnly: true,
secure: isProduction, // Required for HTTPS on Vercel
sameSite: "lax"
},
};
app.use(session(sessionOptions));
import homeRoutes from "./routes/home.js";
import authRoutes from "./routes/auth.js";
import dashboardRoutes from "./routes/dashboard.js";
import transactionRoutes from "./routes/transactions.js";
import analyticsRoutes from "./routes/analytics.js";
import scanReceiptRoutes from "./routes/scanReceipt.js";
import twilioRoutes from "./routes/twilio.js";
const templateHtml = isProduction
? await fs.readFile("./dist/client/index.html", "utf-8")
: "";
// API Routes
app.use("/api", homeRoutes);
app.use("/api", authRoutes);
app.use("/api", twilioRoutes);
app.use("/api/dashboard", dashboardRoutes);
app.use("/api/dashboard/:accountId", transactionRoutes);
app.use("/api/dashboard/:accountId", analyticsRoutes);
app.use("/api/dashboard/:accountId/transaction", scanReceiptRoutes);
// Expose secure Vercel Cron endpoints
const cronAuth = (req, res, next) => {
if (process.env.NODE_ENV !== "production" || req.headers["x-vercel-cron"] === "true") {
next();
} else {
res.status(401).json({ error: "Unauthorized" });
}
};
app.get("/api/cron/process-recurring", cronAuth, async (req, res, next) => {
try {
await processRecurringTransactions();
res.json({ success: true, message: "Recurring transactions processed successfully." });
} catch (error) {
next(error);
}
});
app.get("/api/cron/monthly-alerts", cronAuth, async (req, res, next) => {
try {
await sendMonthlyAlerts();
res.json({ success: true, message: "Monthly alerts sent successfully." });
} catch (error) {
next(error);
}
});
// Serve HTML
app.use("*all", async (req, res) => {
try {
let url = req.originalUrl.replace(base, "");
// Ensure the URL always starts with a leading slash.
if (!url.startsWith("/")) {
url = "/" + url;
}
/** @type {string} */
let template;
/** @type {import('./src/entry-server.js').render} */
let render;
if (!isProduction) {
template = await fs.readFile("./index.html", "utf-8");
template = await vite.transformIndexHtml(url, template);
render = (await vite.ssrLoadModule("/src/entry-server.jsx")).render;
} else {
template = templateHtml;
render = (await import("./dist/server/entry-server.js")).render;
}
const rendered = await render(url);
const html = template
.replace(`<!--app-head-->`, rendered.head ?? "")
.replace(`<!--app-html-->`, rendered.html ?? "");
// Technical SEO: Check valid client routes to return standard 404 code for dead URLs
const validRoutes = [
/^\/$/,
/^\/privacy\/?$/,
/^\/terms\/?$/,
/^\/signup\/?$/,
/^\/login\/?$/,
/^\/dashboard\/?$/,
/^\/dashboard\/addAccount\/?$/,
/^\/dashboard\/[^/]+\/?$/,
/^\/dashboard\/[^/]+\/createTransaction\/?$/,
/^\/dashboard\/[^/]+\/transaction\/[^/]+\/edit\/?$/,
/^\/dashboard\/[^/]+\/analytics\/?$/
];
const isValidRoute = validRoutes.some(regex => regex.test(url));
const statusCode = isValidRoute ? 200 : 404;
res.status(statusCode).set({ "Content-Type": "text/html" }).send(html);
} catch (e) {
vite?.ssrFixStacktrace(e);
res.status(500).end(e.stack);
}
});
// Use the custom error handling middleware
app.use(errorHandler);
// Check NODE_ENV instead of process.env.VERCEL:
if (!process.env.VERCEL) {
app.listen(port, () => {
console.log(`Server started at http://localhost:${port}`);
startScheduler();
cron.schedule("0 9 1 * *", sendMonthlyAlerts);
});
}
// EXPORT the Express app so that Vercel can use it as a handler
export default app;