express.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. var {
  2. _optionalChain
  3. } = require('@sentry/utils');
  4. Object.defineProperty(exports, '__esModule', { value: true });
  5. const core = require('@sentry/core');
  6. const utils = require('@sentry/utils');
  7. const debugBuild = require('../../common/debug-build.js');
  8. const nodeUtils = require('./utils/node-utils.js');
  9. /* eslint-disable max-lines */
  10. /**
  11. * Express integration
  12. *
  13. * Provides an request and error handler for Express framework as well as tracing capabilities
  14. */
  15. class Express {
  16. /**
  17. * @inheritDoc
  18. */
  19. static __initStatic() {this.id = 'Express';}
  20. /**
  21. * @inheritDoc
  22. */
  23. /**
  24. * Express App instance
  25. */
  26. /**
  27. * @inheritDoc
  28. */
  29. constructor(options = {}) {
  30. this.name = Express.id;
  31. this._router = options.router || options.app;
  32. this._methods = (Array.isArray(options.methods) ? options.methods : []).concat('use');
  33. }
  34. /**
  35. * @inheritDoc
  36. */
  37. setupOnce(_, getCurrentHub) {
  38. if (!this._router) {
  39. debugBuild.DEBUG_BUILD && utils.logger.error('ExpressIntegration is missing an Express instance');
  40. return;
  41. }
  42. if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) {
  43. debugBuild.DEBUG_BUILD && utils.logger.log('Express Integration is skipped because of instrumenter configuration.');
  44. return;
  45. }
  46. instrumentMiddlewares(this._router, this._methods);
  47. instrumentRouter(this._router );
  48. }
  49. }Express.__initStatic();
  50. /**
  51. * Wraps original middleware function in a tracing call, which stores the info about the call as a span,
  52. * and finishes it once the middleware is done invoking.
  53. *
  54. * Express middlewares have 3 various forms, thus we have to take care of all of them:
  55. * // sync
  56. * app.use(function (req, res) { ... })
  57. * // async
  58. * app.use(function (req, res, next) { ... })
  59. * // error handler
  60. * app.use(function (err, req, res, next) { ... })
  61. *
  62. * They all internally delegate to the `router[method]` of the given application instance.
  63. */
  64. // eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any
  65. function wrap(fn, method) {
  66. const arity = fn.length;
  67. switch (arity) {
  68. case 2: {
  69. return function ( req, res) {
  70. const transaction = res.__sentry_transaction;
  71. if (transaction) {
  72. // eslint-disable-next-line deprecation/deprecation
  73. const span = transaction.startChild({
  74. description: fn.name,
  75. op: `middleware.express.${method}`,
  76. origin: 'auto.middleware.express',
  77. });
  78. res.once('finish', () => {
  79. span.end();
  80. });
  81. }
  82. return fn.call(this, req, res);
  83. };
  84. }
  85. case 3: {
  86. return function (
  87. req,
  88. res,
  89. next,
  90. ) {
  91. const transaction = res.__sentry_transaction;
  92. // eslint-disable-next-line deprecation/deprecation
  93. const span = _optionalChain([transaction, 'optionalAccess', _2 => _2.startChild, 'call', _3 => _3({
  94. description: fn.name,
  95. op: `middleware.express.${method}`,
  96. origin: 'auto.middleware.express',
  97. })]);
  98. fn.call(this, req, res, function ( ...args) {
  99. _optionalChain([span, 'optionalAccess', _4 => _4.end, 'call', _5 => _5()]);
  100. next.call(this, ...args);
  101. });
  102. };
  103. }
  104. case 4: {
  105. return function (
  106. err,
  107. req,
  108. res,
  109. next,
  110. ) {
  111. const transaction = res.__sentry_transaction;
  112. // eslint-disable-next-line deprecation/deprecation
  113. const span = _optionalChain([transaction, 'optionalAccess', _6 => _6.startChild, 'call', _7 => _7({
  114. description: fn.name,
  115. op: `middleware.express.${method}`,
  116. origin: 'auto.middleware.express',
  117. })]);
  118. fn.call(this, err, req, res, function ( ...args) {
  119. _optionalChain([span, 'optionalAccess', _8 => _8.end, 'call', _9 => _9()]);
  120. next.call(this, ...args);
  121. });
  122. };
  123. }
  124. default: {
  125. throw new Error(`Express middleware takes 2-4 arguments. Got: ${arity}`);
  126. }
  127. }
  128. }
  129. /**
  130. * Takes all the function arguments passed to the original `app` or `router` method, eg. `app.use` or `router.use`
  131. * and wraps every function, as well as array of functions with a call to our `wrap` method.
  132. * We have to take care of the arrays as well as iterate over all of the arguments,
  133. * as `app.use` can accept middlewares in few various forms.
  134. *
  135. * app.use([<path>], <fn>)
  136. * app.use([<path>], <fn>, ...<fn>)
  137. * app.use([<path>], ...<fn>[])
  138. */
  139. function wrapMiddlewareArgs(args, method) {
  140. return args.map((arg) => {
  141. if (typeof arg === 'function') {
  142. return wrap(arg, method);
  143. }
  144. if (Array.isArray(arg)) {
  145. return arg.map((a) => {
  146. if (typeof a === 'function') {
  147. return wrap(a, method);
  148. }
  149. return a;
  150. });
  151. }
  152. return arg;
  153. });
  154. }
  155. /**
  156. * Patches original router to utilize our tracing functionality
  157. */
  158. function patchMiddleware(router, method) {
  159. const originalCallback = router[method];
  160. router[method] = function (...args) {
  161. return originalCallback.call(this, ...wrapMiddlewareArgs(args, method));
  162. };
  163. return router;
  164. }
  165. /**
  166. * Patches original router methods
  167. */
  168. function instrumentMiddlewares(router, methods = []) {
  169. methods.forEach((method) => patchMiddleware(router, method));
  170. }
  171. /**
  172. * Patches the prototype of Express.Router to accumulate the resolved route
  173. * if a layer instance's `match` function was called and it returned a successful match.
  174. *
  175. * @see https://github.com/expressjs/express/blob/master/lib/router/index.js
  176. *
  177. * @param appOrRouter the router instance which can either be an app (i.e. top-level) or a (nested) router.
  178. */
  179. function instrumentRouter(appOrRouter) {
  180. // This is how we can distinguish between app and routers
  181. const isApp = 'settings' in appOrRouter;
  182. // In case the app's top-level router hasn't been initialized yet, we have to do it now
  183. if (isApp && appOrRouter._router === undefined && appOrRouter.lazyrouter) {
  184. appOrRouter.lazyrouter();
  185. }
  186. const router = isApp ? appOrRouter._router : appOrRouter;
  187. if (!router) {
  188. /*
  189. If we end up here, this means likely that this integration is used with Express 3 or Express 5.
  190. For now, we don't support these versions (3 is very old and 5 is still in beta). To support Express 5,
  191. we'd need to make more changes to the routing instrumentation because the router is no longer part of
  192. the Express core package but maintained in its own package. The new router has different function
  193. signatures and works slightly differently, demanding more changes than just taking the router from
  194. `app.router` instead of `app._router`.
  195. @see https://github.com/pillarjs/router
  196. TODO: Proper Express 5 support
  197. */
  198. debugBuild.DEBUG_BUILD && utils.logger.debug('Cannot instrument router for URL Parameterization (did not find a valid router).');
  199. debugBuild.DEBUG_BUILD && utils.logger.debug('Routing instrumentation is currently only supported in Express 4.');
  200. return;
  201. }
  202. const routerProto = Object.getPrototypeOf(router) ;
  203. const originalProcessParams = routerProto.process_params;
  204. routerProto.process_params = function process_params(
  205. layer,
  206. called,
  207. req,
  208. res,
  209. done,
  210. ) {
  211. // Base case: We're in the first part of the URL (thus we start with the root '/')
  212. if (!req._reconstructedRoute) {
  213. req._reconstructedRoute = '';
  214. }
  215. // If the layer's partial route has params, is a regex or an array, the route is stored in layer.route.
  216. const { layerRoutePath, isRegex, isArray, numExtraSegments } = getLayerRoutePathInfo(layer);
  217. if (layerRoutePath || isRegex || isArray) {
  218. req._hasParameters = true;
  219. }
  220. // Otherwise, the hardcoded path (i.e. a partial route without params) is stored in layer.path
  221. let partialRoute;
  222. if (layerRoutePath) {
  223. partialRoute = layerRoutePath;
  224. } else {
  225. /**
  226. * prevent duplicate segment in _reconstructedRoute param if router match multiple routes before final path
  227. * example:
  228. * original url: /api/v1/1234
  229. * prevent: /api/api/v1/:userId
  230. * router structure
  231. * /api -> middleware
  232. * /api/v1 -> middleware
  233. * /1234 -> endpoint with param :userId
  234. * final _reconstructedRoute is /api/v1/:userId
  235. */
  236. partialRoute = preventDuplicateSegments(req.originalUrl, req._reconstructedRoute, layer.path) || '';
  237. }
  238. // Normalize the partial route so that it doesn't contain leading or trailing slashes
  239. // and exclude empty or '*' wildcard routes.
  240. // The exclusion of '*' routes is our best effort to not "pollute" the transaction name
  241. // with interim handlers (e.g. ones that check authentication or do other middleware stuff).
  242. // We want to end up with the parameterized URL of the incoming request without any extraneous path segments.
  243. const finalPartialRoute = partialRoute
  244. .split('/')
  245. .filter(segment => segment.length > 0 && (isRegex || isArray || !segment.includes('*')))
  246. .join('/');
  247. // If we found a valid partial URL, we append it to the reconstructed route
  248. if (finalPartialRoute && finalPartialRoute.length > 0) {
  249. // If the partial route is from a regex route, we append a '/' to close the regex
  250. req._reconstructedRoute += `/${finalPartialRoute}${isRegex ? '/' : ''}`;
  251. }
  252. // Now we check if we are in the "last" part of the route. We determine this by comparing the
  253. // number of URL segments from the original URL to that of our reconstructed parameterized URL.
  254. // If we've reached our final destination, we update the transaction name.
  255. const urlLength = utils.getNumberOfUrlSegments(utils.stripUrlQueryAndFragment(req.originalUrl || '')) + numExtraSegments;
  256. const routeLength = utils.getNumberOfUrlSegments(req._reconstructedRoute);
  257. if (urlLength === routeLength) {
  258. if (!req._hasParameters) {
  259. if (req._reconstructedRoute !== req.originalUrl) {
  260. req._reconstructedRoute = req.originalUrl ? utils.stripUrlQueryAndFragment(req.originalUrl) : req.originalUrl;
  261. }
  262. }
  263. const transaction = res.__sentry_transaction;
  264. const attributes = (transaction && core.spanToJSON(transaction).data) || {};
  265. if (transaction && attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] !== 'custom') {
  266. // If the request URL is '/' or empty, the reconstructed route will be empty.
  267. // Therefore, we fall back to setting the final route to '/' in this case.
  268. const finalRoute = req._reconstructedRoute || '/';
  269. const [name, source] = utils.extractPathForTransaction(req, { path: true, method: true, customRoute: finalRoute });
  270. transaction.updateName(name);
  271. transaction.setAttribute(core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source);
  272. }
  273. }
  274. return originalProcessParams.call(this, layer, called, req, res, done);
  275. };
  276. }
  277. /**
  278. * Recreate layer.route.path from layer.regexp and layer.keys.
  279. * Works until express.js used package path-to-regexp@0.1.7
  280. * or until layer.keys contain offset attribute
  281. *
  282. * @param layer the layer to extract the stringified route from
  283. *
  284. * @returns string in layer.route.path structure 'router/:pathParam' or undefined
  285. */
  286. const extractOriginalRoute = (
  287. path,
  288. regexp,
  289. keys,
  290. ) => {
  291. if (!path || !regexp || !keys || Object.keys(keys).length === 0 || !_optionalChain([keys, 'access', _10 => _10[0], 'optionalAccess', _11 => _11.offset])) {
  292. return undefined;
  293. }
  294. const orderedKeys = keys.sort((a, b) => a.offset - b.offset);
  295. // add d flag for getting indices from regexp result
  296. // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- regexp comes from express.js
  297. const pathRegex = new RegExp(regexp, `${regexp.flags}d`);
  298. /**
  299. * use custom type cause of TS error with missing indices in RegExpExecArray
  300. */
  301. const execResult = pathRegex.exec(path) ;
  302. if (!execResult || !execResult.indices) {
  303. return undefined;
  304. }
  305. /**
  306. * remove first match from regex cause contain whole layer.path
  307. */
  308. const [, ...paramIndices] = execResult.indices;
  309. if (paramIndices.length !== orderedKeys.length) {
  310. return undefined;
  311. }
  312. let resultPath = path;
  313. let indexShift = 0;
  314. /**
  315. * iterate param matches from regexp.exec
  316. */
  317. paramIndices.forEach((item, index) => {
  318. /** check if offsets is define because in some cases regex d flag returns undefined */
  319. if (item) {
  320. const [startOffset, endOffset] = item;
  321. /**
  322. * isolate part before param
  323. */
  324. const substr1 = resultPath.substring(0, startOffset - indexShift);
  325. /**
  326. * define paramName as replacement in format :pathParam
  327. */
  328. const replacement = `:${orderedKeys[index].name}`;
  329. /**
  330. * isolate part after param
  331. */
  332. const substr2 = resultPath.substring(endOffset - indexShift);
  333. /**
  334. * recreate original path but with param replacement
  335. */
  336. resultPath = substr1 + replacement + substr2;
  337. /**
  338. * calculate new index shift after resultPath was modified
  339. */
  340. indexShift = indexShift + (endOffset - startOffset - replacement.length);
  341. }
  342. });
  343. return resultPath;
  344. };
  345. /**
  346. * Extracts and stringifies the layer's route which can either be a string with parameters (`users/:id`),
  347. * a RegEx (`/test/`) or an array of strings and regexes (`['/path1', /\/path[2-5]/, /path/:id]`). Additionally
  348. * returns extra information about the route, such as if the route is defined as regex or as an array.
  349. *
  350. * @param layer the layer to extract the stringified route from
  351. *
  352. * @returns an object containing the stringified route, a flag determining if the route was a regex
  353. * and the number of extra segments to the matched path that are additionally in the route,
  354. * if the route was an array (defaults to 0).
  355. */
  356. function getLayerRoutePathInfo(layer) {
  357. let lrp = _optionalChain([layer, 'access', _12 => _12.route, 'optionalAccess', _13 => _13.path]);
  358. const isRegex = utils.isRegExp(lrp);
  359. const isArray = Array.isArray(lrp);
  360. if (!lrp) {
  361. // parse node.js major version
  362. // Next.js will complain if we directly use `proces.versions` here because of edge runtime.
  363. const [major] = (utils.GLOBAL_OBJ ).process.versions.node.split('.').map(Number);
  364. // allow call extractOriginalRoute only if node version support Regex d flag, node 16+
  365. if (major >= 16) {
  366. /**
  367. * If lrp does not exist try to recreate original layer path from route regexp
  368. */
  369. lrp = extractOriginalRoute(layer.path, layer.regexp, layer.keys);
  370. }
  371. }
  372. if (!lrp) {
  373. return { isRegex, isArray, numExtraSegments: 0 };
  374. }
  375. const numExtraSegments = isArray
  376. ? Math.max(getNumberOfArrayUrlSegments(lrp ) - utils.getNumberOfUrlSegments(layer.path || ''), 0)
  377. : 0;
  378. const layerRoutePath = getLayerRoutePathString(isArray, lrp);
  379. return { layerRoutePath, isRegex, isArray, numExtraSegments };
  380. }
  381. /**
  382. * Returns the number of URL segments in an array of routes
  383. *
  384. * Example: ['/api/test', /\/api\/post[0-9]/, '/users/:id/details`] -> 7
  385. */
  386. function getNumberOfArrayUrlSegments(routesArray) {
  387. return routesArray.reduce((accNumSegments, currentRoute) => {
  388. // array members can be a RegEx -> convert them toString
  389. return accNumSegments + utils.getNumberOfUrlSegments(currentRoute.toString());
  390. }, 0);
  391. }
  392. /**
  393. * Extracts and returns the stringified version of the layers route path
  394. * Handles route arrays (by joining the paths together) as well as RegExp and normal
  395. * string values (in the latter case the toString conversion is technically unnecessary but
  396. * it doesn't hurt us either).
  397. */
  398. function getLayerRoutePathString(isArray, lrp) {
  399. if (isArray) {
  400. return (lrp ).map(r => r.toString()).join(',');
  401. }
  402. return lrp && lrp.toString();
  403. }
  404. /**
  405. * remove duplicate segment contain in layerPath against reconstructedRoute,
  406. * and return only unique segment that can be added into reconstructedRoute
  407. */
  408. function preventDuplicateSegments(
  409. originalUrl,
  410. reconstructedRoute,
  411. layerPath,
  412. ) {
  413. // filter query params
  414. const normalizeURL = utils.stripUrlQueryAndFragment(originalUrl || '');
  415. const originalUrlSplit = _optionalChain([normalizeURL, 'optionalAccess', _14 => _14.split, 'call', _15 => _15('/'), 'access', _16 => _16.filter, 'call', _17 => _17(v => !!v)]);
  416. let tempCounter = 0;
  417. const currentOffset = _optionalChain([reconstructedRoute, 'optionalAccess', _18 => _18.split, 'call', _19 => _19('/'), 'access', _20 => _20.filter, 'call', _21 => _21(v => !!v), 'access', _22 => _22.length]) || 0;
  418. const result = _optionalChain([layerPath
  419. , 'optionalAccess', _23 => _23.split, 'call', _24 => _24('/')
  420. , 'access', _25 => _25.filter, 'call', _26 => _26(segment => {
  421. if (_optionalChain([originalUrlSplit, 'optionalAccess', _27 => _27[currentOffset + tempCounter]]) === segment) {
  422. tempCounter += 1;
  423. return true;
  424. }
  425. return false;
  426. })
  427. , 'access', _28 => _28.join, 'call', _29 => _29('/')]);
  428. return result;
  429. }
  430. exports.Express = Express;
  431. exports.extractOriginalRoute = extractOriginalRoute;
  432. exports.preventDuplicateSegments = preventDuplicateSegments;
  433. //# sourceMappingURL=express.js.map