1 import {
2 ContainerRegistrationKeys,
3 FeatureFlag,
4 isFileDisabled,
5 parseCorsOrigins,
6 } from "@medusajs/utils"
7 import cors, { CorsOptions } from "cors"
8 import type {
9 ErrorRequestHandler,
10 Express,
11 IRouter,
12 RequestHandler,
13 } from "express"
14 import type {
15 AdditionalDataValidatorRoute,
16 BodyParserConfigRoute,
17 MedusaNextFunction,
18 MedusaRequest,
19 MedusaResponse,
20 MiddlewareDescriptor,
21 MiddlewareFunction,
22 MiddlewareVerb,
23 RouteDescriptor,
24 RouteHandler,
25 } from "./types"
26
27 import { Logger, MedusaContainer } from "@medusajs/types"
28 import { join } from "path"
29 import { configManager } from "../config"
30 import { MiddlewareFileLoader } from "./middleware-file-loader"
31 import { applyLocale, authenticate, AuthType } from "./middlewares"
32 import { createBodyParserMiddlewaresStack } from "./middlewares/bodyparser"
33 import { wrapWithPoliciesCheck } from "./middlewares/check-permissions"
34 import { ensurePublishableApiKeyMiddleware } from "./middlewares/ensure-publishable-api-key"
35 import { errorHandler } from "./middlewares/error-handler"
36 import { RoutesFinder } from "./routes-finder"
37 import { RoutesLoader } from "./routes-loader"
38 import { RoutesSorter } from "./routes-sorter"
39 import { RestrictedFields } from "./utils/restricted-fields"
40 import { wrapHandler } from "./utils/wrap-handler"
41
42 export class ApiLoader {
43 /**
44 * Wrap the original route handler implementation for
45 * instrumentation.
46 */
47 static traceRoute?: (
48 handler: RouteHandler,
49 route: { route: string; method: string }
50 ) => RouteHandler
51
52 /**
53 * Wrap the original middleware handler implementation for
54 * instrumentation.
55 */
56 static traceMiddleware?: (
57 handler: RequestHandler | MiddlewareFunction,
58 route: { route: string; method?: string }
59 ) => RequestHandler | MiddlewareFunction
60
61 /**
62 * An express instance
63 * @private
64 */
65 readonly #app: Express
66
67 /**
68 * Path from where to load the routes from
69 * @private
70 */
71 readonly #sourceDirs: string[]
72
73 readonly #logger: Logger
74
75 constructor({
76 app,
77 sourceDir,
78 baseRestrictedFields = [],
79 storeRelationsLimit,
80 container,
81 }: {
82 app: Express
83 sourceDir: string | string[]
84 baseRestrictedFields?: string[]
85 storeRelationsLimit?: number
86 container: MedusaContainer
87 }) {
88 this.#app = app
89 this.#sourceDirs = Array.isArray(sourceDir) ? sourceDir : [sourceDir]
90 this.#assignRestrictedFields(
91 baseRestrictedFields ?? [],
92 storeRelationsLimit
93 )
94 this.#logger = container.resolve(ContainerRegistrationKeys.LOGGER)
95 }
96
97 /**
98 * Loads routes, middleware, bodyParserConfig routes, routes that have
99 * opted out for Auth and CORS and the error handler.
100 */
101 async #loadHttpResources() {
102 const routesLoader = new RoutesLoader()
103
104 const middlewareLoader = new MiddlewareFileLoader()
105
106 for (const dir of this.#sourceDirs) {
107 await routesLoader.scanDir(dir)
108 await middlewareLoader.scanDir(dir)
109 }
110
111 return {
112 routes: routesLoader.getRoutes(),
113 routesFinder: new RoutesFinder<RouteDescriptor>(),
114 middlewares: middlewareLoader.getMiddlewares(),
115 errorHandler: middlewareLoader.getErrorHandler() as
116 | ErrorRequestHandler
117 | undefined,
118 bodyParserConfigRoutes: middlewareLoader.getBodyParserConfigRoutes(),
119 additionalDataValidatorRoutes:
120 middlewareLoader.getAdditionalDataValidatorRoutes(),
121 }
122 }
123
124 /**
125 * Checks if a route file is disabled for a given matcher and method
126 * by trying to find the corresponding route file path
127 */
128 #isRouteFileDisabled(matcher: string | RegExp): boolean {
129 /**
130 * A regular expression matcher does not map to a single route file on the
131 * filesystem, so there is nothing to check for being disabled.
132 */
133 if (matcher instanceof RegExp) {
134 return false
135 }
136
137 const routePathSegments = matcher
138 .split("/")
139 .filter(Boolean)
140 .map((segment) => {
141 if (segment.startsWith(":")) {
142 return `[${segment.slice(1)}]`
143 }
144 return segment
145 })
146
147 for (const sourceDir of this.#sourceDirs) {
148 for (const ext of [".ts", ".js"]) {
149 const routeFilePath = join(
150 sourceDir,
151 ...routePathSegments,
152 `route${ext}`
153 )
154
155 if (isFileDisabled(routeFilePath)) {
156 return true
157 }
158 }
159 }
160
161 return false
162 }
163
164 /**
165 * Registers a middleware or a route handler with Express
166 */
167 #registerExpressHandler(
168 route: MiddlewareDescriptor | RouteDescriptor | RouteDescriptor
169 ) {
170 if ("isRoute" in route) {
171 this.#logger.debug(`registering route ${route.method} ${route.matcher}`)
172 const handler = ApiLoader.traceRoute
173 ? ApiLoader.traceRoute(route.handler, {
174 route: route.matcher,
175 method: route.method,
176 })
177 : route.handler
178
179 this.#app[route.method.toLowerCase()](route.matcher, wrapHandler(handler))
180
181 return
182 }
183
184 const isRbacEnabled = FeatureFlag.isFeatureEnabled("rbac")
185 if (!route.methods) {
186 this.#logger.debug(`registering global middleware for ${route.matcher}`)
187
188 // Wrap with permission check if policies are defined
189 let handlerToUse = route.handler
190 if (route.policies && isRbacEnabled) {
191 handlerToUse = wrapWithPoliciesCheck(route.handler, route.policies)
192 }
193
194 const handler = ApiLoader.traceMiddleware
195 ? (ApiLoader.traceMiddleware(handlerToUse, {
196 route: String(route.matcher),
197 }) as RequestHandler)
198 : (handlerToUse as RequestHandler)
199
200 this.#app.use(route.matcher, wrapHandler(handler))
201 return
202 }
203
204 const methods = Array.isArray(route.methods)
205 ? route.methods
206 : [route.methods]
207 methods.forEach((method) => {
208 const isDisabled = this.#isRouteFileDisabled(route.matcher)
209 if (isDisabled) {
210 this.#logger.debug(
211 `skipping disabled route middleware registration for ${method} ${route.matcher}`
212 )
213 return
214 }
215
216 this.#logger.debug(
217 `registering route middleware ${method} ${route.matcher}`
218 )
219
220 let handlerToUse = route.handler
221 if (route.policies && isRbacEnabled) {
222 handlerToUse = wrapWithPoliciesCheck(route.handler, route.policies)
223 }
224
225 const handler = ApiLoader.traceMiddleware
226 ? (ApiLoader.traceMiddleware(wrapHandler(handlerToUse), {
227 route: String(route.matcher),
228 method: method,
229 }) as RequestHandler)
230 : wrapHandler(handlerToUse)
231
232 this.#app[method.toLowerCase()](route.matcher, handler)
233 })
234 }
235
236 /**
237 * Registers the middleware for restricted fields
238 */
239 #assignRestrictedFields(
240 baseRestrictedFields: string[],
241 storeRelationsLimit?: number
242 ) {
243 this.#app.use(((
244 req: MedusaRequest,
245 _: MedusaResponse,
246 next: MedusaNextFunction
247 ) => {
248 req.allowed = []
249 next()
250 }) as unknown as RequestHandler)
251
252 this.#app.use("/store", ((
253 req: MedusaRequest,
254 _: MedusaResponse,
255 next: MedusaNextFunction
256 ) => {
257 req.restrictedFields = new RestrictedFields()
258 req.restrictedFields.add(baseRestrictedFields)
259 req.storeRelationsLimit = storeRelationsLimit
260 next()
261 }) as unknown as RequestHandler)
262
263 this.#app.use("/admin", ((
264 req: MedusaRequest,
265 _: MedusaResponse,
266 next: MedusaNextFunction
267 ) => {
268 req.restrictedFields = new RestrictedFields()
269 next()
270 }) as unknown as RequestHandler)
271 }
272
273 /**
274 * Creates the options for the Cors middleware
275 */
276 #createCorsOptions(origin: string): CorsOptions {
277 return {
278 origin: parseCorsOrigins(origin),
279 credentials: true,
280 preflightContinue: false,
281 }
282 }
283
284 /**
285 * Assigns global cors middleware for a given prefix
286 */
287 #applyCorsMiddleware(
288 routesFinder: RoutesFinder<RouteDescriptor>,
289 namespace: string,
290 toggleKey:
291 | "shouldAppendAdminCors"
292 | "shouldAppendAuthCors"
293 | "shouldAppendStoreCors",
294 corsOptions: CorsOptions
295 ) {
296 const logger = this.#logger
297 const corsFn = cors(corsOptions)
298 const corsMiddleware: RequestHandler = function corsMiddleware(
299 req,
300 res,
301 next
302 ) {
303 let method: string = req.method
304 if (req.method === "OPTIONS") {
305 method = req.headers["access-control-request-method"] ?? req.method
306 }
307
308 const path = `${namespace}${req.path}`
309 const matchingRoute = routesFinder.find(path, method as MiddlewareVerb)
310 if (matchingRoute && matchingRoute[toggleKey] === true) {
311 return corsFn(req, res, next)
312 }
313
314 logger.debug(`Skipping CORS middleware ${req.method} ${path}`)
315 return next()
316 }
317
318 this.#app.use(
319 namespace,
320 ApiLoader.traceMiddleware
321 ? (ApiLoader.traceMiddleware(corsMiddleware, {
322 route: namespace,
323 }) as RequestHandler)
324 : corsMiddleware
325 )
326 }
327
328 /**
329 * Applies the route middleware on a route. Encapsulates the logic
330 * needed to pass the middleware via the trace calls
331 */
332 #applyAuthMiddleware(
333 routesFinder: RoutesFinder<RouteDescriptor>,
334 namespace: string,
335 actorType: string | string[],
336 authType: AuthType | AuthType[],
337 options?: { allowUnauthenticated?: boolean; allowUnregistered?: boolean }
338 ) {
339 const logger = this.#logger
340 logger.debug(`Registering auth middleware for prefix ${namespace}`)
341
342 const originalFn = authenticate(actorType, authType, options)
343 const authMiddleware: RequestHandler = function authMiddleware(
344 req,
345 res,
346 next
347 ) {
348 const path = `${namespace}${req.path}`
349 const matchingRoute = routesFinder.find(
350 path,
351 req.method as MiddlewareVerb
352 )
353 if (matchingRoute && matchingRoute.optedOutOfAuth) {
354 logger.debug(`Skipping auth ${req.method} ${path}`)
355 return next()
356 }
357
358 logger.debug(`Authenticating route ${req.method} ${path}`)
359 return originalFn(req, res, next)
360 }
361
362 this.#app.use(
363 namespace,
364 ApiLoader.traceMiddleware
365 ? (ApiLoader.traceMiddleware(authMiddleware, {
366 route: namespace,
367 }) as RequestHandler)
368 : authMiddleware
369 )
370 }
371
372 /**
373 * Apply the most specific body parser middleware to the router
374 */
375 #applyBodyParserMiddleware(
376 namespace: string,
377 routesFinder: RoutesFinder<BodyParserConfigRoute>
378 ): void {
379 this.#logger.debug(
380 `Registering bodyparser middleware for prefix ${namespace}`
381 )
382 this.#app.use(
383 namespace,
384 createBodyParserMiddlewaresStack(
385 namespace,
386 routesFinder,
387 ApiLoader.traceMiddleware
388 )
389 )
390 }
391
392 /**
393 * Applies the route middleware on a route. Encapsulates the logic
394 * needed to pass the middleware via the trace calls
395 */
396 #assignAdditionalDataValidator(
397 namespace: string,
398 routesFinder: RoutesFinder<AdditionalDataValidatorRoute>
399 ) {
400 const logger = this.#logger
401 logger.debug(
402 `Registering assignAdditionalDataValidator middleware for prefix ${namespace}`
403 )
404
405 const additionalDataValidator = function additionalDataValidator(
406 req: MedusaRequest,
407 _: MedusaResponse,
408 next: MedusaNextFunction
409 ) {
410 const matchingRoute = routesFinder.find(
411 req.path,
412 req.method as MiddlewareVerb
413 )
414 if (matchingRoute && matchingRoute.validator) {
415 logger.debug(
416 `Using validator to validate additional data on ${req.method} ${req.path}`
417 )
418 req.additionalDataValidator = matchingRoute.validator
419 }
420 return next()
421 }
422
423 this.#app.use(
424 namespace,
425 ApiLoader.traceMiddleware
426 ? (ApiLoader.traceMiddleware(additionalDataValidator, {
427 route: namespace,
428 }) as RequestHandler)
429 : (additionalDataValidator as RequestHandler)
430 )
431 }
432
433 /**
434 * Applies the middleware to authenticate the headers to contain
435 * a `x-publishable-key` header
436 */
437 #applyStorePublishableKeyMiddleware(namespace: string) {
438 this.#logger.debug(
439 `Registering publishable key middleware for namespace ${namespace}`
440 )
441 const middleware = ApiLoader.traceMiddleware
442 ? ApiLoader.traceMiddleware(ensurePublishableApiKeyMiddleware, {
443 route: namespace,
444 })
445 : ensurePublishableApiKeyMiddleware
446
447 this.#app.use(namespace, middleware as RequestHandler)
448 }
449
450 #applyLocaleMiddleware(namespace: string) {
451 this.#logger.debug(
452 `Registering locale middleware for namespace ${namespace}`
453 )
454 const middleware = ApiLoader.traceMiddleware
455 ? ApiLoader.traceMiddleware(applyLocale, {
456 route: namespace,
457 })
458 : applyLocale
459 this.#app.use(namespace, middleware as RequestHandler)
460 }
461
462 async load() {
463 if (FeatureFlag.isFeatureEnabled("backend_hmr")) {
464 ;(global as any).__MEDUSA_HMR_API_LOADER__ = this
465 }
466
467 const {
468 errorHandler: sourceErrorHandler,
469 middlewares,
470 routes,
471 routesFinder,
472 bodyParserConfigRoutes,
473 additionalDataValidatorRoutes,
474 } = await this.#loadHttpResources()
475
476 /**
477 * Parse request body on all the requests and use the routes finder
478 * to pick the best matching config for the given route.
479 */
480 const bodyParserRoutesFinder = new RoutesFinder<BodyParserConfigRoute>(
481 new RoutesSorter(bodyParserConfigRoutes).sort([
482 "static",
483 "params",
484 "regex",
485 "wildcard",
486 "global",
487 ])
488 )
489 this.#applyBodyParserMiddleware("/", bodyParserRoutesFinder)
490
491 /**
492 * Use the routes finder to pick the additional data validator
493 * to be applied on the current request
494 */
495 if (additionalDataValidatorRoutes.length) {
496 const additionalDataValidatorRoutesFinder =
497 new RoutesFinder<AdditionalDataValidatorRoute>(
498 new RoutesSorter(additionalDataValidatorRoutes).sort([
499 "static",
500 "params",
501 "regex",
502 "wildcard",
503 "global",
504 ])
505 )
506 this.#assignAdditionalDataValidator(
507 "/",
508 additionalDataValidatorRoutesFinder
509 )
510 }
511
512 /**
513 * CORS and Auth setup for admin routes
514 */
515 this.#applyCorsMiddleware(
516 routesFinder,
517 "/admin",
518 "shouldAppendAdminCors",
519 this.#createCorsOptions(configManager.config.projectConfig.http.adminCors)
520 )
521 this.#applyAuthMiddleware(routesFinder, "/admin", "user", [
522 "bearer",
523 "session",
524 "api-key",
525 ])
526
527 this.#applyCorsMiddleware(
528 routesFinder,
529 "/store",
530 "shouldAppendStoreCors",
531 this.#createCorsOptions(configManager.config.projectConfig.http.storeCors)
532 )
533 /**
534 * Publishable key check, CORS and auth setup for store routes.
535 */
536 this.#applyStorePublishableKeyMiddleware("/store")
537
538 this.#applyLocaleMiddleware("/store")
539
540 this.#applyAuthMiddleware(
541 routesFinder,
542 "/store",
543 "customer",
544 ["bearer", "session"],
545 {
546 allowUnauthenticated: true,
547 }
548 )
549
550 /**
551 * Apply CORS middleware for "/auth" routes
552 */
553 this.#applyCorsMiddleware(
554 routesFinder,
555 "/auth",
556 "shouldAppendAuthCors",
557 this.#createCorsOptions(configManager.config.projectConfig.http.authCors)
558 )
559
560 const collectionToSort = ([] as (MiddlewareDescriptor | RouteDescriptor)[])
561 .concat(middlewares)
562 .concat(routes)
563
564 const sortedRoutes = new RoutesSorter(collectionToSort).sort()
565 sortedRoutes.forEach((route) => {
566 if ("isRoute" in route) {
567 routesFinder.add(route)
568 }
569 this.#registerExpressHandler(route)
570 })
571
572 /**
573 * Registering error handler as the final handler
574 */
575 this.#app.use(sourceErrorHandler ?? errorHandler())
576 }
577
578 /**
579 * Clear all API resources registered by this loader
580 * This removes all routes and middleware added after the initial stack state
581 * Used by HMR to reset the API state before reloading
582 */
583 clearAllResources() {
584 const router = this.#app._router as IRouter
585 const initialStackLength =
586 (global as any).__MEDUSA_HMR_INITIAL_STACK_LENGTH__ ?? 0
587
588 if (router && router.stack) {
589 router.stack.splice(initialStackLength)
590 }
591 }
592 }