http-proxy-middleware.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.HttpProxyMiddleware = void 0;
  4. const httpProxy = require("http-proxy");
  5. const configuration_1 = require("./configuration");
  6. const get_plugins_1 = require("./get-plugins");
  7. const path_filter_1 = require("./path-filter");
  8. const PathRewriter = require("./path-rewriter");
  9. const Router = require("./router");
  10. const debug_1 = require("./debug");
  11. const function_1 = require("./utils/function");
  12. const logger_1 = require("./logger");
  13. class HttpProxyMiddleware {
  14. constructor(options) {
  15. this.wsInternalSubscribed = false;
  16. this.serverOnCloseSubscribed = false;
  17. // https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript#red-flags-for-this
  18. this.middleware = (async (req, res, next) => {
  19. if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
  20. try {
  21. const activeProxyOptions = await this.prepareProxyRequest(req);
  22. (0, debug_1.Debug)(`proxy request to target: %O`, activeProxyOptions.target);
  23. this.proxy.web(req, res, activeProxyOptions);
  24. }
  25. catch (err) {
  26. next?.(err);
  27. }
  28. }
  29. else {
  30. next?.();
  31. }
  32. /**
  33. * Get the server object to subscribe to server events;
  34. * 'upgrade' for websocket and 'close' for graceful shutdown
  35. *
  36. * NOTE:
  37. * req.socket: node >= 13
  38. * req.connection: node < 13 (Remove this when node 12/13 support is dropped)
  39. */
  40. const server = (req.socket ?? req.connection)?.server;
  41. if (server && !this.serverOnCloseSubscribed) {
  42. server.on('close', () => {
  43. (0, debug_1.Debug)('server close signal received: closing proxy server');
  44. this.proxy.close();
  45. });
  46. this.serverOnCloseSubscribed = true;
  47. }
  48. if (this.proxyOptions.ws === true) {
  49. // use initial request to access the server object to subscribe to http upgrade event
  50. this.catchUpgradeRequest(server);
  51. }
  52. });
  53. this.catchUpgradeRequest = (server) => {
  54. if (!this.wsInternalSubscribed) {
  55. (0, debug_1.Debug)('subscribing to server upgrade event');
  56. server.on('upgrade', this.handleUpgrade);
  57. // prevent duplicate upgrade handling;
  58. // in case external upgrade is also configured
  59. this.wsInternalSubscribed = true;
  60. }
  61. };
  62. this.handleUpgrade = async (req, socket, head) => {
  63. if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
  64. const activeProxyOptions = await this.prepareProxyRequest(req);
  65. this.proxy.ws(req, socket, head, activeProxyOptions);
  66. (0, debug_1.Debug)('server upgrade event received. Proxying WebSocket');
  67. }
  68. };
  69. /**
  70. * Determine whether request should be proxied.
  71. */
  72. this.shouldProxy = (pathFilter, req) => {
  73. try {
  74. return (0, path_filter_1.matchPathFilter)(pathFilter, req.url, req);
  75. }
  76. catch (err) {
  77. (0, debug_1.Debug)('Error: matchPathFilter() called with request url: ', `"${req.url}"`);
  78. this.logger.error(err);
  79. return false;
  80. }
  81. };
  82. /**
  83. * Apply option.router and option.pathRewrite
  84. * Order matters:
  85. * Router uses original path for routing;
  86. * NOT the modified path, after it has been rewritten by pathRewrite
  87. * @param {Object} req
  88. * @return {Object} proxy options
  89. */
  90. this.prepareProxyRequest = async (req) => {
  91. /**
  92. * Incorrect usage confirmed: https://github.com/expressjs/express/issues/4854#issuecomment-1066171160
  93. * Temporary restore req.url patch for {@link src/legacy/create-proxy-middleware.ts legacyCreateProxyMiddleware()}
  94. * FIXME: remove this patch in future release
  95. */
  96. if (this.middleware.__LEGACY_HTTP_PROXY_MIDDLEWARE__) {
  97. req.url = req.originalUrl || req.url;
  98. }
  99. const newProxyOptions = Object.assign({}, this.proxyOptions);
  100. // Apply in order:
  101. // 1. option.router
  102. // 2. option.pathRewrite
  103. await this.applyRouter(req, newProxyOptions);
  104. await this.applyPathRewrite(req, this.pathRewriter);
  105. return newProxyOptions;
  106. };
  107. // Modify option.target when router present.
  108. this.applyRouter = async (req, options) => {
  109. let newTarget;
  110. if (options.router) {
  111. newTarget = await Router.getTarget(req, options);
  112. if (newTarget) {
  113. (0, debug_1.Debug)('router new target: "%s"', newTarget);
  114. options.target = newTarget;
  115. }
  116. }
  117. };
  118. // rewrite path
  119. this.applyPathRewrite = async (req, pathRewriter) => {
  120. if (pathRewriter) {
  121. const path = await pathRewriter(req.url, req);
  122. if (typeof path === 'string') {
  123. (0, debug_1.Debug)('pathRewrite new path: %s', req.url);
  124. req.url = path;
  125. }
  126. else {
  127. (0, debug_1.Debug)('pathRewrite: no rewritten path found: %s', req.url);
  128. }
  129. }
  130. };
  131. (0, configuration_1.verifyConfig)(options);
  132. this.proxyOptions = options;
  133. this.logger = (0, logger_1.getLogger)(options);
  134. (0, debug_1.Debug)(`create proxy server`);
  135. this.proxy = httpProxy.createProxyServer({});
  136. this.registerPlugins(this.proxy, this.proxyOptions);
  137. this.pathRewriter = PathRewriter.createPathRewriter(this.proxyOptions.pathRewrite); // returns undefined when "pathRewrite" is not provided
  138. // https://github.com/chimurai/http-proxy-middleware/issues/19
  139. // expose function to upgrade externally
  140. this.middleware.upgrade = (req, socket, head) => {
  141. if (!this.wsInternalSubscribed) {
  142. this.handleUpgrade(req, socket, head);
  143. }
  144. };
  145. }
  146. registerPlugins(proxy, options) {
  147. const plugins = (0, get_plugins_1.getPlugins)(options);
  148. plugins.forEach((plugin) => {
  149. (0, debug_1.Debug)(`register plugin: "${(0, function_1.getFunctionName)(plugin)}"`);
  150. plugin(proxy, options);
  151. });
  152. }
  153. }
  154. exports.HttpProxyMiddleware = HttpProxyMiddleware;