Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support localAddress #163

Merged
merged 3 commits into from
Oct 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions src/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,22 @@ interface Options {
method: string;
headers: string[];
path?: string;
localAddress?: string;
}

export interface HandlerOpts {
upstreamProxyUrlParsed: URL;
localAddress?: string;
}

interface ChainOpts {
request: { url?: string },
sourceSocket: Socket,
head?: Buffer,
handlerOpts: HandlerOpts,
server: EventEmitter & { log: (...args: any[]) => void; },
isPlain: boolean,
request: { url?: string };
sourceSocket: Socket;
head?: Buffer;
handlerOpts: HandlerOpts;
server: EventEmitter & { log: (...args: any[]) => void; };
isPlain: boolean;
localAddress?: string;
}

export const chain = (
Expand Down Expand Up @@ -61,6 +64,7 @@ export const chain = (
'host',
request.url!,
],
localAddress: handlerOpts.localAddress,
};

if (proxy.username || proxy.password) {
Expand Down
15 changes: 11 additions & 4 deletions src/direct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,16 @@ import { EventEmitter } from 'events';
import { countTargetBytes } from './utils/count_target_bytes';
import { Socket } from './socket';

export interface HandlerOpts {
localAddress?: string;
}

interface DirectOpts {
request: { url?: string },
sourceSocket: Socket,
head: Buffer,
server: EventEmitter & { log: (...args: any[]) => void; },
request: { url?: string };
sourceSocket: Socket;
head: Buffer;
server: EventEmitter & { log: (...args: any[]) => void; };
handlerOpts: HandlerOpts;
}

export const direct = (
Expand All @@ -18,6 +23,7 @@ export const direct = (
sourceSocket,
head,
server,
handlerOpts,
}: DirectOpts,
): void => {
const url = new URL(`connect://${request.url}`);
Expand All @@ -37,6 +43,7 @@ export const direct = (
const options = {
port: Number(url.port),
host: url.hostname,
localAddress: handlerOpts.localAddress,
};

if (options.host[0] === '[') {
Expand Down
3 changes: 3 additions & 0 deletions src/forward.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ interface Options {
headers: string[];
insecureHTTPParser: boolean;
path?: string;
localAddress?: string;
}

export interface HandlerOpts {
upstreamProxyUrlParsed: URL;
localAddress?: string;
}

export const forward = async (
Expand All @@ -33,6 +35,7 @@ export const forward = async (
method: request.method!,
headers: validHeadersOnly(request.rawHeaders),
insecureHTTPParser: true,
localAddress: handlerOpts.localAddress,
};

// In case of proxy the path needs to be an absolute URL
Expand Down
18 changes: 11 additions & 7 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ type HandlerOpts = {
upstreamProxyUrlParsed: URL | null;
isHttp: boolean;
customResponseFunction: CustomResponseOpts['customResponseFunction'] | null;
localAddress?: string;
};

type PrepareRequestFunctionOpts = {
Expand All @@ -68,6 +69,7 @@ type PrepareRequestFunctionResult = {
requestAuthentication?: boolean;
failMsg?: string;
upstreamProxyUrl?: string | null;
localAddress?: string;
};

type Promisable<T> = T | Promise<T>;
Expand Down Expand Up @@ -343,7 +345,7 @@ export class Server extends EventEmitter {
* @param request
* @param handlerOpts
*/
async callPrepareRequestFunction(request: http.IncomingMessage, handlerOpts: HandlerOpts): Promise<PrepareRequestFunctionResult | undefined> {
async callPrepareRequestFunction(request: http.IncomingMessage, handlerOpts: HandlerOpts): Promise<PrepareRequestFunctionResult> {
// Authenticate the request using a user function (if provided)
if (this.prepareRequestFunction) {
const funcOpts: PrepareRequestFunctionOpts = {
Expand Down Expand Up @@ -372,11 +374,11 @@ export class Server extends EventEmitter {
funcOpts.password = auth.password!;
}

// User function returns a result directly or a promise
return this.prepareRequestFunction(funcOpts);
const result = await this.prepareRequestFunction(funcOpts);
return result ?? {};
}

return { requestAuthentication: false, upstreamProxyUrl: null };
return {};
}

/**
Expand All @@ -388,12 +390,14 @@ export class Server extends EventEmitter {
const handlerOpts = this.getHandlerOpts(request);
const funcResult = await this.callPrepareRequestFunction(request, handlerOpts);

handlerOpts.localAddress = funcResult.localAddress;

// If not authenticated, request client to authenticate
if (funcResult && funcResult.requestAuthentication) {
if (funcResult.requestAuthentication) {
throw new RequestError(funcResult.failMsg || 'Proxy credentials required.', 407);
}

if (funcResult && funcResult.upstreamProxyUrl) {
if (funcResult.upstreamProxyUrl) {
try {
handlerOpts.upstreamProxyUrlParsed = new URL(funcResult.upstreamProxyUrl);
} catch (error) {
Expand All @@ -408,7 +412,7 @@ export class Server extends EventEmitter {

const { proxyChainId } = request.socket as Socket;

if (funcResult && funcResult.customResponseFunction) {
if (funcResult.customResponseFunction) {
this.log(proxyChainId, 'Using custom response function');

handlerOpts.customResponseFunction = funcResult.customResponseFunction;
Expand Down
31 changes: 31 additions & 0 deletions test/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -1200,6 +1200,37 @@ describe('non-200 upstream connect response', () => {
});
});

it('supports localAddress', async () => {
const target = http.createServer((serverRequest, serverResponse) => {
serverResponse.end(serverRequest.socket.remoteAddress);
});

await util.promisify(target.listen.bind(target))(0);

const server = new Server({
port: 0,
prepareRequestFunction: () => {
return {
localAddress: '127.0.0.2',
};
},
});

await server.listen();

const response = await requestPromised({
url: `http://127.0.0.1:${target.address().port}`,
proxy: `http://127.0.0.2:${server.port}`,
});

try {
expect(response.body).to.be.equal('::ffff:127.0.0.2');
} finally {
await server.close();
await util.promisify(target.close.bind(target))();
}
});

// Run all combinations of test parameters
const useSslVariants = [
false,
Expand Down