-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
364 lines (315 loc) · 15.8 KB
/
server.ts
File metadata and controls
364 lines (315 loc) · 15.8 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
import * as fs from "node:fs";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import express from "express";
import type { Request, Response } from "express";
import dotenv from "dotenv";
import { ViteDevServer } from "vite";
import api from "./server/app.js";
import cookieParser from "cookie-parser";
import rateLimit from "express-rate-limit";
import { loggingMiddleware } from "./server/api/middleware/loggingMiddleware.js";
import { startWebhookEventScheduler, stopWebhookEventScheduler } from "./server/api/jobs/webhookEventProcessor.js";
import { startRetentionEmailScheduler, stopRetentionEmailScheduler } from "./server/api/jobs/retentionEmailProcessor.js";
import { ensureWebhookSubscription } from "./server/api/handlers/stravaWebhookHandler.js";
import { handleShortLinkRedirect } from "./server/api/handlers/shortLinkHandler.js";
dotenv.config();
// Get directory name for ES modules (needed because __dirname doesn't exist in ES modules)
const __dirname: string = path.dirname(fileURLToPath(import.meta.url));
const isTest = process.env.VITEST;
const isProd = process.env.NODE_ENV === "production";
const root: string = process.cwd();
// Fail fast if APP_URL is missing in production. Without it, links emitted in
// password-reset / email-change emails would fall back to http://localhost:3000.
if (isProd && !process.env.APP_URL) {
throw new Error("FATAL: APP_URL environment variable is not set in production.");
}
// Helper to resolve paths relative to server directory
const resolve = (_path: string) => path.resolve(__dirname, _path);
// Pre-load production HTML template for SSR (only in production)
const indexProd: string = isProd
? fs.readFileSync(resolve("client/index.html"), "utf-8")
: "";
const createServer = async () => {
const app = express();
// Hide Express from response headers to reduce fingerprinting
app.disable("x-powered-by");
// Trust proxy headers when behind nginx/reverse proxy (required for secure cookies)
if (isProd) {
app.set("trust proxy", 1);
}
// Parse request bodies for form submissions with size limits to prevent DoS
app.use(express.urlencoded({ extended: true, limit: "1mb" }));
// Paddle webhook needs raw body for signature verification
app.use("/api/paddle/webhook", express.json({
limit: "1mb",
verify: (req: Request, res, buf) => {
(req as Request & { rawBody?: string }).rawBody = buf.toString();
}
}));
app.use(express.json({ limit: "1mb" }));
// Parse cookies
app.use(cookieParser());
// Security headers to prevent clickjacking, MIME sniffing, and enforce HTTPS
app.use((_req, res, next) => {
res.setHeader("X-Frame-Options", "DENY");
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
res.setHeader("X-XSS-Protection", "0");
// Cross-origin isolation defenses (COEP deliberately omitted — would break
// allowlisted third-party images like cdn.paddle.com / openfoodfacts.org).
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
res.setHeader("Cross-Origin-Resource-Policy", "same-origin");
// CSP provides defense-in-depth against XSS attacks
// Development needs unsafe-inline/eval for Vite HMR and React refresh
if (isProd) {
res.setHeader("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.paddle.com https://static.cloudflareinsights.com https://*.stripe.network https://*.localizecdn.com; style-src 'self' 'unsafe-inline' https://cdn.paddle.com https://fonts.googleapis.com; img-src 'self' https://cdn.nobull.fit https://cdn.paddle.com https://images.openfoodfacts.org data:; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://api.paddle.com https://checkout-analytics.paddle.com https://checkout-service.paddle.com https://*.stripe.com https://*.stripe.network https://*.localizecdn.com https://*.ingest.sentry.io https://cloudflareinsights.com; frame-src https://buy.paddle.com https://sandbox-buy.paddle.com https://*.stripe.com https://*.stripe.network; frame-ancestors 'none'; base-uri 'self'; object-src 'none'; form-action 'self';");
}
if (isProd) {
res.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
}
next();
});
// Allow cross-origin requests from local dev servers (Vite, Expo) in development.
// Only reflect the Origin header back when it matches the localhost allowlist —
// never echo arbitrary origins with credentials enabled.
if (!isProd) {
const LOCAL_DEV_ORIGIN = /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;
app.use("/api", (req, res, next) => {
const origin = req.headers.origin;
if (origin && LOCAL_DEV_ORIGIN.test(origin)) {
res.header("Access-Control-Allow-Origin", origin);
res.header("Vary", "Origin");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.header("Access-Control-Allow-Credentials", "true");
}
if (req.method === "OPTIONS") {
res.sendStatus(204);
return;
}
next();
});
}
// Rate limiting for auth endpoints to prevent brute-force attacks
const authRateLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 10, // 10 attempts per window
standardHeaders: true,
legacyHeaders: false,
message: { error: "Too many attempts. Please try again later." }
});
app.use("/api/sign-in", authRateLimiter);
app.use("/api/sign-up", authRateLimiter);
app.use("/api/forgot-password", authRateLimiter);
app.use("/api/reset-password", authRateLimiter);
// Throttle account-modification endpoints — these require an authenticated
// session, so the IP bucket is effectively per-user in normal use.
const changeActionRateLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5,
standardHeaders: true,
legacyHeaders: false,
message: { error: "Too many attempts. Please try again later." }
});
app.use("/api/settings/change-password", changeActionRateLimiter);
app.use("/api/settings/change-email", changeActionRateLimiter);
// Tighter limit on phone OTP send to protect against SMS-cost abuse.
const phoneSendCodeRateLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 3,
standardHeaders: true,
legacyHeaders: false,
message: { error: "Too many verification code requests. Please try again later." }
});
app.use("/api/phone/send-code", phoneSendCodeRateLimiter);
// Log all API requests to the database
app.use("/api", loggingMiddleware);
// Mount API routes BEFORE Vite middleware so API requests are handled by Express
// This is critical for webhooks (like Paddle) that won't have allowed host headers
app.use("/api", api.router);
// Short link redirect handler (for SMS and other scenarios)
app.get("/p/:code", handleShortLinkRedirect);
// Block admin panel routes in production
if (isProd) {
app.use("/admin", (_req, res) => {
res.status(404).send("Not found");
});
}
let vite: ViteDevServer | undefined;
// Initialize Vite dev server in development mode
if (!isProd) {
vite = await (await import("vite")).createServer({
root,
logLevel: isTest ? "error" : "info",
server: {
middlewareMode: true,
// Use polling for file watching (better compatibility on Windows)
watch: {
usePolling: true,
interval: 100
}
},
appType: "custom"
});
// Use Vite's middleware to handle dev server requests
app.use(vite.middlewares);
}
if (isProd) {
// Enable gzip compression for production
const compressionModule = await import("compression");
// compression is a CommonJS module, handle both default and namespace exports
const compressionFn = (compressionModule.default || compressionModule) as () => express.RequestHandler;
app.use(compressionFn());
// Serve static files from client build directory
app.use(
(await import("serve-static")).default(resolve("./client"), {
index: false
})
);
}
// SSR route handler - catches all non-API routes
app.use(/.*/, async (req: Request, res: Response) => {
// Skip API routes
if (req.path.startsWith("/api")) {
return;
}
try {
const url = req.originalUrl;
let template, render;
// In development, use Vite's SSR capabilities
let cssLinks = "";
if (!isProd && vite) {
template = fs.readFileSync(resolve("index.html"), "utf8");
// Load SSR entry module first to process CSS imports
const ssrModule = await vite.ssrLoadModule("/src/entry-server.tsx");
render = ssrModule.default.render;
// Extract CSS from Vite's module graph
// CSS files imported in entry-server.tsx are processed by Vite
const cssModules: string[] = [];
vite.moduleGraph.idToModuleMap.forEach((module, id) => {
if ((id.endsWith(".css") || id.endsWith(".scss")) && module.url) {
cssModules.push(module.url);
}
});
// Create CSS link tags - use absolute URLs for Vite dev server
cssLinks = cssModules
.map((cssUrl) => `<link rel="stylesheet" href="${cssUrl}" />`)
.join("\n ");
// Transform HTML template with Vite (injects HMR scripts, etc.)
template = await vite.transformIndexHtml(url, template);
} else {
// In production, use pre-loaded template and compiled entry
template = indexProd;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
render = (await import("../entry/entry-server.js")).default.render;
// In production, CSS is already bundled - Vite will inject it via transformIndexHtml
}
// Context for handling redirects from React Router
interface RedirectContext {
url?: string;
}
const context: RedirectContext = {};
// Render React app to HTML string or handle action response
const result = await render(req);
// If result is a Response (from action), handle it directly
if (result instanceof Response) {
// Handle redirects
if (result.status >= 300 && result.status < 400) {
const location = result.headers.get("Location");
if (location) {
return res.redirect(result.status, location);
}
}
// Handle other responses (like JSON error responses from actions)
const contentType = result.headers.get("Content-Type") || "text/html";
res.status(result.status).set("Content-Type", contentType);
const body = await result.text();
return res.send(body);
}
const appHtml = result;
const { helmet } = appHtml;
// Handle redirects from React Router loaders
if (context.url) return res.redirect(301, context.url);
// Inject rendered HTML into template
let html = template.replace("<!--app-html-->", appHtml.html);
// Inject helmet meta tags and CSS into head section
html = html.replace("<!--app-head-->", [
cssLinks,
helmet.title.toString(),
helmet.meta.toString(),
helmet.link.toString(),
helmet.style.toString()
].filter(Boolean).join("\n "));
// Inject scripts before closing body tag
html = html.replace("<!--app-scripts-->", helmet.script.toString());
// Prevent browser from caching authenticated pages so back-button after logout shows nothing
const headers: Record<string, string> = { "Content-Type": "text/html" };
if (req.path.startsWith("/dashboard") || req.path.startsWith("/admin")) {
headers["Cache-Control"] = "no-store";
}
res.status(200).set(headers).end(html);
} catch (e) {
// Handle redirects from React Router loaders/actions
if (e instanceof Response) {
if (e.status >= 300 && e.status < 400) {
const location = e.headers.get("Location");
if (location) {
return res.redirect(e.status, location);
}
}
// If it's a Response but not a redirect, send it as-is
return res.status(e.status).set(Object.fromEntries(e.headers.entries())).send(e.body);
}
// Error handling for SSR failures
if (e instanceof Error) {
// Fix stack traces in development (Vite needs to map source locations)
!isProd && vite && vite.ssrFixStacktrace(e);
console.error(e.stack);
// Never expose stack traces to clients in production
res.status(500).end(isProd ? "Internal Server Error" : e.stack);
} else {
console.error(e);
res.status(500).end("Internal Server Error");
}
}
});
return { app, vite };
};
// Start server (skip in test environment)
if (!isTest) {
createServer().then(async ({ app }) => {
// Start webhook event processor (runs every 30 seconds)
const webhookProcessorId = startWebhookEventScheduler(30);
// Start retention email processor (runs every 24 hours)
const retentionProcessorId = startRetentionEmailScheduler(86400);
const server = app.listen(process.env.PORT || 3000, async () => {
console.log(`Server running on http://localhost:${process.env.PORT || 3000}`);
console.log("[WebhookProcessor] Scheduler started (interval: 30 seconds)");
console.log("[RetentionEmailProcessor] Scheduler started (interval: 24 hours)");
// Auto-setup Strava webhook subscription in production
// Must run AFTER server is listening so Strava's validation callback can reach us
if (isProd) {
// Small delay to ensure server is fully ready. The inner promise
// is explicitly caught so a rejection doesn't bubble into an
// unhandled-promise-rejection and kill the process at boot.
setTimeout(() => {
ensureWebhookSubscription().catch((err) => {
console.error("[Strava Webhook] ensureWebhookSubscription failed:", err);
});
}, 2000);
}
});
// Graceful shutdown
process.on("SIGTERM", () => {
console.log("SIGTERM received, shutting down gracefully...");
stopWebhookEventScheduler(webhookProcessorId);
stopRetentionEmailScheduler(retentionProcessorId);
server.close(() => {
console.log("Server closed");
process.exit(0);
});
});
});
}