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

Allow SOCKS proxies to be chained #259

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
13 changes: 13 additions & 0 deletions .changeset/plenty-lamps-tease.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'socks-proxy-agent': minor
---

You can now use SOCKS proxy chains by passing an array of SOCKS proxy URLs to the `SocksProxyAgent()` constructor:

```ts
const agent = new SocksProxyAgent([
'socks://user:pass@host:port',
'socks://user:pass@host:port',
'socks://user:pass@host:port',
]);
```
92 changes: 70 additions & 22 deletions packages/socks-proxy-agent/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { SocksClient, SocksProxy, SocksClientOptions } from 'socks';
import {
SocksClient,
SocksProxy,
SocksClientOptions,
SocksClientChainOptions,
} from 'socks';
import { Agent, AgentConnectOpts } from 'agent-base';
import createDebug from 'debug';
import * as dns from 'dns';
Expand Down Expand Up @@ -87,19 +92,40 @@ export class SocksProxyAgent extends Agent {
'socks5h',
] as const;

readonly shouldLookup: boolean;
readonly proxy: SocksProxy;
readonly shouldLookup!: boolean;
readonly proxies: SocksProxy[];
timeout: number | null;
rejectUnauthorized = true;

constructor(uri: string | URL, opts?: SocksProxyAgentOptions) {
constructor(
uri: string | URL | string[] | URL[],
opts?: SocksProxyAgentOptions & {
rejectUnauthorized?: boolean
}
) {
super(opts);

const url = typeof uri === 'string' ? new URL(uri) : uri;
const { proxy, lookup } = parseSocksURL(url);
const uriList = Array.isArray(uri) ? uri : [uri];

if (uriList.length === 0) {
throw new Error('At least one proxy server URI must be specified.');
}

this.proxies = [];
for (const [i, uri] of uriList.entries()) {
const { proxy, lookup } = parseSocksURL(new URL(uri.toString()));
this.proxies.push(proxy);
if (i === 0) {
this.shouldLookup = lookup;
}
}

this.shouldLookup = lookup;
this.proxy = proxy;
this.timeout = opts?.timeout ?? null;
this.rejectUnauthorized = opts?.rejectUnauthorized ?? true;
}

get proxy(): SocksProxy {
return this.proxies[0];
}

/**
Expand All @@ -110,7 +136,7 @@ export class SocksProxyAgent extends Agent {
req: http.ClientRequest,
opts: AgentConnectOpts
): Promise<net.Socket> {
const { shouldLookup, proxy, timeout } = this;
const { shouldLookup, proxies, timeout } = this;

if (!opts.host) {
throw new Error('No `host` defined!');
Expand All @@ -133,25 +159,46 @@ export class SocksProxyAgent extends Agent {
});
}

const socksOpts: SocksClientOptions = {
proxy,
destination: {
host,
port: typeof port === 'number' ? port : parseInt(port, 10),
},
command: 'connect',
timeout: timeout ?? undefined,
};

let socket: net.Socket;
const cleanup = (tlsSocket?: tls.TLSSocket) => {
req.destroy();
socket.destroy();
if (tlsSocket) tlsSocket.destroy();
};

debug('Creating socks proxy connection: %o', socksOpts);
const { socket } = await SocksClient.createConnection(socksOpts);
debug('Successfully created socks proxy connection');
if (proxies.length === 1) {
const socksOpts: SocksClientOptions = {
proxy: proxies[0],
destination: {
host,
port: typeof port === 'number' ? port : parseInt(port, 10),
},
command: 'connect',
timeout: timeout ?? undefined,
};

debug('Creating socks proxy connection: %o', socksOpts);
const connection = await SocksClient.createConnection(socksOpts);
socket = connection.socket;
debug('Successfully created socks proxy connection');
} else {
const socksOpts: SocksClientChainOptions = {
proxies: proxies,
destination: {
host,
port: typeof port === 'number' ? port : parseInt(port, 10),
},
command: 'connect',
timeout: timeout ?? undefined,
};

debug('Creating chained socks proxy connection: %o', socksOpts);
const connection = await SocksClient.createConnectionChain(
socksOpts
);
socket = connection.socket;
debug('Successfully created chained socks proxy connection');
}

if (timeout !== null) {
socket.setTimeout(timeout);
Expand All @@ -165,6 +212,7 @@ export class SocksProxyAgent extends Agent {
const servername = opts.servername || opts.host;
const tlsSocket = tls.connect({
...omit(opts, 'host', 'path', 'port'),
rejectUnauthorized: this.rejectUnauthorized,
socket,
servername: net.isIP(servername) ? undefined : servername,
});
Expand Down
35 changes: 35 additions & 0 deletions packages/socks-proxy-agent/test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,41 @@ describe('SocksProxyAgent', () => {
const body = await json(res);
assert.equal('bar', body.foo);
});

it('should work against an HTTP endpoint with multiple SOCKS proxies', async () => {
const secondSocksServer = socks.createServer(function (
// @ts-expect-error no types for `socksv5`
_info,
// @ts-expect-error no types for `socksv5`
accept
) {
accept();
});
await listen(secondSocksServer);
const port = secondSocksServer.address().port;
const secondSocksServerUrl = new URL(`socks://127.0.0.1:${port}`);
secondSocksServer.useAuth(socks.auth.None());

httpServer.once('request', function (req, res) {
assert.equal('/foo', req.url);
res.statusCode = 404;
res.end(JSON.stringify(req.headers));
});

const res = await req(new URL('/foo', httpServerUrl), {
agent: new SocksProxyAgent([
socksServerUrl,
secondSocksServerUrl,
]),
headers: { foo: 'bar' },
});
assert.equal(404, res.statusCode);

const body = await json(res);
assert.equal('bar', body.foo);

secondSocksServer.close();
});
});

describe('"https" module', () => {
Expand Down