All files / lib globalProxy.js

22.89% Statements 19/83
0% Branches 0/34
0% Functions 0/13
25% Lines 19/76

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173                                  1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x   1x   1x             1x                       1x                                                                                                                       1x 1x             1x                                                                                             1x          
"use strict";
/**
 * Creates new instance of `GlobalProxy`.
 *
 * @class
 * @name GlobalProxy
 * @classdesc - Contains methods to run and manage global transparent proxy.
 * @arg {object} [opts] - global proxy options
 * @arg {number} [opts.port=0] - global proxy port
 * @arg {number} [opts.timeout=0] - global proxy timeout
 * @arg {boolean} [opts.installCertificate=false] - flag to install global
 *  proxy certificate as trusted in order to manage `https` connection or no
 * @arg {?string} [opts.rootPath] - Folder where proxy starts in order to
 *  generate self-signed certificate. By default is `current work directory`.
 * @arg {boolean} [opts.useCache=false] - flag to cache and take from cache responses
 */
 
var fs = require("fs");
var path = require("path");
var util = require("util");
 
var expect = require("chai").expect;
const getPort = require("get-port");
var MitmProxy = require("http-mitm-proxy").Proxy;
var spawn = require("cross-spawn");
var U = require("glace-utils");
 
var BaseProxy = require("./baseProxy");
var cache = require("./middleware/cache");
var middleware = require("./middleware");
 
var LOG = U.logger;
 
var _onError = MitmProxy.prototype._onError;
/**
 * Patch mitm proxy error processing, in order to avoid default response
 * finalizing on reconnect.
 *
 * @ignore
 */
MitmProxy.prototype._onError = function (kind, ctx, err) {
    if (!ctx) return _onError.apply(this, arguments);
    var req = ctx.clientToProxyRequest;
    if (req._reconnect > 0 && !req.socket.destroyed) {
        this.onErrorHandlers.forEach(function(handler) {
            return handler(ctx, err, kind);
        });
    } else {
        _onError.apply(this, arguments);
    };
};
 
var GlobalProxy = function (opts) {
 
    opts = U.defVal(opts, {});
    BaseProxy.call(this, opts);
 
    this._installCertificate = U.defVal(opts.installCertificate, false);
    this._sslCaDir = U.defVal(opts.sslCaDir, path.resolve(U.cwd, ".http-mitm-proxy"));
    this._certificatePath = path.resolve(this._sslCaDir, "certs", "ca.pem");
 
    this._proxy = new MitmProxy();
 
    this._proxy.onError((ctx, err) => {
 
        if (!ctx) {
            LOG.error(err);
            return;
        }
 
        var req = ctx.clientToProxyRequest;
        if (req._reconnect > 0 && !req.socket.destroyed) {
            LOG.warn(util.format("Request reconnected", U.getReqKey(req)));
            req._reconnect--;
            this._proxy._onHttpServerRequest(ctx.isSSL,
                ctx.clientToProxyRequest,
                ctx.proxyToClientResponse);
        } else {
            LOG.error(util.format(U.getReqKey(req), err));
        };
    });
 
    this._proxy.onRequest(async (ctx, callback) => {
 
        this.req = ctx.clientToProxyRequest;
        if (this.req._reconnect === undefined) {
            this.req._reconnect = this._reconnect;
        };
        this.res = ctx.proxyToClientResponse;
 
        for (var mw of middleware) if (await mw.call(this)) return;
 
        delete this.req;
        delete this.res;
 
        return callback();
    });
 
    // TODO not sure that it works reliable
    this._proxy.onRequestData((ctx, chunk, callback) => {
        if (ctx.clientToProxyRequest.body) {
            chunk = new Buffer("");
        };
        return callback(null, chunk);
    });
    this._proxy.onResponse((ctx, callback) => {
        if (ctx.clientToProxyRequest.body) {
            ctx.proxyToServerRequest.end(ctx.clientToProxyRequest.body);
        };
        return callback(null);
    });
};
util.inherits(GlobalProxy, BaseProxy);
module.exports = GlobalProxy;
/**
 * Starts global proxy if it's not started yet.
 *
 * @async
 * @method
 */
GlobalProxy.prototype.start = async function () {
    if (this.isRunning) return;
    if (!this._port) this._port = await getPort();
 
    return new Promise((resolve, reject) => {
 
        this._proxy.listen({ port: this._port,
            silent: true,
            sslCaDir: this._sslCaDir,
            timeout: this._timeout },
        err => {
            if (err) reject(err);
            resolve();
        });
 
    }).then(() => cache.init()).then(() => {
 
        this.isRunning = true;
 
        if (this._installCertificate) {
 
            if (process.platform !== "win32") {
                throw new Error("For your platform certificate" +
                                     "installation isn't implemented");
            };
            expect(fs.existsSync(this._certificatePath),
                `Proxy certificate ${this._certificatePath} is absent`)
                .to.be.true;
 
            var proc = spawn.sync("certutil", [ "-addstore",
                "-enterprise",
                "-f", "Root",
                this._certificatePath ]);
 
            if (proc.status !== 0) {
                throw new Error(
                    "Can't install proxy certificate as trusted:\n" +
                    proc.stdout.toString());
            };
        };
    });
};
/**
 * Stops global proxy if it's not stopped yet.
 *
 * @method
 */
GlobalProxy.prototype.stop = function () {
    if (!this.isRunning) return;
    this._proxy.close();
    this.isRunning = false;
};