/
test.ts
361 lines (316 loc) · 9.29 KB
/
test.ts
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import assert from 'assert';
import * as https from 'https';
import * as http from 'http';
import * as path from 'path';
import * as fs from 'fs';
import { URL } from 'url';
import dns2 from 'dns2';
// @ts-expect-error no types
import socks from 'socksv5';
import CacheableLookup from 'cacheable-lookup';
import { listen } from 'async-listen';
import { req, json } from 'agent-base';
import { SocksProxyAgent } from '../src';
import { once } from 'events';
describe('SocksProxyAgent', () => {
let httpServer: http.Server;
let httpServerUrl: URL;
let httpsServer: https.Server;
let httpsServerUrl: URL;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let socksServer: any;
let socksServerUrl: URL;
let socksServerHost: string | null = null;
beforeEach(async () => {
// setup SOCKS proxy server
// @ts-expect-error no types for `socksv5`
socksServer = socks.createServer(function (_info, accept) {
accept();
});
await listen(socksServer, 0, socksServerHost ?? '127.0.0.1');
const { port, family, address } = socksServer.address();
socksServerUrl = new URL(
`socks://${family === 'IPv6' ? 'localhost' : address}:${port}`
);
socksServer.useAuth(socks.auth.None());
});
afterEach(() => {
socksServer.close();
});
beforeAll(async () => {
// setup target HTTP server
httpServer = http.createServer();
httpServerUrl = await listen(httpServer);
});
beforeAll(async () => {
// setup target SSL HTTPS server
const options = {
key: fs.readFileSync(
path.resolve(__dirname, 'ssl-cert-snakeoil.key')
),
cert: fs.readFileSync(
path.resolve(__dirname, 'ssl-cert-snakeoil.pem')
),
};
httpsServer = https.createServer(options);
httpsServerUrl = await listen(httpsServer);
});
afterAll(() => {
httpServer.close();
httpsServer.close();
});
beforeEach(() => {
httpServer.removeAllListeners('request');
httpsServer.removeAllListeners('request');
});
describe('constructor', () => {
it('should accept a "string" proxy argument', () => {
const agent = new SocksProxyAgent(socksServerUrl.href);
assert.equal(socksServerUrl.hostname, agent.proxy.host);
assert.equal(+socksServerUrl.port, agent.proxy.port);
});
it('should accept a `new URL()` result object argument', () => {
const agent = new SocksProxyAgent(socksServerUrl);
assert.equal(socksServerUrl.hostname, agent.proxy.host);
assert.equal(+socksServerUrl.port, agent.proxy.port);
});
it('should respect `timeout` option during connection to socks server', async () => {
const agent = new SocksProxyAgent(socksServerUrl, { timeout: 1 });
let err: Error | undefined;
try {
await req('http://example.com', { agent });
} catch (_err) {
err = _err as Error;
}
assert(err);
assert.equal(err.message, 'Proxy connection timed out');
});
});
describe('ipv6 host', () => {
beforeAll(() => {
socksServerHost = '::1';
});
afterAll(() => {
socksServerHost = null;
});
it('should connect over ipv6 socket', async () => {
httpServer.once('request', (req, res) => res.end());
const res = await req(new URL('/foo', httpServerUrl), {
agent: new SocksProxyAgent(socksServerUrl, { socketOptions: { family: 6 } }),
});
assert(res);
});
it('should refuse connection over ipv4 socket', async () => {
let err: Error | undefined;
try {
await req(new URL('/foo', httpServerUrl), {
agent: new SocksProxyAgent(socksServerUrl, { socketOptions: { family: 4 } }),
});
} catch (_err) {
err = _err as Error;
}
assert(err);
assert.equal(err.message, `connect ECONNREFUSED 127.0.0.1:${socksServerUrl.port}`);
});
});
describe('"http" module', () => {
it('should work against an HTTP endpoint', async () => {
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),
headers: { foo: 'bar' },
});
assert.equal(404, res.statusCode);
const body = await json(res);
assert.equal('bar', body.foo);
});
it('should work with username/password auth', async () => {
let authWasCalled = false;
socksServer._auths.pop();
socksServer.useAuth(
socks.auth.UserPassword(
(
user: string,
password: string,
cb: (valid: boolean) => void
) => {
authWasCalled = true;
cb(user === 'nodejs' && password === 'rules!');
}
)
);
socksServerUrl.username = 'nodejs'
socksServerUrl.password = 'rules!'
console.log(socksServerUrl.href)
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),
headers: { foo: 'bar' },
});
assert(authWasCalled);
assert.equal(404, res.statusCode);
const body = await json(res);
assert.equal('bar', body.foo);
});
it('should emit "error" event if username/password auth fails', async () => {
let authWasCalled = false;
socksServer._auths.pop();
socksServer.useAuth(
socks.auth.UserPassword(
(
user: string,
password: string,
cb: (valid: boolean) => void
) => {
authWasCalled = true;
cb(user === 'nodejs' && password === 'rules!');
}
)
);
socksServerUrl.username = 'nodejs'
socksServerUrl.password = 'bad'
let err: Error | undefined;
try {
await req(new URL('/foo', httpServerUrl), {
agent: new SocksProxyAgent(socksServerUrl),
headers: { foo: 'bar' },
});
} catch (_err) {
err = _err as Error;
}
assert(authWasCalled);
assert(err);
assert.equal(err.message, `Socks5 Authentication failed`);
});
});
describe('"https" module', () => {
it('should work against an HTTPS endpoint', async () => {
httpsServer.once('request', function (req, res) {
assert.equal('/foo', req.url);
res.statusCode = 404;
res.end(JSON.stringify(req.headers));
});
const res = await req(
`https://127.0.0.1:${httpsServerUrl.port}/foo`,
{
agent: new SocksProxyAgent(socksServerUrl),
rejectUnauthorized: false,
headers: { foo: 'bar' },
}
);
assert.equal(404, res.statusCode);
const body = await json(res);
assert.equal('bar', body.foo);
});
});
describe('Custom lookup option', () => {
let dnsServer: ReturnType<typeof dns2.createServer>;
let dnsQueries: { type: string; name: string }[];
beforeAll(async () => {
dnsQueries = [];
// A custom DNS server that always replies with 127.0.0.1:
dnsServer = dns2.createServer({
udp: true,
handle: (request, send) => {
const response =
dns2.Packet.createResponseFromRequest(request);
const [question] = request.questions;
const { name } = question;
dnsQueries.push({
// @ts-expect-error meh
type: question.type,
name: question.name,
});
response.answers.push({
name,
type: dns2.Packet.TYPE.A,
class: dns2.Packet.CLASS.IN,
ttl: 300,
address: '127.0.0.1',
});
send(response);
},
});
dnsServer.listen({ udp: 5333 });
await once(dnsServer, 'listening');
});
afterAll(() => {
dnsServer.close();
});
it("should use a requests's custom lookup function with socks5", async () => {
httpServer.once('request', function (req, res) {
assert.equal('/foo', req.url);
res.statusCode = 404;
res.end();
});
const agent = new SocksProxyAgent(
socksServerUrl.href.replace('socks', 'socks5')
);
try {
await req(
`http://non-existent-domain.test:${httpServerUrl.port}/foo`,
{
agent,
lookup(hostname, _opts, callback) {
if (hostname === 'non-existent-domain.test') {
// @ts-expect-error meh
callback(null, '127.0.0.1');
return;
}
// @ts-expect-error meh
callback(new Error('Bad domain'));
},
}
);
} catch (err) {
console.log(err);
}
});
it('should support caching DNS requests', async () => {
httpServer.on('request', function (req, res) {
res.statusCode = 200;
res.end();
});
const agent = new SocksProxyAgent(
socksServerUrl.href.replace('socks', 'socks5')
);
const cacheableLookup = new CacheableLookup();
cacheableLookup.servers = ['127.0.0.1:5333'];
// No DNS queries made initially
assert.deepEqual(dnsQueries, []);
const res = await req(
`http://test-domain.test:${httpServerUrl.port}/foo`,
// @ts-expect-error meh
{ agent, lookup: cacheableLookup.lookup }
);
assert.equal(200, res.statusCode);
// Initial DNS query for first request
assert.deepEqual(dnsQueries, [
{ name: 'test-domain.test', type: dns2.Packet.TYPE.A },
{ name: 'test-domain.test', type: dns2.Packet.TYPE.AAAA },
]);
const res2 = await req(
`http://test-domain.test:${httpServerUrl.port}/foo`,
// @ts-expect-error meh
{ agent, lookup: cacheableLookup.lookup }
);
assert.equal(200, res2.statusCode);
// Still the same. No new DNS queries, so the response was cached
assert.deepEqual(dnsQueries, [
{ name: 'test-domain.test', type: dns2.Packet.TYPE.A },
{
name: 'test-domain.test',
type: dns2.Packet.TYPE.AAAA,
},
]);
});
});
});