Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 42x 281x 281x 281x 281x 281x 281x 281x 5x 281x 281x 281x 278x 281x 281x 4x 4x 4x 4x 281x 281x 278x 278x 278x 281x 281x 6x 6x 281x 278x 278x 281x 12x 34x 12x 10x 10x 2x 281x 281x 1x 1x 1x 281x 281x 281x 281x 281x 281x 281x 281x 42x 277x 277x 277x 4x 277x 277x 277x 277x 277x 277x | import { once } from "node:events";
import http, { Server, ServerResponse } from "node:http";
import path from "node:path";
import { flush, setupExpressErrorHandler } from "@sentry/node";
import express, { NextFunction, Request, Response } from "express";
import expressStaticGzip from "express-static-gzip";
import helmet from "helmet";
import { config } from "shared/config";
import { apiRoutes } from "server/api/apiRoutes";
import { healthRoutes } from "server/api/healthRoutes";
import { sentryRoutes } from "server/api/sentryRoutes";
import { db } from "server/db/mongodb";
import { allowCORS } from "server/middleware/cors";
import { wwwRedirect } from "server/middleware/wwwRedirect";
import { stopCronJobs } from "server/utils/cron";
import { logger } from "server/utils/logger";
interface StartServerParams {
dbConnString: string;
port?: number;
dbName?: string;
// Overridable so a test can serve a directory of its own instead of the
// build output, which other suites running in parallel also read
staticFilesPath?: string;
}
export const startServer = async ({
dbConnString,
port,
dbName,
staticFilesPath,
}: StartServerParams): Promise<Server> => {
await db.connectToDb(dbConnString, dbName);
const app = express();
// Trust one hop of reverse proxy (k8s ingress / load balancer) so req.ip reads
// X-Forwarded-For instead of the proxy's address. Harmless in dev.
app.set("trust proxy", 1);
const cspConnectSrc = [
"'self'",
"*.sentry.io",
...config.server().allowedCorsOrigins,
];
// Only the deployed profiles sit behind a TLS ingress. Everywhere else the
// app is served over plain http, and upgrading subresource requests there
// breaks the page outright: WebKit applies the upgrade to loopback origins
// too (Chromium exempts them), so every chunk fails the TLS handshake and
// nothing renders.
const servedOverTls =
process.env.SETTINGS === "production" || process.env.SETTINGS === "staging";
app.use(
helmet({
contentSecurityPolicy: {
directives: {
"connect-src": cspConnectSrc,
...(!servedOverTls && {
upgradeInsecureRequests: null,
}),
},
},
}),
);
Iif (process.env.NODE_ENV === "development") {
// Kompassi mock service requires content type application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
}
// A cronjob-only instance serves no client traffic, but is still probed
const serveIndexAndApi =
!config.server().onlyCronjobs ||
config.server().cronjobsAndBackendSameInstance;
app.use(healthRoutes);
if (serveIndexAndApi) {
// Accepts raw body, so it has to be mounted before the JSON parser below
app.use(sentryRoutes);
}
// Every request body is parsed as JSON, whatever content type it declares
app.use(express.json({ limit: "1000kb", type: "*/*" }));
// The parser rejects a body the client got wrong (malformed JSON, too large,
// an unsupported charset) with a 4xx error, so it is not a server error
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
Eif (
"status" in err &&
typeof err.status === "number" &&
err.status >= 400 &&
err.status < 500
) {
const ip = req.ip?.replace(/^::ffff:/, "") ?? "-";
logger.warn(
`Invalid request: ${req.method} ${req.originalUrl} ip=${ip}: ${err.message}`,
);
return res.sendStatus(err.status);
}
next(err);
});
app.use(wwwRedirect);
if (serveIndexAndApi) {
app.use("/api", allowCORS);
app.use("/auth", allowCORS);
app.use(apiRoutes);
}
const staticPath =
staticFilesPath ?? path.join(import.meta.dirname, "../../", "front");
// The bundler emits every file it builds into assets/ with a content hash
// in the name, while static files are copied from the client's public
// directory to the served root. A path under assets/ is therefore exactly
// the set of files whose name changes with their content, which is what
// makes them safe to cache forever. Deciding by directory rather than by
// the shape of the filename matters because names alone are ambiguous:
// an ordinary hyphenated name (service-worker-registration.js) is
// indistinguishable from a hashed one. Everything else revalidates,
// index.html above all - it decides which hashed files are requested.
// Split on both separators because the path comes from the serving
// library and may use either style.
const setStaticCacheHeaders = (
res: ServerResponse,
filePath: string,
): void => {
// Relative to the served root: the absolute path can carry an "assets"
// directory of its own above it, which would cache index.html forever
const isBundledAsset = path
.relative(staticPath, filePath)
.split(/[\\/]/)
.includes("assets");
res.setHeader(
"Cache-Control",
isBundledAsset ? "public, max-age=31536000, immutable" : "no-cache",
);
};
if (serveIndexAndApi) {
if (config.server().bundleCompression) {
app.use(
expressStaticGzip(staticPath, {
enableBrotli: true,
orderPreference: ["br", "gz"],
serveStatic: {
acceptRanges: false,
setHeaders: setStaticCacheHeaders,
},
}),
);
} else E{
app.use(
express.static(staticPath, {
acceptRanges: false,
setHeaders: setStaticCacheHeaders,
}),
);
}
}
app.get("/*splat", (req: Request, res: Response) => {
// A dotted path segment is a file request the static middleware already
// failed to match, so the file doesn't exist. App routes never contain dots.
const looksLikeFile = req.path
.split("/")
.some((segment) => segment.includes("."));
if (
req.originalUrl.includes("/api/") ||
looksLikeFile ||
!serveIndexAndApi
) {
res.sendStatus(404);
return;
}
res.sendFile(path.join(staticPath, "index.html"), {
headers: { "Cache-Control": "no-cache" },
});
});
// Sentry setup: add this after all routes and before other error-handling middlewares
setupExpressErrorHandler(app);
app.use((err: Error, _req: Request, res: Response, next: NextFunction) => {
// Once headers are sent the default Express handler is the only thing that can still
// close the connection and fail the request, e.g. after an error mid-stream
Iif (res.headersSent) {
logger.error(new Error("Error after headers sent", { cause: err }));
next(err);
return;
}
logger.error(err);
return res.sendStatus(500);
});
const server = http.createServer(app);
const runningServer = server.listen(port ?? process.env.PORT);
try {
await once(runningServer, "listening");
} catch (error) {
logger.warn("Starting server failed, shutting down...");
await closeServer(server);
// eslint-disable-next-line no-restricted-syntax -- Server startup
throw error;
}
const address = runningServer.address();
Iif (!address || typeof address === "string") {
// eslint-disable-next-line no-restricted-syntax -- Server startup
throw new Error("Unable to get address");
}
logger.info(`Express: Server started on port ${address.port}`);
return runningServer;
};
export const closeServer = async (
server: Server,
signal?: string,
): Promise<void> => {
logger.info(`Received signal to terminate${signal ? `: ${signal}` : ""}`);
const enableCronjobs =
config.server().onlyCronjobs ||
config.server().cronjobsAndBackendSameInstance;
if (enableCronjobs) {
stopCronJobs();
}
server.close();
logger.info("Server closed");
try {
await db.gracefulExit();
} catch (error) {
logger.error(error);
}
// Send buffered Sentry events before the process exits. The timeout leaves
// room for the transport's short first retry; an event already in the long
// second retry is abandoned rather than risking the k8s termination grace
// period. No-op when Sentry is not initialized (tests, local dev).
await flush(5000);
logger.info("Shutdown completed, bye");
};
|