Repository navigation
Expand file tree
/
Copy pathapp.ts
More file actions
218 lines (195 loc) · 7.51 KB
/
Copy pathapp.ts
File metadata and controls
218 lines (195 loc) · 7.51 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
import compression from "compression";
import cookieParser from "cookie-parser";
import cors from "cors";
import express, { Express } from "express";
import helmet from "helmet";
import path from "path";
import pinoHttp from "pino-http";
import swaggerUi from "swagger-ui-express";
import { isDatabaseConnected } from "./config/database";
import { env } from "./config/env";
import { logger } from "./config/logger";
import { clearResetOutbox, getLastResetUrl } from "./config/mailer";
import passport from "./config/passport";
import { swaggerSpec, swaggerUiAssets } from "./config/swagger";
import { resetDatabase } from "./db/reset";
import { errorHandler, notFoundHandler } from "./middleware/error-handler";
import { apiLimiter } from "./middleware/rate-limit";
import { storageDriver, uploadsDir } from "./modules/uploads/upload.service";
import routes from "./routes/index";
import { asyncHandler } from "./utils/async-handler";
/**
* Answers without touching the database, so frequent uptime checks do not keep
* a scale-to-zero database awake. `api/index.ts` skips its connection gate for
* this path too.
*/
export const LIVENESS_PATH = "/health/live";
export function createApp(): Express {
const app = express();
// Vercel (and any reverse proxy) sits in front of this app. Without this,
// req.ip is the proxy's address, so every client shares one rate-limit
// bucket: one attacker exhausts authLimiter's 20 attempts for everyone.
app.set("trust proxy", 1);
app.use(helmet());
app.use(compression());
app.use(pinoHttp({ logger }));
/**
* An explicit allowlist, echoing back the caller's own origin only when it
* is on the list. The previous version always answered with the single
* configured ORIGIN_URL regardless of who asked, so the moment a second
* legitimate origin existed (localhost alongside a deployed frontend) it
* was blocked, and its IGNORE_ORIGINS escape hatch fixed that locally by
* allowing *every* origin instead. `credentials: true` means a wildcard is
* never an option here, so the list has to be real.
*
* Requests with no Origin header at all (curl, server-to-server, same-origin
* navigations) are allowed through: CORS is a browser mechanism and there is
* nothing to protect when no browser origin is involved.
*/
const allowedOrigins = new Set([env.ORIGIN_URL, ...env.CORS_ORIGINS]);
app.use(
cors({
origin: (origin, callback) => {
if (!origin || allowedOrigins.has(origin)) {
callback(null, origin ?? true);
} else {
callback(null, false);
}
},
credentials: true,
allowedHeaders: ["Set-Cookie", "Content-Type"],
}),
);
// Text only. Images never travel in a JSON body: an event cover is uploaded to
// object storage and the event keeps its link (DB-1), so nothing here needs
// more than a few hundred kilobytes. A small ceiling keeps one request from
// exhausting memory (S-4).
app.use(express.json({ limit: "1mb" }));
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(passport.initialize());
app.use(apiLimiter);
// Uploaded event covers when images go to local disk (development and test;
// a deployment with a Blob token serves them from Blob). Helmet's default
// same-origin resource policy would stop the web app, on another origin,
// from showing them. Files are named by random id and never change, so they
// cache for good.
if (storageDriver() === "local") {
app.use(
"/uploads/files",
(_req, res, next) => {
res.setHeader("Cross-Origin-Resource-Policy", "cross-origin");
next();
},
express.static(uploadsDir(), {
index: false,
dotfiles: "deny",
immutable: true,
maxAge: "1y",
}),
);
}
app.get("/", (_req, res) => {
res.send("HELLO FROM API");
});
app.get(LIVENESS_PATH, (_req, res) => {
res.json({ status: "ok" });
});
// Reports the real database state. A down database answers 503, so a free
// uptime monitor pointed at this URL alerts without any extra service (O-5).
app.get(
"/health",
asyncHandler(async (_req, res) => {
const connected = await isDatabaseConnected();
res.status(connected ? 200 : 503).json({
status: connected ? "ok" : "unavailable",
postgres: connected ? "connected" : "disconnected",
});
}),
);
/**
* Test-only, gated behind NODE_ENV==="test" so it can never exist in a
* real deployment. Wipes every PostgreSQL table
* — Playwright's global setup calls this between spec files instead of
* restarting the whole e2e server, the same isolation Jest's own
* `afterEach` gets for free from an in-process app. See
* apps/api/tests/e2e/server.ts and docs/specs/testing.md (apps/web).
* apiLimiter above already `skip`s for NODE_ENV==="test", so this isn't
* rate-limited either.
*/
if (env.NODE_ENV === "test") {
app.post("/__test__/reset", async (_req, res) => {
await resetDatabase();
clearResetOutbox();
res.status(204).end();
});
/**
* Reads the captured reset URL so Playwright can complete a full
* forgot/reset-password journey without a real mail provider.
*/
app.get("/__test__/last-reset-url", (req, res) => {
const to = String(req.query.email ?? "");
const resetUrl = getLastResetUrl(to);
if (!resetUrl) {
res
.status(404)
.json({ message: "No reset email captured for this address yet." });
return;
}
res.json({ resetUrl });
});
}
// Local development helper for inspecting a captured password-reset link.
// Keep it loopback-only: reset tokens must not be readable over a network.
if (env.NODE_ENV === "development") {
app.get("/__dev__/last-reset-url", (req, res) => {
const remoteAddress = req.socket.remoteAddress ?? "";
const isLoopback =
remoteAddress === "::1" ||
remoteAddress === "127.0.0.1" ||
remoteAddress.startsWith("::ffff:127.");
if (!isLoopback) {
res.sendStatus(404);
return;
}
const to = String(req.query.email ?? "");
const resetUrl = getLastResetUrl(to);
if (!resetUrl) {
res
.status(404)
.json({ message: "No reset email captured for this address yet." });
return;
}
res.json({ resetUrl });
});
}
// Each file is named here so that the Vercel build ships it with the function:
// it cannot see the folder swagger-ui-express serves them from. `root` is
// needed because pnpm's path contains a dot folder, which `sendFile` refuses.
for (const file of swaggerUiAssets) {
app.get(`/docs/${path.basename(file)}`, (_req, res) => {
res.sendFile(path.basename(file), { root: path.dirname(file) });
});
}
app.use("/docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec));
app.use(routes);
app.use(notFoundHandler);
app.use(errorHandler);
return app;
}
/**
* Vercel's zero-config detection recognises `src/app.ts` as an Express
* entrypoint (the build fails without one that imports express) and runs it
* directly for `GET /`. That needs a default export that is a handler, or the
* root URL answers 500 `FUNCTION_INVOCATION_FAILED`. Every other path goes
* through `api/index.ts`, which also waits for the database. The root route
* needs no database, so this handler does not.
*/
let rootApp: Express | undefined;
export default function handler(
req: express.Request,
res: express.Response,
): void {
rootApp ??= createApp();
rootApp(req, res);
}