mswjs / interceptors

Low-level network interception library.
https://npm.im/@mswjs/interceptors
MIT License
565 stars 127 forks source link

Protocol "https:" not supported. Expected "http:" when using "proxy-agent" #570

Open indrek-sixfold opened 6 months ago

indrek-sixfold commented 6 months ago

When using ClientRequestInterceptor with ProxyAgent, it ends with error

TypeError [ERR_INVALID_PROTOCOL]: Protocol "https:" not supported. Expected "http:"
    at new ClientRequest (node:_http_client:183:11)
    at new _NodeClientRequest (/home/indrek/service/node_modules/@mswjs/interceptors/lib/node/chunk-SXGRMPXP.js:226:5)
    at interceptorsHttpRequest (/home/indrek/service/node_modules/@mswjs/interceptors/lib/node/chunk-SXGRMPXP.js:850:12)
    at /home/indrek/service/node_modules/node-fetch/lib/index.js:1478:15
    at new Promise (<anonymous>)
    at fetch (/home/indrek/service/node_modules/node-fetch/lib/index.js:1447:9)
    at Generator.next (<anonymous>)

Code is here:

import { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest';
import fetch from 'node-fetch';
import { ProxyAgent } from 'proxy-agent';

  async execute() {
    const interceptor = new ClientRequestInterceptor();
    interceptor.apply();
    await fetch('https://google.com', {
      agent: new ProxyAgent(), // ALL_PROXY=http://127.0.0.1:3000
    });
    interceptor.dispose();
  }

Using packages:

node-fetch:2.7.0
proxy-agent:6.4.0
@mswjs/interceptors:0.29.1

Is there anything to configure to make it work with proxy?

kettanaito commented 6 months ago

Hi, @indrek-sixfold! Thanks for reporting this.

At the first glance, the issue is happening because the request-making module (http or https) is bound to the initial request when using Interceptors. I assume during proxying, since you are switching protocols, the interceptor attempts to perform the proxied request using the wrong request module for some reason.

In theory, that shouldn't happen because the request originates from proxy-agent, we aren't constructing them internally (unless the request is bypassed, which I believe is precisely your use case).

We need an integration test for this.

justemu commented 2 months ago

This bug is still there.

kettanaito commented 2 months ago

@justemu, would you like to give it a try? I can support you with code review and merge your fix once it's ready. Let me know!