475 lines
16 KiB
JavaScript
475 lines
16 KiB
JavaScript
'use strict';
|
||
|
||
/**
|
||
* 集成测试:覆盖配置校验、HTTP 代理、CONNECT 隧道、SOCKS5、认证与 IP 白名单。
|
||
* 运行:npm test
|
||
*/
|
||
|
||
const test = require('node:test');
|
||
const assert = require('node:assert');
|
||
const http = require('node:http');
|
||
const net = require('node:net');
|
||
|
||
const { normalizeConfig } = require('../src/config');
|
||
const { ProxyManager } = require('../src/proxyManager');
|
||
const { IpFilter } = require('../src/ipFilter');
|
||
|
||
/** 静默日志器,避免测试输出被日志淹没 */
|
||
const quietLogger = {
|
||
level: 'error',
|
||
setLevel() {},
|
||
error() {},
|
||
warn() {},
|
||
info() {},
|
||
debug() {},
|
||
recent() {
|
||
return [];
|
||
},
|
||
};
|
||
|
||
/**
|
||
* 生成一份测试用配置。
|
||
* @param {object} [overrides] 覆盖字段
|
||
* @returns {object}
|
||
*/
|
||
function baseConfig(overrides = {}) {
|
||
return normalizeConfig({
|
||
admin: { host: '127.0.0.1', port: 58787 },
|
||
http: { enabled: true, host: '127.0.0.1', port: 0, username: '', password: '' },
|
||
socks5: { enabled: true, host: '127.0.0.1', port: 0, username: '', password: '' },
|
||
targetFilter: { mode: 'allowAll', allowList: [] },
|
||
logLevel: 'error',
|
||
...overrides,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 启动一个返回固定内容的 HTTP 服务。
|
||
* @returns {Promise<{server: import('node:http').Server, port: number}>}
|
||
*/
|
||
async function startHttpTarget() {
|
||
const server = http.createServer((req, res) => {
|
||
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' });
|
||
res.end(`hello ${req.url}`);
|
||
});
|
||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||
return { server, port: server.address().port };
|
||
}
|
||
|
||
/**
|
||
* 启动一个 TCP 回声服务,用于 CONNECT 隧道测试。
|
||
* @returns {Promise<{server: import('node:net').Server, port: number, close: () => void}>}
|
||
*/
|
||
async function startEchoTarget() {
|
||
const sockets = new Set();
|
||
const server = net.createServer((socket) => {
|
||
sockets.add(socket);
|
||
socket.on('data', (chunk) => socket.write(chunk));
|
||
socket.on('close', () => sockets.delete(socket));
|
||
socket.on('error', () => {});
|
||
});
|
||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||
return {
|
||
server,
|
||
port: server.address().port,
|
||
close() {
|
||
for (const socket of sockets) socket.destroy();
|
||
server.close();
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 带 Promise 的 socket 读取缓冲器(测试专用)。
|
||
* @param {import('node:net').Socket} socket 连接
|
||
*/
|
||
function createReader(socket) {
|
||
let buffer = Buffer.alloc(0);
|
||
const waiters = [];
|
||
|
||
socket.on('data', (chunk) => {
|
||
buffer = Buffer.concat([buffer, chunk]);
|
||
flush();
|
||
});
|
||
socket.on('close', flush);
|
||
|
||
function flush() {
|
||
while (waiters.length > 0) {
|
||
const waiter = waiters[0];
|
||
if (buffer.length >= waiter.size) {
|
||
waiters.shift();
|
||
const data = buffer.subarray(0, waiter.size);
|
||
buffer = buffer.subarray(waiter.size);
|
||
waiter.resolve(data);
|
||
} else break;
|
||
}
|
||
}
|
||
|
||
return {
|
||
/**
|
||
* 读取指定字节。
|
||
* @param {number} size 字节数
|
||
* @returns {Promise<Buffer>}
|
||
*/
|
||
read(size) {
|
||
return new Promise((resolve) => {
|
||
waiters.push({ size, resolve });
|
||
flush();
|
||
});
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 通过 HTTP 代理发起普通请求。
|
||
* @param {number} proxyPort 代理端口
|
||
* @param {string} url 目标绝对地址
|
||
* @param {Record<string, string>} [headers] 附加请求头
|
||
* @returns {Promise<{status: number, body: string}>}
|
||
*/
|
||
function httpViaProxy(proxyPort, url, headers = {}) {
|
||
return new Promise((resolve, reject) => {
|
||
const request = http.request(
|
||
{
|
||
host: '127.0.0.1',
|
||
port: proxyPort,
|
||
method: 'GET',
|
||
path: url,
|
||
headers: { host: new URL(url).host, ...headers },
|
||
},
|
||
(res) => {
|
||
let body = '';
|
||
res.setEncoding('utf8');
|
||
res.on('data', (chunk) => {
|
||
body += chunk;
|
||
});
|
||
res.on('end', () => resolve({ status: res.statusCode, body }));
|
||
},
|
||
);
|
||
request.on('error', reject);
|
||
request.end();
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 建立 CONNECT 隧道。
|
||
* @param {number} proxyPort 代理端口
|
||
* @param {string} target "host:port"
|
||
* @param {string} [extraHeaders] 附加请求头(例如认证)
|
||
* @returns {Promise<{socket: import('node:net').Socket, head: string}>}
|
||
*/
|
||
function connectViaProxy(proxyPort, target, extraHeaders = '') {
|
||
return new Promise((resolve, reject) => {
|
||
const socket = net.connect(proxyPort, '127.0.0.1');
|
||
let buffer = '';
|
||
let settled = false;
|
||
socket.setEncoding('utf8');
|
||
socket.on('data', (chunk) => {
|
||
if (settled) return;
|
||
buffer += chunk;
|
||
if (buffer.includes('\r\n\r\n')) {
|
||
settled = true;
|
||
resolve({ socket, head: buffer });
|
||
}
|
||
});
|
||
socket.on('error', reject);
|
||
socket.write(`CONNECT ${target} HTTP/1.1\r\nHost: ${target}\r\n${extraHeaders}\r\n`);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 完成 SOCKS5 握手并建立 CONNECT。
|
||
* @param {number} proxyPort 代理端口
|
||
* @param {{host: string, port: number, username?: string, password?: string}} options 目标与凭据
|
||
* @returns {Promise<{socket: import('node:net').Socket, authStatus: number, reply: number}>}
|
||
*/
|
||
async function socks5Connect(proxyPort, options) {
|
||
const socket = net.connect(proxyPort, '127.0.0.1');
|
||
const reader = createReader(socket);
|
||
await new Promise((resolve, reject) => {
|
||
socket.once('connect', resolve);
|
||
socket.once('error', reject);
|
||
});
|
||
|
||
const useAuth = Boolean(options.username);
|
||
socket.write(Buffer.from([0x05, 0x01, useAuth ? 0x02 : 0x00]));
|
||
|
||
const methodReply = await reader.read(2);
|
||
assert.strictEqual(methodReply[0], 0x05, 'SOCKS5 版本应为 5');
|
||
const expectedMethod = useAuth ? 0x02 : 0x00;
|
||
assert.strictEqual(methodReply[1], expectedMethod, `协商方法应为 ${expectedMethod}`);
|
||
|
||
let authStatus = 0;
|
||
if (useAuth) {
|
||
const userName = Buffer.from(options.username, 'utf8');
|
||
const password = Buffer.from(options.password || '', 'utf8');
|
||
const payload = Buffer.concat([
|
||
Buffer.from([0x01, userName.length]),
|
||
userName,
|
||
Buffer.from([password.length]),
|
||
password,
|
||
]);
|
||
socket.write(payload);
|
||
const authReply = await reader.read(2);
|
||
authStatus = authReply[1];
|
||
if (authStatus !== 0x00) return { socket, authStatus, reply: -1 };
|
||
}
|
||
|
||
const hostBuffer = Buffer.from(options.host, 'utf8');
|
||
const request = Buffer.concat([
|
||
Buffer.from([0x05, 0x01, 0x00, 0x03, hostBuffer.length]),
|
||
hostBuffer,
|
||
Buffer.from([(options.port >> 8) & 0xff, options.port & 0xff]),
|
||
]);
|
||
socket.write(request);
|
||
|
||
const reply = await reader.read(10);
|
||
return { socket, authStatus, reply: reply[1] };
|
||
}
|
||
|
||
/**
|
||
* 启一个代理实例跑测试,结束后清理。
|
||
* @param {object} overrides 配置覆盖
|
||
* @param {(ctx: {httpPort: number, socksPort: number, manager: ProxyManager}) => Promise<void>} fn 测试内容
|
||
*/
|
||
async function withProxy(overrides, fn) {
|
||
const config = baseConfig(overrides);
|
||
const manager = new ProxyManager({ config, logger: quietLogger });
|
||
await manager.apply(config);
|
||
const status = manager.getStatus();
|
||
try {
|
||
await fn({ httpPort: status.http.actualPort, socksPort: status.socks5.actualPort, manager });
|
||
} finally {
|
||
manager.stopAll();
|
||
}
|
||
}
|
||
|
||
test('配置校验:非法端口、端口冲突、非法 IP 规则都应报错', () => {
|
||
assert.throws(() => normalizeConfig({ http: { port: 70000 } }), /端口不合法/);
|
||
assert.throws(
|
||
() => normalizeConfig({ http: { port: 8080 }, socks5: { port: 8080 }, admin: { port: 1 } }),
|
||
/端口冲突/,
|
||
);
|
||
assert.throws(
|
||
() => normalizeConfig({ targetFilter: { mode: 'allowList', allowList: ['999.1.1.1'] } }),
|
||
/无法识别的 IP/,
|
||
);
|
||
assert.throws(
|
||
() => normalizeConfig({ http: { port: 8080, username: '', password: 'x' } }),
|
||
/用户名/,
|
||
);
|
||
const ok = normalizeConfig({ targetFilter: { mode: 'allowList', allowList: ['10.0.0.0/8', '2001:db8::/32'] } });
|
||
assert.deepStrictEqual(ok.targetFilter.allowList, ['10.0.0.0/8', '2001:db8::/32']);
|
||
});
|
||
|
||
test('IP 过滤器:单 IP、CIDR、IPv6 与 IPv4-mapped 匹配', () => {
|
||
const filter = new IpFilter({ mode: 'allowList', allowList: ['192.168.1.5', '10.0.0.0/8', '2001:db8::/32'] });
|
||
assert.strictEqual(filter.allows('192.168.1.5'), true);
|
||
assert.strictEqual(filter.allows('192.168.1.6'), false);
|
||
assert.strictEqual(filter.allows('10.20.30.40'), true);
|
||
assert.strictEqual(filter.allows('2001:db8::1'), true);
|
||
assert.strictEqual(filter.allows('2001:db9::1'), false);
|
||
// IPv4-mapped IPv6 应归一到 IPv4 规则
|
||
assert.strictEqual(filter.allows('::ffff:10.1.2.3'), true);
|
||
|
||
const allowAll = new IpFilter({ mode: 'allowAll' });
|
||
assert.strictEqual(allowAll.allows('8.8.8.8'), true);
|
||
|
||
const emptyList = new IpFilter({ mode: 'allowList', allowList: [] });
|
||
assert.strictEqual(emptyList.allows('8.8.8.8'), false);
|
||
});
|
||
|
||
test('HTTP 代理:转发普通请求', async () => {
|
||
const target = await startHttpTarget();
|
||
try {
|
||
await withProxy({}, async ({ httpPort }) => {
|
||
const result = await httpViaProxy(httpPort, `http://127.0.0.1:${target.port}/abc?x=1`);
|
||
assert.strictEqual(result.status, 200);
|
||
assert.strictEqual(result.body, 'hello /abc?x=1');
|
||
});
|
||
} finally {
|
||
target.server.close();
|
||
}
|
||
});
|
||
|
||
test('HTTP 代理:CONNECT 隧道可双向传输', async () => {
|
||
const echo = await startEchoTarget();
|
||
try {
|
||
await withProxy({}, async ({ httpPort }) => {
|
||
const { socket, head } = await connectViaProxy(httpPort, `127.0.0.1:${echo.port}`);
|
||
assert.match(head, /200 Connection Established/);
|
||
const reply = await new Promise((resolve) => {
|
||
socket.write('ping-through-tunnel\n');
|
||
socket.once('data', (chunk) => resolve(chunk.toString()));
|
||
});
|
||
assert.strictEqual(reply, 'ping-through-tunnel\n');
|
||
socket.destroy();
|
||
});
|
||
} finally {
|
||
echo.close();
|
||
}
|
||
});
|
||
|
||
test('HTTP 代理:开启认证后无凭据 407,凭据正确才放行', async () => {
|
||
const target = await startHttpTarget();
|
||
try {
|
||
await withProxy({ http: { enabled: true, host: '127.0.0.1', port: 0, username: 'user', password: 'pass' } }, async ({ httpPort }) => {
|
||
const url = `http://127.0.0.1:${target.port}/auth`;
|
||
|
||
const noAuth = await httpViaProxy(httpPort, url);
|
||
assert.strictEqual(noAuth.status, 407);
|
||
|
||
const badPassword = Buffer.from('user:wrong').toString('base64');
|
||
const denied = await httpViaProxy(httpPort, url, { 'proxy-authorization': `Basic ${badPassword}` });
|
||
assert.strictEqual(denied.status, 407);
|
||
|
||
const good = Buffer.from('user:pass').toString('base64');
|
||
const allowed = await httpViaProxy(httpPort, url, { 'proxy-authorization': `Basic ${good}` });
|
||
assert.strictEqual(allowed.status, 200);
|
||
assert.strictEqual(allowed.body, 'hello /auth');
|
||
|
||
// CONNECT 同样受认证保护
|
||
const tunnel = await connectViaProxy(httpPort, `127.0.0.1:${target.port}`);
|
||
assert.match(tunnel.head, /407 Proxy Authentication Required/);
|
||
tunnel.socket.destroy();
|
||
|
||
const tunnelOk = await connectViaProxy(
|
||
httpPort,
|
||
`127.0.0.1:${target.port}`,
|
||
`Proxy-Authorization: Basic ${good}\r\n`,
|
||
);
|
||
assert.match(tunnelOk.head, /200 Connection Established/);
|
||
tunnelOk.socket.destroy();
|
||
});
|
||
} finally {
|
||
target.server.close();
|
||
}
|
||
});
|
||
|
||
test('SOCKS5:无认证时可直接建立隧道并访问目标', async () => {
|
||
const target = await startHttpTarget();
|
||
try {
|
||
await withProxy({}, async ({ socksPort }) => {
|
||
const { reply, socket } = await socks5Connect(socksPort, { host: '127.0.0.1', port: target.port });
|
||
assert.strictEqual(reply, 0x00, 'CONNECT 应成功');
|
||
|
||
const response = await new Promise((resolve) => {
|
||
socket.write(`GET /socks HTTP/1.1\r\nHost: 127.0.0.1:${target.port}\r\nConnection: close\r\n\r\n`);
|
||
let buffer = '';
|
||
socket.on('data', (chunk) => {
|
||
buffer += chunk.toString('utf8');
|
||
});
|
||
socket.on('end', () => resolve(buffer));
|
||
});
|
||
|
||
assert.match(response, /200 OK/);
|
||
assert.match(response, /hello \/socks/);
|
||
socket.destroy();
|
||
});
|
||
} finally {
|
||
target.server.close();
|
||
}
|
||
});
|
||
|
||
test('SOCKS5:用户名密码认证生效', async () => {
|
||
const target = await startHttpTarget();
|
||
try {
|
||
await withProxy(
|
||
{ socks5: { enabled: true, host: '127.0.0.1', port: 0, username: 'sock', password: '123456' } },
|
||
async ({ socksPort }) => {
|
||
// 未提供凭据时服务端只接受用户名密码方式
|
||
const anonymous = net.connect(socksPort, '127.0.0.1');
|
||
const reader = createReader(anonymous);
|
||
await new Promise((resolve) => anonymous.once('connect', resolve));
|
||
anonymous.write(Buffer.from([0x05, 0x01, 0x00]));
|
||
const methodReply = await reader.read(2);
|
||
assert.strictEqual(methodReply[1], 0xff, '应该没有可接受的方法');
|
||
anonymous.destroy();
|
||
|
||
// 密码错误
|
||
const wrong = await socks5Connect(socksPort, {
|
||
host: '127.0.0.1',
|
||
port: target.port,
|
||
username: 'sock',
|
||
password: 'bad',
|
||
});
|
||
assert.notStrictEqual(wrong.authStatus, 0x00);
|
||
wrong.socket.destroy();
|
||
|
||
// 密码正确
|
||
const ok = await socks5Connect(socksPort, {
|
||
host: '127.0.0.1',
|
||
port: target.port,
|
||
username: 'sock',
|
||
password: '123456',
|
||
});
|
||
assert.strictEqual(ok.authStatus, 0x00);
|
||
assert.strictEqual(ok.reply, 0x00);
|
||
ok.socket.destroy();
|
||
},
|
||
);
|
||
} finally {
|
||
target.server.close();
|
||
}
|
||
});
|
||
|
||
test('目标 IP 白名单:不在列表内的目标被拒绝(HTTP 403 / SOCKS5 0x02)', async () => {
|
||
const target = await startHttpTarget();
|
||
try {
|
||
await withProxy({ targetFilter: { mode: 'allowList', allowList: ['10.0.0.0/8'] } }, async ({ httpPort, socksPort }) => {
|
||
const blocked = await httpViaProxy(httpPort, `http://127.0.0.1:${target.port}/blocked`);
|
||
assert.strictEqual(blocked.status, 403);
|
||
assert.match(blocked.body, /不在允许列表/);
|
||
|
||
const { reply, socket } = await socks5Connect(socksPort, { host: '127.0.0.1', port: target.port });
|
||
assert.strictEqual(reply, 0x02, 'SOCKS5 应返回 not allowed');
|
||
socket.destroy();
|
||
});
|
||
|
||
await withProxy({ targetFilter: { mode: 'allowList', allowList: ['127.0.0.0/8'] } }, async ({ httpPort }) => {
|
||
const allowed = await httpViaProxy(httpPort, `http://127.0.0.1:${target.port}/allowed`);
|
||
assert.strictEqual(allowed.status, 200);
|
||
assert.strictEqual(allowed.body, 'hello /allowed');
|
||
});
|
||
} finally {
|
||
target.server.close();
|
||
}
|
||
});
|
||
|
||
test('状态快照:统计连接数与端口信息', async () => {
|
||
const target = await startHttpTarget();
|
||
try {
|
||
await withProxy({}, async ({ httpPort, manager }) => {
|
||
await httpViaProxy(httpPort, `http://127.0.0.1:${target.port}/stats`);
|
||
const status = manager.getStatus();
|
||
assert.strictEqual(status.http.listening, true);
|
||
assert.ok(status.http.actualPort > 0);
|
||
assert.ok(status.stats.http.total >= 1);
|
||
assert.ok(status.stats.http.bytesDown > 0);
|
||
});
|
||
} finally {
|
||
target.server.close();
|
||
}
|
||
});
|
||
|
||
test('带宽采样:传输数据后能算出上下行速率与趋势点', async () => {
|
||
const target = await startHttpTarget();
|
||
try {
|
||
await withProxy({}, async ({ httpPort, manager }) => {
|
||
await httpViaProxy(httpPort, `http://127.0.0.1:${target.port}/speed`);
|
||
|
||
// 手动触发一次采样,避免依赖 1 秒定时器
|
||
const rates = manager.stats.sample();
|
||
const stats = manager.getStatus().stats;
|
||
|
||
assert.ok(rates.down > 0, '应有下行速率');
|
||
assert.ok(stats.rates.total.down > 0, '快照中应有合计下行速率');
|
||
assert.ok(stats.rates.http.down > 0, 'HTTP 卡片应有下行速率');
|
||
assert.ok(stats.history.length >= 1, '应有趋势采样点');
|
||
assert.ok(stats.peak.down > 0, '应记录峰值下行速率');
|
||
});
|
||
} finally {
|
||
target.server.close();
|
||
}
|
||
});
|