1 import { MedusaContainer } from "@medusajs/framework/types"
2 import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
3 import { dynamicImport } from "@medusajs/utils"
4 import compression from "compression"
5 import createStore from "connect-redis"
6 import cookieParser from "cookie-parser"
7 import express, { Express, RequestHandler } from "express"
8 import session from "express-session"
9 import Redis from "ioredis"
10 import morgan from "morgan"
11 import path from "path"
12 import { configManager } from "../config"
13 import { MedusaRequest, MedusaResponse } from "./types"
14 import {
15 compressionOptions,
16 shouldCompressResponse,
17 } from "./utils/http-compression"
18
19 const NOISY_ENDPOINTS_CHUNKS = ["@fs", "@id", "@vite", "@react", "node_modules"]
20
21 const isHealthCheck = (req: MedusaRequest) => req.path === "/health"
22
23 /**
24 * Resolves the `sameSite` and `secure` flags used for the session cookie.
25 *
26 * In production/staging the cookie must be `Secure`, but `sameSite` is kept
27 * at `"lax"` rather than `"none"` to prevent CSRF: `SameSite=none` allows the
28 * cookie to be attached to cross-site POSTs from a malicious page, which is
29 * the root cause of GHSA-jhvc-qx3m-6r3q.
30 */
31 export function resolveSessionCookieSecurity({
32 isProduction,
33 isStaging,
34 }: {
35 isProduction: boolean
36 isStaging: boolean
37 }): { sameSite: "lax" | boolean; secure: boolean } {
38 if (isProduction || isStaging) {
39 return { sameSite: "lax", secure: true }
40 }
41 return { sameSite: false, secure: false }
42 }
43
44 export async function expressLoader({
45 app,
46 container,
47 }: {
48 app: Express
49 container: MedusaContainer
50 }): Promise<{
51 app: Express
52 shutdown: () => Promise<void>
53 }> {
54 const baseDir = configManager.baseDir
55 const configModule = configManager.config
56 const isProduction = configManager.isProduction
57 const NODE_ENV = process.env.NODE_ENV || "development"
58 const IS_DEV = NODE_ENV.startsWith("dev")
59 const isStaging = NODE_ENV === "staging"
60 const isTest = NODE_ENV === "test"
61 const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
62
63 const { sameSite, secure } = resolveSessionCookieSecurity({
64 isProduction,
65 isStaging,
66 })
67
68 const { http, sessionOptions, cookieOptions } = configModule.projectConfig
69 const sessionOpts = {
70 name: sessionOptions?.name ?? "connect.sid",
71 resave: sessionOptions?.resave ?? true,
72 rolling: sessionOptions?.rolling ?? false,
73 saveUninitialized: sessionOptions?.saveUninitialized ?? false,
74 proxy: true,
75 secret: sessionOptions?.secret ?? http?.cookieSecret,
76 cookie: {
77 sameSite,
78 secure,
79 maxAge: sessionOptions?.ttl ?? 10 * 60 * 60 * 1000,
80 ...cookieOptions,
81 },
82 store: null,
83 }
84
85 let redisClient: Redis
86
87 if (configModule?.projectConfig.sessionOptions?.dynamodbOptions) {
88 const storeFactory = await dynamicImport("connect-dynamodb")
89 const client = await dynamicImport("@aws-sdk/client-dynamodb")
90 const DynamoDBStore = storeFactory({ session })
91 sessionOpts.store = new DynamoDBStore({
92 ...configModule.projectConfig.sessionOptions.dynamodbOptions,
93 client: new client.DynamoDBClient(
94 configModule.projectConfig.sessionOptions.dynamodbOptions.clientOptions
95 ),
96 })
97 } else if (configModule?.projectConfig?.redisUrl) {
98 const RedisStore = createStore(session)
99 redisClient = new Redis(
100 configModule.projectConfig.redisUrl,
101 configModule.projectConfig.redisOptions ?? {}
102 )
103 sessionOpts.store = new RedisStore({
104 client: redisClient,
105 prefix: `${configModule?.projectConfig?.redisPrefix ?? ""}sess:`,
106 })
107 }
108
109 app.set("trust proxy", 1)
110
111 /**
112 * Register the HTTP compression middleware when it's enabled through
113 * `projectConfig.http.compression`. It has to be registered before the
114 * route handlers so it can compress the responses they produce. The
115 * `filter` additionally skips compression for requests that opt out via
116 * the `x-no-compression` header.
117 */
118 const httpCompressionOptions = compressionOptions(configModule.projectConfig)
119 if (httpCompressionOptions.enabled) {
120 // `compression` ships its own copy of the Express types, so both its
121 // filter input and its middleware output have to be bridged to the
122 // Express types used here. `shouldCompressResponse` additionally reads
123 // `req.scope` off the Medusa request, which only exists at runtime, hence
124 // the casts through `unknown`.
125 const compressionMiddleware = compression({
126 ...httpCompressionOptions,
127 filter:
128 shouldCompressResponse as unknown as compression.CompressionFilter,
129 }) as unknown as RequestHandler
130
131 app.use(compressionMiddleware)
132 }
133
134 /**
135 * Method to skip logging HTTP requests. We skip in test environment
136 * and also exclude files served by vite during development
137 */
138 function shouldSkipHttpLog(req: MedusaRequest, res: MedusaResponse) {
139 return (
140 isTest ||
141 isHealthCheck(req) ||
142 NOISY_ENDPOINTS_CHUNKS.some((chunk) => req.url.includes(chunk)) ||
143 !logger.shouldLog("http")
144 )
145 }
146
147 let loggingMiddleware: RequestHandler
148
149 /**
150 * The middleware to use for logging. We write the log messages
151 * using winston, but rely on morgan to hook into HTTP requests
152 */
153 if (!IS_DEV) {
154 const jsonFormat = (tokens, req, res) => {
155 const result = {
156 level: "http",
157 // client ip
158 client_ip: req.ip || "-",
159
160 // Request ID can be correlated with other logs (like error reports)
161 request_id: req.requestId || "-",
162
163 // Standard HTTP request properties
164 http_version: tokens["http-version"](req, res),
165 method: tokens.method(req, res),
166 path: tokens.url(req, res),
167
168 // Response details
169 status: Number(tokens.status(req, res)),
170 response_size: tokens.res(req, res, "content-length") || 0,
171 request_size: tokens.req(req, res, "content-length") || 0,
172 duration: Number(tokens["response-time"](req, res)),
173
174 // Useful headers that might help in debugging or tracing
175 referrer: tokens.referrer(req, res) || "-",
176 user_agent: tokens["user-agent"](req, res),
177
178 timestamp: new Date().toISOString(),
179 }
180
181 return JSON.stringify(result)
182 }
183
184 loggingMiddleware = morgan(jsonFormat, {
185 skip: shouldSkipHttpLog,
186 })
187 } else {
188 loggingMiddleware = morgan(
189 ":method :url ← :referrer (:status) - :response-time ms",
190 {
191 skip: shouldSkipHttpLog,
192 stream: {
193 write: (message: string) => logger.http(message.trim()),
194 },
195 }
196 )
197 }
198
199 app.use(loggingMiddleware)
200 app.use(cookieParser())
201 app.use(session(sessionOpts))
202
203 // Currently we don't allow configuration of static files, but this can be revisited as needed.
204 app.use("/static", express.static(path.join(baseDir, "static")))
205
206 const shutdown = async () => {
207 redisClient?.disconnect()
208 }
209
210 return { app, shutdown }
211 }