All Projects → apify → Proxy Chain

apify / Proxy Chain

Licence: apache-2.0
Node.js implementation of a proxy server (think Squid) with support for SSL, authentication and upstream proxy chaining.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Proxy Chain

Apify Js
Apify SDK — The scalable web scraping and crawling library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.
Stars: ✭ 3,154 (+743.32%)
Mutual labels:  headless-chrome, javascript-library
Javascript Winwheel
Create spinning prize wheels on HTML canvas with Winwheel.js
Stars: ✭ 357 (-4.55%)
Mutual labels:  javascript-library
Luaparse
A Lua parser written in JavaScript
Stars: ✭ 309 (-17.38%)
Mutual labels:  javascript-library
Pyppeteer
Headless chrome/chromium automation library (unofficial port of puppeteer)
Stars: ✭ 3,480 (+830.48%)
Mutual labels:  headless-chrome
Voca
The ultimate JavaScript string library
Stars: ✭ 3,387 (+805.61%)
Mutual labels:  javascript-library
Athens
A Go module datastore and proxy
Stars: ✭ 3,736 (+898.93%)
Mutual labels:  proxy-server
Binance
A wrapper for the Binance REST and WebSocket APIs. Also beautifies responses
Stars: ✭ 304 (-18.72%)
Mutual labels:  javascript-library
Jsuites
jSuites is a collection of lightweight common required javascript web components. It is composed of fully responsive vanilla plugins to help you bring the best user experience to your projects, independent of the platform. Same JS codebase across different platforms.
Stars: ✭ 365 (-2.41%)
Mutual labels:  javascript-library
Proxy requests
a class that uses scraped proxies to make http GET/POST requests (Python requests)
Stars: ✭ 357 (-4.55%)
Mutual labels:  proxy-server
Mochify.js
☕️ TDD with Browserify, Mocha, Headless Chrome and WebDriver
Stars: ✭ 338 (-9.63%)
Mutual labels:  headless-chrome
Approvejs
A simple JavaScript validation library that doesn't interfere
Stars: ✭ 336 (-10.16%)
Mutual labels:  javascript-library
Chrome Headless Browser Docker
Continuously building Chrome Docker image for Linux.
Stars: ✭ 323 (-13.64%)
Mutual labels:  headless-chrome
Js Library Boilerplate Basic
Javascript Minimal Starter Boilerplate - Webpack 5 🚀, Babel 7, UMD, Unit Testing
Stars: ✭ 354 (-5.35%)
Mutual labels:  javascript-library
Ionic Boilerplate
✨ An Ionic Starter kit featuring Tests, E2E, Karma, Protractor, Jasmine, Istanbul, Gitlab CI, Automatic IPA and APK, TypeScript 2, TsLint, Codelyzer, Typedoc, Yarn, Rollup, and Webpack 2
Stars: ✭ 309 (-17.38%)
Mutual labels:  headless-chrome
Fluid Player
Fluid Player - an open source VAST compliant HTML5 video player
Stars: ✭ 359 (-4.01%)
Mutual labels:  javascript-library
Macos Fortress
Firewall and Privatizing Proxy for Trackers, Attackers, Malware, Adware, and Spammers with Anti-Virus On-Demand and On-Access Scanning (PF, squid, privoxy, hphosts, dshield, emergingthreats, hostsfile, PAC file, clamav)
Stars: ✭ 307 (-17.91%)
Mutual labels:  proxy-server
Nodepolus
NodePolus is a JavaScript library containing multiple implementations of the Among Us network protocol.
Stars: ✭ 331 (-11.5%)
Mutual labels:  javascript-library
Josh.js
A JavaScript library to animate content on page scroll.
Stars: ✭ 345 (-7.75%)
Mutual labels:  javascript-library
Radialmenu
A highly customizable radial menu that's very easy to setup.
Stars: ✭ 371 (-0.8%)
Mutual labels:  javascript-library
Webster
a reliable high-level web crawling & scraping framework for Node.js.
Stars: ✭ 364 (-2.67%)
Mutual labels:  headless-chrome

Programmable HTTP proxy server for Node.js

npm version Build Status

Node.js implementation of a proxy server (think Squid) with support for SSL, authentication, upstream proxy chaining, custom HTTP responses and measuring traffic statistics. The authentication and proxy chaining configuration is defined in code and can be dynamic. Note that the proxy server only supports Basic authentication (see Proxy-Authorization for details).

For example, this package is useful if you need to use proxies with authentication in the headless Chrome web browser, because it doesn't accept proxy URLs such as http://username:[email protected]:8080. With this library, you can set up a local proxy server without any password that will forward requests to the upstream proxy with password. The package is used for this exact purpose by the Apify web scraping platform.

To learn more about the rationale behind this package, read How to make headless Chrome and Puppeteer use a proxy server with authentication.

Run a simple HTTP/HTTPS proxy server

const ProxyChain = require('proxy-chain');

const server = new ProxyChain.Server({ port: 8000 });

server.listen(() => {
    console.log(`Proxy server is listening on port ${8000}`);
});

Run a HTTP/HTTPS proxy server with credentials and upstream proxy

const ProxyChain = require('proxy-chain');

const server = new ProxyChain.Server({
    // Port where the server will listen. By default 8000.
    port: 8000,

    // Enables verbose logging
    verbose: true,

    // Custom user-defined function to authenticate incoming proxy requests,
    // and optionally provide the URL to chained upstream proxy.
    // The function must return an object (or promise resolving to the object) with the following signature:
    // { requestAuthentication: Boolean, upstreamProxyUrl: String }
    // If the function is not defined or is null, the server runs in simple mode.
    // Note that the function takes a single argument with the following properties:
    // * request      - An instance of http.IncomingMessage class with information about the client request
    //                  (which is either HTTP CONNECT for SSL protocol, or other HTTP request)
    // * username     - Username parsed from the Proxy-Authorization header. Might be empty string.
    // * password     - Password parsed from the Proxy-Authorization header. Might be empty string.
    // * hostname     - Hostname of the target server
    // * port         - Port of the target server
    // * isHttp       - If true, this is a HTTP request, otherwise it's a HTTP CONNECT tunnel for SSL
    //                  or other protocols
    // * connectionId - Unique ID of the HTTP connection. It can be used to obtain traffic statistics.
    prepareRequestFunction: ({ request, username, password, hostname, port, isHttp, connectionId }) => {
        return {
            // If set to true, the client is sent HTTP 407 resposne with the Proxy-Authenticate header set,
            // requiring Basic authentication. Here you can verify user credentials.
            requestAuthentication: username !== 'bob' || password !== 'TopSecret',

            // Sets up an upstream HTTP proxy to which all the requests are forwarded.
            // If null, the proxy works in direct mode, i.e. the connection is forwarded directly
            // to the target server. This field is ignored if "requestAuthentication" is true.
            // The username and password should be URI-encoded, in case it contains some special characters.
            // See `parseUrl()` function for details.
            upstreamProxyUrl: `http://username:[email protected]:3128`,

            // If "requestAuthentication" is true, you can use the following property
            // to define a custom error message to return to the client instead of the default "Proxy credentials required"
            failMsg: 'Bad username or password, please try again.',
        };
    },
});

server.listen(() => {
  console.log(`Proxy server is listening on port ${server.port}`);
});

// Emitted when HTTP connection is closed
server.on('connectionClosed', ({ connectionId, stats }) => {
  console.log(`Connection ${connectionId} closed`);
  console.dir(stats);
});

// Emitted when HTTP request fails
server.on('requestFailed', ({ request, error }) => {
  console.log(`Request ${request.url} failed`);
  console.error(error);
});

Custom error responses

To return a custom HTTP response to indicate an error to the client, you can throw the RequestError from inside of the prepareRequestFunction function. The class constructor has the following parameters: RequestError(body, statusCode, headers). By default, the response will have Content-Type: text/plain; charset=utf-8.

const ProxyChain = require('proxy-chain');

const server = new ProxyChain.Server({
    prepareRequestFunction: ({ request, username, password, hostname, port, isHttp, connectionId }) => {
        if (username !== 'bob') {
           throw new ProxyChain.RequestError('Only Bob can use this proxy!', 400);
        }
    },
});

Measuring traffic statistics

To get traffic statistics for a certain HTTP connection, you can use:

const stats = server.getConnectionStats(connectionId);
console.dir(stats);

The resulting object looks like:

{
    // Number of bytes sent to client
    srcTxBytes: Number,
    // Number of bytes received from client
    srcRxBytes: Number,
    // Number of bytes sent to target server (proxy or website)
    trgTxBytes: Number,
    // Number of bytes received from target server (proxy or website)
    trgRxBytes: Number,
}

If the underlying sockets were closed, the corresponding values will be null, rather than 0.

Custom responses

Custom responses allow you to override the response to a HTTP requests to the proxy, without contacting any target host. For example, this is useful if you want to provide a HTTP proxy-style interface to an external API or respond with some custom page to certain requests. Note that this feature is only available for HTTP connections. That's because HTTPS connections cannot be intercepted without access to the target host's private key.

To provide a custom response, the result of the prepareRequestFunction function must define the customResponseFunction property, which contains a function that generates the custom response. The function is passed no parameters and it must return an object (or a promise resolving to an object) with the following properties:

{
  // Optional HTTP status code of the response. By default it is 200.
  statusCode: 200,

  // Optional HTTP headers of the response
  headers: {
    'X-My-Header': 'bla bla',
  }

  // Optional string with the body of the HTTP response
  body: 'My custom response',

  // Optional encoding of the body. If not provided, defaults to 'UTF-8'
  encoding: 'UTF-8',
}

Here is a simple example:

const ProxyChain = require('proxy-chain');

const server = new ProxyChain.Server({
    port: 8000,
    prepareRequestFunction: ({ request, username, password, hostname, port, isHttp }) => {
        return {
            customResponseFunction: () => {
                return {
                    statusCode: 200,
                    body: `My custom response to ${request.url}`,
                };
            },
        };
    },
});

server.listen(() => {
  console.log(`Proxy server is listening on port ${server.port}`);
});

Closing the server

To shut down the proxy server, call the close([destroyConnections], [callback]) function. For example:

server.close(true, () => {
  console.log('Proxy server was closed.');
});

The closeConnections parameter indicates whether pending proxy connections should be forcibly closed. If it's false, the function will wait until all connections are closed, which can take a long time. If the callback parameter is omitted, the function returns a promise.

Accessing the CONNECT response headers for proxy tunneling

Some upstream proxy providers might include valuable debugging information in the CONNECT response headers when establishing the proxy tunnel, for they may not modify future data in the tunneled connection.

The proxy server would emit a tunnelConnectResponded event for exposing such information, where the parameter types of the event callback are described in Node.js's documentation. Example:

server.on('tunnelConnectResponded', ({ response, socket, head }) => {
    console.log(`CONNECT response headers received: ${response.headers}`);
});

Alternatively a helper function may be used:

listenConnectAnonymizedProxy(anonymizedProxyUrl, ({ response, socket, head }) => {
    console.log(`CONNECT response headers received: ${response.headers}`);
});

Helper functions

The package also provides several utility functions.

anonymizeProxy(proxyUrl, callback)

Parses and validates a HTTP proxy URL. If the proxy requires authentication, then the function starts an open local proxy server that forwards to the proxy. The port is chosen randomly.

The function takes an optional callback that receives the anonymous proxy URL. If no callback is supplied, the function returns a promise that resolves to a String with anonymous proxy URL or the original URL if it was already anonymous.

The following example shows how you can use a proxy with authentication from headless Chrome and Puppeteer. For details, read this blog post.

const puppeteer = require('puppeteer');
const proxyChain = require('proxy-chain');

(async() => {
    const oldProxyUrl = 'http://bob:[email protected]:8000';
    const newProxyUrl = await proxyChain.anonymizeProxy(oldProxyUrl);

    // Prints something like "http://127.0.0.1:45678"
    console.log(newProxyUrl);

    const browser = await puppeteer.launch({
        args: [`--proxy-server=${newProxyUrl}`],
    });

    // Do your magic here...
    const page = await browser.newPage();
    await page.goto('https://www.example.com');
    await page.screenshot({ path: 'example.png' });
    await browser.close();

    // Clean up
    await proxyChain.closeAnonymizedProxy(newProxyUrl, true);
})();

closeAnonymizedProxy(anonymizedProxyUrl, closeConnections, callback)

Closes anonymous proxy previously started by anonymizeProxy(). If proxy was not found or was already closed, the function has no effect and its result is false. Otherwise the result is true.

The closeConnections parameter indicates whether pending proxy connections are forcibly closed. If it's false, the function will wait until all connections are closed, which can take a long time.

The function takes an optional callback that receives the result Boolean from the function. If callback is not provided, the function returns a promise instead.

createTunnel(proxyUrl, targetHost, options, callback)

Creates a TCP tunnel to targetHost that goes through a HTTP proxy server specified by the proxyUrl parameter.

The optional options parameter is an object with the following properties:

  • port: Number - Enables specifying the local port to listen at. By default 0, which means a random port will be selected.
  • hostname: String - Local hostname to listen at. By default localhost.
  • verbose: Boolean - If true, the functions logs a lot. By default false.

The result of the function is a local endpoint in a form of hostname:port. All TCP connections made to the local endpoint will be tunneled through the proxy to the target host and port. For example, this is useful if you want to access a certain service from a specific IP address.

The tunnel should be eventually closed by calling the closeTunnel() function.

The createTunnel() function accepts an optional Node.js-style callback that receives the path to the local endpoint. If no callback is supplied, the function returns a promise that resolves to a String with the path to the local endpoint.

For more information, read this blog post.

Example:

const host = await createTunnel('http://bob:[email protected]:8000', 'service.example.com:356');
// Prints something like "localhost:56836"
console.log(host);

closeTunnel(tunnelString, closeConnections, callback)

Closes tunnel previously started by createTunnel(). The result value is false if the tunnel was not found or was already closed, otherwise it is true.

The closeConnections parameter indicates whether pending connections are forcibly closed. If it's false, the function will wait until all connections are closed, which can take a long time.

The function takes an optional callback that receives the result of the function. If the callback is not provided, the function returns a promise instead.

listenConnectAnonymizedProxy(anonymizedProxyUrl, tunnelConnectRespondedCallback)

Allows to configure a callback on the anonymized proxy URL for the CONNECT response headers. See the above section Accessing the CONNECT response headers for proxy tunneling for details.

parseUrl(url)

An utility function for parsing URLs. It parses the URL using Node.js' new URL(url) and adds the following features:

  • The result is a vanilla JavaScript object
  • port field is casted to number / null from string
  • path field is added (pathname + search)
  • both username and password is URI-decoded if possible (if not, the function keeps the username and password as is)
  • auth field is added, and it contains username + ":" + password, or an empty string.

If the URL is invalid, the function throws an error.

The username and password parsing should make it possible to parse proxy URLs containing special characters, such as http://user:pass:[email protected] or http://us%35er:[email protected]. The parsing is done on a best-effort basis. The safest way is to always URI-encode username and password before constructing the URL, according to RFC 3986.

Note that compared to the old implementation using url.parse(), the new function:

  • is unable to distinguish empty password and missing password
  • password and username are empty string if not present (or empty)
  • we are able to parse IPv6

redactUrl(url, passwordReplacement)

Takes a URL and hides the password from it. For example:

// Prints 'http://bob:<redacted>@example.com'
console.log(redactUrl('http://bob:[email protected]'));
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].