node-http-mitm-proxy icon indicating copy to clipboard operation
node-http-mitm-proxy copied to clipboard

Redirecting a request to another server

Open Jiri-Mihal opened this issue 3 years ago • 0 comments

Hi,

I need to prevent a request from being sent to the target server, instead I would like to send it (unchanged, including all data) to another server and return the data from that server.

Client --> Proxy ----------------> Target
curl -k -x 'http://127.0.0.1:8081' 'https://httpbin.org/anything'

So the above CURL command should, for example, send/return data to/from 'https://127.0.0.1:443' instead of 'https://httpbin.org/anything'. Is it possible to do it with 'http-mitm-proxy'? My current code is as follows:

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

proxy.onError( (ctx, err) => {
    console.error('Proxy error: ', err);
});

async function sendAndGetData(ctx, host) {
    // !!!!! Todo !!!!!: Ideally, just passing the request to `host` without reconstructing it. Maybe via connect?
}

async function getResponse(ctx) {

    // Get proxy headers
    const sym = Object.getOwnPropertySymbols(ctx.connectRequest).find(function(s) {
        return String(s) === 'Symbol(kHeaders)';
    });
    console.log('Proxy headers: ', ctx.connectRequest[sym]);

    // Modify request headers
    // Add Proxy-Authorization header to request headers
    ctx.proxyToServerRequestOptions.headers['Proxy-Authorization'] = ctx.connectRequest[sym]['proxy-authorization'];

    // !!!!! Todo !!!!!: Here I want to send a request to https://127.0.0.1:443 and return a response from it
    return await sendAndGetData(ctx, 'https://127.0.0.1:443');
}

proxy.onConnect(async (req, socket, head, callback) => {
    // Hack: Add proxy headers to ctx. Without this ctx does not include proxy headers
    req.headers;
    return callback();
});

proxy.onRequest( async (ctx, callback) => {
    // Get request headers
    console.log('Request headers: ', ctx.clientToProxyRequest.headers);

    // Intercepting proxy
    // No callback() so proxy request is not sent to the server
    ctx.proxyToClientResponse.end(await getResponse(ctx));

    // MITM proxy
    // return callback();
});

proxy.listen({port: 8081});

Thank you in advance for any help.

Jiri-Mihal avatar Oct 08 '22 11:10 Jiri-Mihal