• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

chimurai / http-proxy-middleware / 14246826731

03 Apr 2025 03:26PM CUT coverage: 97.33% (+0.05%) from 97.284%
14246826731

Pull #823

github

web-flow
Merge ef93655f0 into e94087e8d
Pull Request #823: fix(websocket): handle errors in handleUpgrade

137 of 142 branches covered (96.48%)

16 of 16 new or added lines in 2 files covered. (100.0%)

401 of 412 relevant lines covered (97.33%)

24.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

100.0
/src/http-proxy-middleware.ts
1
import type * as net from 'net';
2
import type * as http from 'http';
3
import type * as https from 'https';
4
import type { RequestHandler, Options, Filter, Logger } from './types';
5
import * as httpProxy from 'http-proxy';
12✔
6
import { verifyConfig } from './configuration';
12✔
7
import { getPlugins } from './get-plugins';
12✔
8
import { matchPathFilter } from './path-filter';
12✔
9
import * as PathRewriter from './path-rewriter';
12✔
10
import * as Router from './router';
12✔
11
import { Debug as debug } from './debug';
12✔
12
import { getFunctionName } from './utils/function';
12✔
13
import { getLogger } from './logger';
12✔
14

15
export class HttpProxyMiddleware<TReq, TRes> {
12✔
16
  private wsInternalSubscribed = false;
75✔
17
  private serverOnCloseSubscribed = false;
75✔
18
  private proxyOptions: Options<TReq, TRes>;
19
  private proxy: httpProxy<TReq, TRes>;
20
  private pathRewriter;
21
  private logger: Logger;
22

23
  constructor(options: Options<TReq, TRes>) {
24
    verifyConfig<TReq, TRes>(options);
75✔
25
    this.proxyOptions = options;
75✔
26
    this.logger = getLogger(options as unknown as Options);
75✔
27

28
    debug(`create proxy server`);
75✔
29
    this.proxy = httpProxy.createProxyServer({});
75✔
30

31
    this.registerPlugins(this.proxy, this.proxyOptions);
75✔
32

33
    this.pathRewriter = PathRewriter.createPathRewriter(this.proxyOptions.pathRewrite); // returns undefined when "pathRewrite" is not provided
75✔
34

35
    // https://github.com/chimurai/http-proxy-middleware/issues/19
36
    // expose function to upgrade externally
37
    this.middleware.upgrade = (req, socket, head) => {
75✔
38
      if (!this.wsInternalSubscribed) {
3✔
39
        this.handleUpgrade(req, socket, head);
3✔
40
      }
41
    };
42
  }
43

44
  // https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript#red-flags-for-this
45
  public middleware: RequestHandler = (async (req, res, next?) => {
75✔
46
    if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
55✔
47
      try {
49✔
48
        const activeProxyOptions = await this.prepareProxyRequest(req);
49✔
49
        debug(`proxy request to target: %O`, activeProxyOptions.target);
48✔
50
        this.proxy.web(req, res, activeProxyOptions);
48✔
51
      } catch (err) {
52
        next?.(err);
2✔
53
      }
54
    } else {
55
      next?.();
6✔
56
    }
57

58
    /**
59
     * Get the server object to subscribe to server events;
60
     * 'upgrade' for websocket and 'close' for graceful shutdown
61
     *
62
     * NOTE:
63
     * req.socket: node >= 13
64
     * req.connection: node < 13 (Remove this when node 12/13 support is dropped)
65
     */
66
    const server: https.Server = ((req.socket ?? req.connection) as any)?.server;
55✔
67

68
    if (server && !this.serverOnCloseSubscribed) {
55✔
69
      server.on('close', () => {
53✔
70
        debug('server close signal received: closing proxy server');
53✔
71
        this.proxy.close();
53✔
72
      });
73
      this.serverOnCloseSubscribed = true;
53✔
74
    }
75

76
    if (this.proxyOptions.ws === true) {
55✔
77
      // use initial request to access the server object to subscribe to http upgrade event
78
      this.catchUpgradeRequest(server);
2✔
79
    }
80
  }) as RequestHandler;
81

82
  private registerPlugins(proxy: httpProxy<TReq, TRes>, options: Options<TReq, TRes>) {
83
    const plugins = getPlugins<TReq, TRes>(options);
75✔
84
    plugins.forEach((plugin) => {
75✔
85
      debug(`register plugin: "${getFunctionName(plugin)}"`);
296✔
86
      plugin(proxy, options);
296✔
87
    });
88
  }
89

90
  private catchUpgradeRequest = (server: https.Server) => {
75✔
91
    if (!this.wsInternalSubscribed) {
2✔
92
      debug('subscribing to server upgrade event');
1✔
93
      server.on('upgrade', this.handleUpgrade);
1✔
94
      // prevent duplicate upgrade handling;
95
      // in case external upgrade is also configured
96
      this.wsInternalSubscribed = true;
1✔
97
    }
98
  };
99

100
  private handleUpgrade = async (req: http.IncomingMessage, socket: net.Socket, head: Buffer) => {
75✔
101
    try {
4✔
102
      if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
4✔
103
        const activeProxyOptions = await this.prepareProxyRequest(req);
4✔
104
        this.proxy.ws(req, socket, head, activeProxyOptions);
3✔
105
        debug('server upgrade event received. Proxying WebSocket');
3✔
106
      }
107
    } catch (err) {
108
      // This error does not include the URL as the fourth argument as we won't
109
      // have the URL if `this.prepareProxyRequest` throws an error.
110
      this.proxy.emit('error', err, req, socket);
1✔
111
    }
112
  };
113

114
  /**
115
   * Determine whether request should be proxied.
116
   */
117
  private shouldProxy = (
75✔
118
    pathFilter: Filter<TReq> | undefined,
119
    req: http.IncomingMessage,
120
  ): boolean => {
121
    try {
59✔
122
      return matchPathFilter(pathFilter, req.url, req);
59✔
123
    } catch (err) {
124
      debug('Error: matchPathFilter() called with request url: ', `"${req.url}"`);
1✔
125
      this.logger.error(err);
1✔
126
      return false;
1✔
127
    }
128
  };
129

130
  /**
131
   * Apply option.router and option.pathRewrite
132
   * Order matters:
133
   *    Router uses original path for routing;
134
   *    NOT the modified path, after it has been rewritten by pathRewrite
135
   * @param {Object} req
136
   * @return {Object} proxy options
137
   */
138
  private prepareProxyRequest = async (req: http.IncomingMessage) => {
75✔
139
    /**
140
     * Incorrect usage confirmed: https://github.com/expressjs/express/issues/4854#issuecomment-1066171160
141
     * Temporary restore req.url patch for {@link src/legacy/create-proxy-middleware.ts legacyCreateProxyMiddleware()}
142
     * FIXME: remove this patch in future release
143
     */
144
    if ((this.middleware as unknown as any).__LEGACY_HTTP_PROXY_MIDDLEWARE__) {
53✔
145
      req.url = (req as unknown as any).originalUrl || req.url;
5!
146
    }
147

148
    const newProxyOptions = Object.assign({}, this.proxyOptions);
53✔
149

150
    // Apply in order:
151
    // 1. option.router
152
    // 2. option.pathRewrite
153
    await this.applyRouter(req, newProxyOptions);
53✔
154
    await this.applyPathRewrite(req, this.pathRewriter);
51✔
155

156
    return newProxyOptions;
51✔
157
  };
158

159
  // Modify option.target when router present.
160
  private applyRouter = async (req: http.IncomingMessage, options: Options<TReq, TRes>) => {
75✔
161
    let newTarget;
162

163
    if (options.router) {
53✔
164
      newTarget = await Router.getTarget(req, options);
13✔
165

166
      if (newTarget) {
11✔
167
        debug('router new target: "%s"', newTarget);
9✔
168
        options.target = newTarget;
9✔
169
      }
170
    }
171
  };
172

173
  // rewrite path
174
  private applyPathRewrite = async (req: http.IncomingMessage, pathRewriter) => {
75✔
175
    if (pathRewriter) {
51✔
176
      const path = await pathRewriter(req.url, req);
10✔
177

178
      if (typeof path === 'string') {
10✔
179
        debug('pathRewrite new path: %s', req.url);
9✔
180
        req.url = path;
9✔
181
      } else {
182
        debug('pathRewrite: no rewritten path found: %s', req.url);
1✔
183
      }
184
    }
185
  };
186
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc