@bjowes/http-mitm-proxy

中文文档
0.9.6发布于 2025/01/28MITTypeScriptCommonJS近 30 天下载 1.1万

HTTP Man In The Middle (MITM) Proxy. This is a fork of Joe Ferners' library node-http-mitm-proxy. Its first release was identical to the master version of the original library, commit 66ac0f5d3298f66b731f90ebf1e9b430fa5d76eb. I decided to publish a scoped

原始使用文档
文档目录27 节
  1. Node.js Compatibility
  2. Typescript
  3. Proxy
  4. Context
  5. WebSocket Context
  6. Proxy
  7. proxy.listen
  8. proxy.close
  9. proxy.onError(fn) or ctx.onError(fn)
  10. proxy.onCertificateRequired = function(hostname, callback)
  11. proxy.onCertificateMissing = function(ctx, files, callback)
  12. proxy.onRequest(fn) or ctx.onRequest(fn)
  13. proxy.onRequestData(fn) or ctx.onRequestData(fn)
  14. proxy.onRequestEnd(fn) or ctx.onRequestEnd(fn)
  15. proxy.onResponse(fn) or ctx.onResponse(fn)
  16. proxy.onResponseData(fn) or ctx.onResponseData(fn)
  17. proxy.onResponseEnd(fn) or ctx.onResponseEnd(fn)
  18. proxy.onWebSocketConnection(fn) or ctx.onWebSocketConnectio…
  19. proxy.onWebSocketSend(fn) or ctx.onWebSocketSend(fn)
  20. proxy.onWebSocketMessage(fn) or ctx.onWebSocketMessage(fn)
  21. proxy.onWebSocketFrame(fn) or ctx.onWebSocketFrame(fn)
  22. proxy.onWebSocketError(fn) or ctx.onWebSocketError(fn)
  23. proxy.onWebSocketClose(fn) or ctx.onWebSocketClose(fn)
  24. proxy.use(module) or ctx.use(module)
  25. Context
  26. ctx.addRequestFilter(stream)
  27. ctx.addResponseFilter(stream)

@bjowes fork

This is a fork of Joe Ferners' library node-http-mitm-proxy (see docs below). Its first release was identical to the master version of the original library, commit 66ac0f5d3298f66b731f90ebf1e9b430fa5d76eb. I decided to publish a scoped version of this library to npm, since I needed the codebase in npm. It is only intended for my own library cypress-ntlm-auth. Use at you own risk!

  • 2025-01-27: 0.9.6 - Dependency bump
  • 2024-03-27: 0.9.5 - Patch for custom status messages, dependency bump
  • 2022-04-08: 0.9.4 - Address accessor, typings fix
  • 2022-04-04: 0.9.3 - Patch for cert filenames with IPv6 sites.
  • 2022-03-31: 0.9.2 - Updated dependencies due to security issues. Improved HTTPS stability. IPv6 Support.
  • 2019-08-01: Updated dependencies due to security issues

HTTP MITM Proxy

HTTP Man In The Middle (MITM) Proxy written in node.js. Supports capturing and modifying the request and response data.

NPM version Downloads Test Status

Install

npm install --save http-mitm-proxy

Node.js Compatibility

The library should work starting Node.js 8.x, but testing is only expected for currently supported LTS versions of Node.js starting Node.js 12.x . use on your own risk with non LTS Node.js versions.

Typescript

type definitions are now included in this project, no extra steps required.

Example

This example will modify any search results coming from google and replace all the result titles with "Pwned!".

var Proxy = require('http-mitm-proxy');
var proxy = Proxy();

proxy.onError(function(ctx, err) {
  console.error('proxy error:', err);
});

proxy.onRequest(function(ctx, callback) {
  if (ctx.clientToProxyRequest.headers.host == 'www.google.com'
    && ctx.clientToProxyRequest.url.indexOf('/search') == 0) {
    ctx.use(Proxy.gunzip);

    ctx.onResponseData(function(ctx, chunk, callback) {
      chunk = new Buffer(chunk.toString().replace(/<h3.*?<\/h3>/g, '<h3>Pwned!</h3>'));
      return callback(null, chunk);
    });
  }
  return callback();
});

proxy.listen({port: 8081});

You can find more examples in the examples directory

SSL

Using node-forge allows the automatic generation of SSL certificates within the proxy. After running your app you will find options.sslCaDir + '/certs/ca.pem' which can be imported to your browser, phone, etc.

API

Proxy

Context

Context functions only effect the current request/response. For example you may only want to gunzip requests made to a particular host.

WebSocket Context

The context available in websocket handlers is a bit different

Proxy

proxy.listen

Starts the proxy listening on the given port.

Arguments

Example

proxy.listen({ port: 80 });

proxy.close

Stops the proxy listening.

Example

proxy.close();

proxy.onError(fn) or ctx.onError(fn)

Adds a function to the list of functions to get called if an error occures.

Arguments

  • fn(ctx, err, errorKind) - The function to be called on an error.

Example

proxy.onError(function(ctx, err, errorKind) {
  // ctx may be null
  var url = (ctx && ctx.clientToProxyRequest) ? ctx.clientToProxyRequest.url : "";
  console.error(errorKind + ' on ' + url + ':', err);
});

proxy.onCertificateRequired = function(hostname, callback)

Allows the default certificate name/path computation to be overwritten.

The default behavior expects keys/{hostname}.pem and certs/{hostname}.pem files to be at self.sslCaDir.

Arguments

  • hostname - Requested hostname.
  • callback - The function to be called when certificate files' path were already computed.

Example 1

proxy.onCertificateRequired = function(hostname, callback) {
  return callback(null, {
    keyFile: path.resolve('/ca/certs/', hostname + '.key'),
    certFile: path.resolve('/ca/certs/', hostname + '.crt')
  });
};

Example 2: Wilcard certificates

proxy.onCertificateRequired = function(hostname, callback) {
  return callback(null, {
    keyFile: path.resolve('/ca/certs/', hostname + '.key'),
    certFile: path.resolve('/ca/certs/', hostname + '.crt'),
    hosts: ["*.mydomain.com"]
  });
};

proxy.onCertificateMissing = function(ctx, files, callback)

Allows you to handle missing certificate files for current request, for example, creating them on the fly.

Arguments

  • ctx - Context with the following properties
  • hostname - The hostname which requires certificates
  • data.keyFileExists - Whether key file exists or not
  • data.certFileExists - Whether certificate file exists or not
  • files - missing files names (files.keyFile, files.certFile and optional files.hosts)
  • callback - The function to be called to pass certificate data back (keyFileData and certFileData)

Example 1

proxy.onCertificateMissing = function(ctx, files, callback) {
  console.log('Looking for "%s" certificates',   ctx.hostname);
  console.log('"%s" missing', ctx.files.keyFile);
  console.log('"%s" missing', ctx.files.certFile);

  // Here you have the last chance to provide certificate files data
  // A tipical use case would be creating them on the fly
  //
  // return callback(null, {
  //   keyFileData: keyFileData,
  //   certFileData: certFileData
  // });
  };

Example 2: Wilcard certificates

proxy.onCertificateMissing = function(ctx, files, callback) {
  return callback(null, {
    keyFileData: keyFileData,
    certFileData: certFileData,
    hosts: ["*.mydomain.com"]
  });
};

proxy.onRequest(fn) or ctx.onRequest(fn)

Adds a function to get called at the beginning of a request.

Arguments

  • fn(ctx, callback) - The function that gets called on each request.

Example

proxy.onRequest(function(ctx, callback) {
  console.log('REQUEST:', ctx.clientToProxyRequest.url);
  return callback();
});

proxy.onRequestData(fn) or ctx.onRequestData(fn)

Adds a function to get called for each request data chunk (the body).

Arguments

  • fn(ctx, chunk, callback) - The function that gets called for each data chunk.

Example

proxy.onRequestData(function(ctx, chunk, callback) {
  console.log('REQUEST DATA:', chunk.toString());
  return callback(null, chunk);
});

proxy.onRequestEnd(fn) or ctx.onRequestEnd(fn)

Adds a function to get called when all request data (the body) was sent.

Arguments

  • fn(ctx, callback) - The function that gets called when all request data (the body) was sent.

Example

var chunks = [];

proxy.onRequestData(function(ctx, chunk, callback) {
  chunks.push(chunk);
  return callback(null, chunk);
});

proxy.onRequestEnd(function(ctx, callback) {
  console.log('REQUEST END', (Buffer.concat(chunks)).toString());
  return callback();
});

proxy.onResponse(fn) or ctx.onResponse(fn)

Adds a function to get called at the beginning of the response.

Arguments

  • fn(ctx, callback) - The function that gets called on each response.

Example

proxy.onResponse(function(ctx, callback) {
  console.log('BEGIN RESPONSE');
  return callback();
});

proxy.onResponseData(fn) or ctx.onResponseData(fn)

Adds a function to get called for each response data chunk (the body).

Arguments

  • fn(ctx, chunk, callback) - The function that gets called for each data chunk.

Example

proxy.onResponseData(function(ctx, chunk, callback) {
  console.log('RESPONSE DATA:', chunk.toString());
  return callback(null, chunk);
});

proxy.onResponseEnd(fn) or ctx.onResponseEnd(fn)

Adds a function to get called when the proxy request to server has ended.

Arguments

  • fn(ctx, callback) - The function that gets called when the proxy request to server as ended.

Example

proxy.onResponseEnd(function(ctx, callback) {
  console.log('RESPONSE END');
  return callback();
});

proxy.onWebSocketConnection(fn) or ctx.onWebSocketConnection(fn)

Adds a function to get called at the beginning of websocket connection

Arguments

  • fn(ctx, callback) - The function that gets called for each data chunk.

Example

proxy.onWebSocketConnection(function(ctx, callback) {
  console.log('WEBSOCKET CONNECT:', ctx.clientToProxyWebSocket.upgradeReq.url);
  return callback();
});

proxy.onWebSocketSend(fn) or ctx.onWebSocketSend(fn)

Adds a function to get called for each WebSocket message sent by the client.

Arguments

  • fn(ctx, message, flags, callback) - The function that gets called for each WebSocket message sent by the client.

Example

proxy.onWebSocketSend(function(ctx, message, flags, callback) {
  console.log('WEBSOCKET SEND:', ctx.clientToProxyWebSocket.upgradeReq.url, message);
  return callback(null, message, flags);
});

proxy.onWebSocketMessage(fn) or ctx.onWebSocketMessage(fn)

Adds a function to get called for each WebSocket message received from the server.

Arguments

  • fn(ctx, message, flags, callback) - The function that gets called for each WebSocket message received from the server.

Example

proxy.onWebSocketMessage(function(ctx, message, flags, callback) {
  console.log('WEBSOCKET MESSAGE:', ctx.clientToProxyWebSocket.upgradeReq.url, message);
  return callback(null, message, flags);
});

proxy.onWebSocketFrame(fn) or ctx.onWebSocketFrame(fn)

Adds a function to get called for each WebSocket frame exchanged (message, ping or pong).

Arguments

  • fn(ctx, type, fromServer, data, flags, callback) - The function that gets called for each WebSocket frame exchanged.

Example

proxy.onWebSocketFrame(function(ctx, type, fromServer, data, flags, callback) {
  console.log('WEBSOCKET FRAME ' + type + ' received from ' + (fromServer ? 'server' : 'client'), ctx.clientToProxyWebSocket.upgradeReq.url, data);
  return callback(null, data, flags);
});

proxy.onWebSocketError(fn) or ctx.onWebSocketError(fn)

Adds a function to the list of functions to get called if an error occures in WebSocket.

Arguments

  • fn(ctx, err) - The function to be called on an error in WebSocket.

Example

proxy.onWebSocketError(function(ctx, err) {
  console.log('WEBSOCKET ERROR:', ctx.clientToProxyWebSocket.upgradeReq.url, err);
});

proxy.onWebSocketClose(fn) or ctx.onWebSocketClose(fn)

Adds a function to get called when a WebSocket connection is closed

Arguments

  • fn(ctx, code, message, callback) - The function that gets when a WebSocket is closed.

Example

proxy.onWebSocketClose(function(ctx, code, message, callback) {
  console.log('WEBSOCKET CLOSED BY '+(ctx.closedByServer ? 'SERVER' : 'CLIENT'), ctx.clientToProxyWebSocket.upgradeReq.url, code, message);
  callback(null, code, message);
});

proxy.use(module) or ctx.use(module)

Adds a module into the proxy. Modules encapsulate multiple life cycle processing functions into one object.

Arguments

  • module - The module to add. Modules contain a hash of functions to add.

Example

proxy.use({
  onError: function(ctx, err) { },
  onCertificateRequired: function(hostname, callback) { return callback(); },
  onCertificateMissing: function(ctx, files, callback) { return callback(); },
  onRequest: function(ctx, callback) { return callback(); },
  onRequestData: function(ctx, chunk, callback) { return callback(null, chunk); },
  onResponse: function(ctx, callback) { return callback(); },
  onResponseData: function(ctx, chunk, callback) { return callback(null, chunk); },
  onWebSocketConnection: function(ctx, callback) { return callback(); },
  onWebSocketSend: function(ctx, message, flags, callback) { return callback(null, message, flags); },
  onWebSocketMessage: function(ctx, message, flags, callback) { return callback(null, message, flags); },
  onWebSocketError: function(ctx, err) {  },
  onWebSocketClose: function(ctx, code, message, callback) {  },
});

node-http-mitm-proxy provide some ready to use modules:

  • Proxy.gunzip Gunzip response filter (uncompress gzipped content before onResponseData and compress back after)
  • Proxy.wildcard Generates wilcard certificates by default (so less certificates are generated)

Context

ctx.addRequestFilter(stream)

Adds a stream into the request body stream.

Arguments

  • stream - The read/write stream to add in the request body stream.

Example

ctx.addRequestFilter(zlib.createGunzip());

ctx.addResponseFilter(stream)

Adds a stream into the response body stream.

Arguments

  • stream - The read/write stream to add in the response body stream.

Example

ctx.addResponseFilter(zlib.createGunzip());

License

Copyright (c) 2015 Joe Ferner

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:



The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.



THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

版本与发布记录

@bjowes/http-mitm-proxy 共发布 7 个版本,首次发布于 2019/06/07;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.9.6latest2025/01/281.8 年前
0.9.52024/03/282 年前
0.9.42022/04/094 年前
0.9.32022/04/054 年前
0.9.22022/04/044 年前
0.7.22019/08/027 年前

关于 @bjowes/http-mitm-proxy 的常见问题

@bjowes/http-mitm-proxy 是什么?

HTTP Man In The Middle (MITM) Proxy. This is a fork of Joe Ferners' library node-http-mitm-proxy. Its first release was identical to the master version of the original library, commit 66ac0f5d3298f66b731f90ebf1e9b430fa5d76eb. I decided to publish a scoped

如何安装 @bjowes/http-mitm-proxy?

在项目目录运行 npm install @bjowes/http-mitm-proxy,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 http-mitm-proxy,可以用 npx http-mitm-proxy 直接运行。

@bjowes/http-mitm-proxy 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@bjowes/http-mitm-proxy 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@bjowes/http-mitm-proxy 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=14。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@bjowes/http-mitm-proxy 可以商用吗?

@bjowes/http-mitm-proxy 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@bjowes/http-mitm-proxy 的下载量有多少?

根据 npm 官方下载统计,@bjowes/http-mitm-proxy 在 2026/10/08 – 2026/11/06 这 30 天内被下载 10,758 次,日均约 359 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@bjowes/http-mitm-proxy 还在维护吗?

最新版本 0.9.6 发布于 2025/01/28(1.8 年前);至今共发布 7 个版本,其中过去 12 个月发布了 0 个;首次发布于 2019/06/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。