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 | 42x 247x 247x 247x 247x 247x 247x 247x 5x 247x 247x 247x 1x 1x 1x 247x 247x 247x 247x 247x 247x 5x 5x 247x 247x 247x 247x 247x 8x 23x 8x 7x 7x 1x 247x 247x 1x 1x 1x 247x 247x 247x 247x 247x 247x 247x 247x 42x 242x 242x 242x 242x 242x 242x 242x 242x 242x | 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 { 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 }));
}
// Accepts raw body
app.use(sentryRoutes);
// Parse body and populate req.body - only accepts JSON
app.use(express.json({ limit: "1000kb", type: "*/*" })); // limit: 1MB
app.use((err: Error, _req: Request, res: Response, next: NextFunction) => {
Eif ("status" in err && err.status === 400) {
logger.warn(`Invalid request: ${err.message}`);
return res.sendStatus(400);
}
next(err);
});
app.use("/api", allowCORS);
app.use("/auth", allowCORS);
app.use(wwwRedirect);
app.use(apiRoutes);
// Set static path
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",
);
};
const serveIndexAndApi =
!config.server().onlyCronjobs ||
config.server().cronjobsAndBackendSameInstance;
Eif (serveIndexAndApi) {
// Set compression
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);
// Error handler
app.use((err: Error, _req: Request, res: Response, next: NextFunction) => {
// Delegate to the default Express error handler, when the headers have already been sent to the client
// For example, if error is encountered while streaming the response to the client
// Express default error handler closes the connection and fails the request
// https://expressjs.com/en/guide/error-handling.html
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;
Iif (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");
};
|