Skip to content

Redirecting a request to another server #268

Open
@Jiri-Mihal

Description

@Jiri-Mihal

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions