npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@dblk/yamp

v1.0.4

Published

Simple MITM HTTP/HTTPS proxy with capability of chaining middleware

Downloads

11

Readme

YAMP (Yet Another Mitm Proxy)

This module provide a basic but yet powerful man in the middle proxy for nodejs.
It provides HTTP & HTTPS support and also modifying the request and response data.

The main goal of this library is to ease the managment of certificate for https requests.

History

A huge part has been borrowed from node-http-mitm-proxy (MIT License).

This fix the main issue that I had using the library by being unable to have the full request's body and still being able to cancel it for the response.

The other feature I added is to allow sequential chaining of middleware. Which is useful if you need to have on middleware to execute before another (and maybe alter the current request).

How to use it?

const { Proxy } = require('@dblk/yamp');
const mitm = new Proxy();

const options = {
    port: 8080,
    sslCaDir: '.generated-certs',
    timeout: 20000,
};

// First middleware for every requests
mitm.onRequest((req, res, next) => {
    try {
        req.middleware1 = true;
    } catch (err) {
        return next(err);
    }
    next();
});

// Second middleware
mitm.onRequest((req, res, next) => {
    try {
        if (req.middleware1) {
            req.middleware2 = true; 
        }
    } catch (err) {
        return next(err);
    }
    next();
});

mitm.onResponse((req, res, proxyRes, next) => {
    try {
        console.log(res.finished);
    } catch (err) {
        return next(err);
    }
});

// Start the proxy
mitm.listen(options);

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.

What's next?

I did port all of the features that node-http-mitm-proxy has to offer and it might be a good starting point to add websocket also.

Please submit an issue on github about what you want next for this librairy.

API

You will find the documentation of available functions with their according signature bellow.

API

Proxy

Proxy

proxy.listen

Starts the proxy listening on the given port.

Arguments

  • options - An object with the following options:
  • port - The port or named socket to listen on (default: 8080).
  • sslCaDir - Path to the certificates cache directory (default: process.cwd() + '/.http-mitm-proxy')
  • keepAlive - enable HTTP persistent connection
  • timeout - The number of milliseconds of inactivity before a socket is presumed to have timed out. (default: 5000).
  • httpAgent - The http.Agent to use when making http requests. Useful for chaining proxys. (default: internal Agent)
  • httpsAgent - The https.Agent to use when making https requests. Useful for chaining proxys. (default: internal Agent)

Example

proxy.listen({ port: 80 });

proxy.close

Stops the proxy listening.

Example

proxy.close();

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)

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

Arguments

  • fn(req, res, next) - The function that gets called on each request.
    • req - The initial http.request object
    • res - The http.response to the client
    • next - Call the next middleware (Pass an object to set the error)

Example

proxy.onRequest(function(req, res, next) {
  console.log('REQUEST:', req.url);
  next();
});

proxy.onResponse(fn)

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

Arguments

  • fn(req, res, proxyRes, next) - The function that gets called on each response.
    • req - The initial http.request object
    • res - The http.response to the client
    • proxyRes - The http.response from the remote server
    • next - Call the next middleware (Pass an object to set the error)

Example

proxy.onResponse(function(req, res, proxyRes, next) {
  if (res.finished) {
      console.log('Response ended before reaching me, can't modify');
      next();
      return;
  }
  console.log('BEGIN RESPONSE');
  if (proxyRes.statusCode !== 200) {
      res.statusCode = 500;
  } else {
      res.statusCode = 200;
  }
  res.end(proxyRes.rawBody);
  next();
});

License

Copyright (c) 2019-2022 Rémy Boulanouar

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.