feat: 初始版本,支持 HTTP 代理和 SOCKS5 代理
This commit is contained in:
@@ -0,0 +1,110 @@
|
|||||||
|
# Frost Network Proxy
|
||||||
|
|
||||||
|
一个用 Node.js 写的轻量网络代理程序:**HTTP 代理 + SOCKS5 代理 + 可视化配置网页**,零第三方依赖(只用 Node 内置模块)。
|
||||||
|
|
||||||
|
## 功能
|
||||||
|
|
||||||
|
- **HTTP 代理**:支持普通 HTTP 请求转发、HTTPS 的 `CONNECT` 隧道、WebSocket(Upgrade)透传
|
||||||
|
- **SOCKS5 代理**:RFC 1928,支持 `CONNECT` 命令(UDP ASSOCIATE / BIND 会明确返回“命令不支持”)
|
||||||
|
- **自定义端口**:HTTP / SOCKS5 / 配置页面各自独立配置端口和监听地址(填 `0` 表示随机端口)
|
||||||
|
- **代理认证**:HTTP 使用 `Proxy-Authorization: Basic`,SOCKS5 使用 RFC 1929 用户名密码认证;用户名留空即关闭认证
|
||||||
|
- **目标 IP 白名单**:可限制只允许代理到指定 IP / CIDR 网段;域名会先解析成 IP 再判断
|
||||||
|
- **配置网页**:实时展示监听状态、连接数、上下行流量、运行日志,支持在线修改并立即生效
|
||||||
|
- **网络状态面板**:每 1 秒采样一次,展示各协议与合计的活跃/累计连接数、实时上传下载速率、累计流量、峰值速率,以及最近 60 秒的双线趋势图
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd frost-network-proxy
|
||||||
|
npm start # 或 node src/index.js
|
||||||
|
```
|
||||||
|
|
||||||
|
启动后终端会打印访问地址,默认:
|
||||||
|
|
||||||
|
| 用途 | 地址 |
|
||||||
|
| --- | --- |
|
||||||
|
| 配置网页 | http://127.0.0.1:8790 |
|
||||||
|
| HTTP 代理 | http://0.0.0.0:8080 |
|
||||||
|
| SOCKS5 代理 | socks5://0.0.0.0:1080 |
|
||||||
|
|
||||||
|
使用示例:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# HTTP 代理
|
||||||
|
curl -x http://127.0.0.1:8080 http://example.com
|
||||||
|
curl -x http://127.0.0.1:8080 https://example.com
|
||||||
|
|
||||||
|
# 带认证
|
||||||
|
curl -x http://user:pass@127.0.0.1:8080 https://example.com
|
||||||
|
|
||||||
|
# SOCKS5(socks5h 表示域名交给代理解析)
|
||||||
|
curl -x socks5h://user:pass@127.0.0.1:1080 https://example.com
|
||||||
|
```
|
||||||
|
|
||||||
|
## 配置文件
|
||||||
|
|
||||||
|
首次启动会在项目根目录生成 `config.json`,也可以在网页上修改后保存(保存即写回该文件并热应用)。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"admin": { "host": "127.0.0.1", "port": 8790, "username": "", "password": "" },
|
||||||
|
"http": { "enabled": true, "host": "0.0.0.0", "port": 8080, "username": "", "password": "" },
|
||||||
|
"socks5": { "enabled": true, "host": "0.0.0.0", "port": 1080, "username": "", "password": "" },
|
||||||
|
"targetFilter": { "mode": "allowAll", "allowList": [] },
|
||||||
|
"logLevel": "info"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
字段说明:
|
||||||
|
|
||||||
|
- `enabled`:是否启用该代理
|
||||||
|
- `host`:监听地址,`0.0.0.0` 为所有网卡,`127.0.0.1` 仅本机
|
||||||
|
- `port`:监听端口,`1-65535`,`0` 表示随机端口;三个监听器不能使用相同端口
|
||||||
|
- `username` / `password`:代理认证凭据,用户名留空表示不校验
|
||||||
|
- `targetFilter.mode`:`allowAll` 允许所有目标;`allowList` 仅允许 `allowList` 内的地址
|
||||||
|
- `targetFilter.allowList`:支持单 IP 与 CIDR,例如 `192.168.1.10`、`10.0.0.0/8`、`2001:db8::/32`
|
||||||
|
- `logLevel`:`error` / `warn` / `info` / `debug`,`debug` 会记录每个请求的目标地址
|
||||||
|
|
||||||
|
修改 `admin.host` 或 `admin.port` 后保存,页面会自动切到新地址;改动其他项则立即生效、无需重启。
|
||||||
|
|
||||||
|
## 目录结构
|
||||||
|
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
index.js 程序入口:加载配置 → 启动代理 → 启动配置页面
|
||||||
|
config.js 配置校验与持久化
|
||||||
|
proxyManager.js 监听器生命周期管理、状态快照
|
||||||
|
httpProxy.js HTTP 代理(请求转发 / CONNECT / Upgrade)
|
||||||
|
socks5.js SOCKS5 代理(握手、认证、CONNECT)
|
||||||
|
resolver.js 目标域名解析 + 白名单校验
|
||||||
|
ipFilter.js IP / CIDR 匹配
|
||||||
|
auth.js Basic 与用户名密码校验
|
||||||
|
stats.js 连接数、累计流量与带宽采样统计
|
||||||
|
logger.js 日志(带内存缓冲供页面展示)
|
||||||
|
util.js 监听封装、双向管道
|
||||||
|
public/
|
||||||
|
index.html 配置页面
|
||||||
|
app.js 页面逻辑(原生 JS)
|
||||||
|
style.css 页面样式
|
||||||
|
test/
|
||||||
|
proxy.test.js 集成测试
|
||||||
|
```
|
||||||
|
|
||||||
|
## 测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm test
|
||||||
|
```
|
||||||
|
|
||||||
|
覆盖:配置校验、IP/CIDR 匹配、HTTP 转发、CONNECT 隧道、代理认证(正确 / 错误 / 缺失)、SOCKS5 握手与认证、白名单拦截、统计快照、带宽采样。
|
||||||
|
|
||||||
|
## 安全提示
|
||||||
|
|
||||||
|
- 代理默认监听 `0.0.0.0`,**在公网机器上请务必配置用户名密码**,否则任何人都能借用你的网络出口
|
||||||
|
- 配置页面默认只监听 `127.0.0.1`;若改为对外监听,请同时设置管理页面的用户名密码
|
||||||
|
- 配置页面走 HTTP 明文,密码以明文存于 `config.json`,仅建议在可信网络内使用
|
||||||
|
- 需要限制访问范围时,把 `targetFilter.mode` 设为 `allowList`,只放行你信任的目标网段
|
||||||
|
|
||||||
|
## 环境要求
|
||||||
|
|
||||||
|
Node.js >= 18(开发验证于 Node 22)。
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"admin": {
|
||||||
|
"host": "127.0.0.1",
|
||||||
|
"port": 8790,
|
||||||
|
"username": "",
|
||||||
|
"password": ""
|
||||||
|
},
|
||||||
|
"http": {
|
||||||
|
"enabled": true,
|
||||||
|
"host": "0.0.0.0",
|
||||||
|
"port": 9202,
|
||||||
|
"username": "",
|
||||||
|
"password": ""
|
||||||
|
},
|
||||||
|
"socks5": {
|
||||||
|
"enabled": true,
|
||||||
|
"host": "0.0.0.0",
|
||||||
|
"port": 9200,
|
||||||
|
"username": "",
|
||||||
|
"password": ""
|
||||||
|
},
|
||||||
|
"targetFilter": {
|
||||||
|
"mode": "allowAll",
|
||||||
|
"allowList": []
|
||||||
|
},
|
||||||
|
"logLevel": "info"
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"name": "frost-network-proxy",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "带可视化配置网页的 HTTP / SOCKS5 网络代理服务(零第三方依赖)",
|
||||||
|
"main": "src/index.js",
|
||||||
|
"scripts": {
|
||||||
|
"start": "node src/index.js",
|
||||||
|
"dev": "node --watch src/index.js",
|
||||||
|
"test": "node --test"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"keywords": [
|
||||||
|
"proxy",
|
||||||
|
"http-proxy",
|
||||||
|
"socks5"
|
||||||
|
],
|
||||||
|
"license": "MIT"
|
||||||
|
}
|
||||||
+596
@@ -0,0 +1,596 @@
|
|||||||
|
/**
|
||||||
|
* 配置页面脚本:拉取状态 / 读写配置 / 展示日志。
|
||||||
|
* 无框架依赖,直接使用原生 DOM 与 fetch。
|
||||||
|
*/
|
||||||
|
|
||||||
|
(function () {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
/** 页面状态 */
|
||||||
|
const state = {
|
||||||
|
/** @type {object|null} 当前服务端配置 */
|
||||||
|
config: null,
|
||||||
|
/** @type {object|null} 最近一次状态快照 */
|
||||||
|
status: null,
|
||||||
|
/** 表单是否被用户改过(改过就不自动覆盖输入值) */
|
||||||
|
dirty: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 简写选择器。
|
||||||
|
* @param {string} selector CSS 选择器
|
||||||
|
* @returns {HTMLElement}
|
||||||
|
*/
|
||||||
|
function $(selector) {
|
||||||
|
const element = document.querySelector(selector);
|
||||||
|
if (!element) throw new Error(`缺少元素:${selector}`);
|
||||||
|
return /** @type {HTMLElement} */ (element);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 请求管理接口。
|
||||||
|
* @param {string} path 接口路径
|
||||||
|
* @param {RequestInit} [options] fetch 配置
|
||||||
|
* @returns {Promise<any>} 解析后的 JSON
|
||||||
|
*/
|
||||||
|
async function api(path, options = {}) {
|
||||||
|
const response = await fetch(path, {
|
||||||
|
cache: 'no-store',
|
||||||
|
...options,
|
||||||
|
headers: { 'content-type': 'application/json', ...(options.headers || {}) },
|
||||||
|
});
|
||||||
|
const data = await response.json().catch(() => ({}));
|
||||||
|
if (!response.ok) throw new Error(data.error || `请求失败(HTTP ${response.status})`);
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 速率格式化(字节/秒)。
|
||||||
|
* @param {number} bytesPerSecond 每秒字节数
|
||||||
|
* @returns {string} 例如 "1.24 MB/s"
|
||||||
|
*/
|
||||||
|
function formatRate(bytesPerSecond) {
|
||||||
|
const value = Math.max(0, Number(bytesPerSecond) || 0);
|
||||||
|
if (value < 1024) return `${Math.round(value)} B/s`;
|
||||||
|
const units = ['KB/s', 'MB/s', 'GB/s'];
|
||||||
|
let size = value / 1024;
|
||||||
|
let index = 0;
|
||||||
|
while (size >= 1024 && index < units.length - 1) {
|
||||||
|
size /= 1024;
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
return `${size.toFixed(size >= 100 ? 0 : size >= 10 ? 1 : 2)} ${units[index]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把最大值向上取整到 1/2/5×10^n,作为坐标轴上限。
|
||||||
|
* @param {number} value 原始最大值
|
||||||
|
* @returns {number} 规整后的上限
|
||||||
|
*/
|
||||||
|
function niceCeil(value) {
|
||||||
|
if (!Number.isFinite(value) || value <= 0) return 1;
|
||||||
|
const exponent = Math.floor(Math.log10(value));
|
||||||
|
const base = Math.pow(10, exponent);
|
||||||
|
const normalized = value / base;
|
||||||
|
const step = normalized <= 1 ? 1 : normalized <= 2 ? 2 : normalized <= 5 ? 5 : 10;
|
||||||
|
return step * base;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 绘制带宽趋势折线图(下载 / 上传双线)。
|
||||||
|
* @param {{at: number, up: number, down: number}[]} history 采样历史
|
||||||
|
*/
|
||||||
|
function drawChart(history) {
|
||||||
|
const canvas = /** @type {HTMLCanvasElement|null} */ (document.getElementById('bandwidth-chart'));
|
||||||
|
if (!canvas) return;
|
||||||
|
const context = canvas.getContext('2d');
|
||||||
|
if (!context) return;
|
||||||
|
|
||||||
|
const dpr = window.devicePixelRatio || 1;
|
||||||
|
const width = canvas.clientWidth || 640;
|
||||||
|
const height = canvas.clientHeight || 170;
|
||||||
|
const pixelWidth = Math.round(width * dpr);
|
||||||
|
const pixelHeight = Math.round(height * dpr);
|
||||||
|
if (canvas.width !== pixelWidth || canvas.height !== pixelHeight) {
|
||||||
|
canvas.width = pixelWidth;
|
||||||
|
canvas.height = pixelHeight;
|
||||||
|
}
|
||||||
|
context.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||||
|
context.clearRect(0, 0, width, height);
|
||||||
|
|
||||||
|
const padding = { top: 14, right: 14, bottom: 20, left: 58 };
|
||||||
|
const chartWidth = Math.max(1, width - padding.left - padding.right);
|
||||||
|
const chartHeight = Math.max(1, height - padding.top - padding.bottom);
|
||||||
|
const points = Array.isArray(history) ? history : [];
|
||||||
|
|
||||||
|
const maxValue = points.reduce((max, point) => Math.max(max, point.up || 0, point.down || 0), 0);
|
||||||
|
const scaleMax = niceCeil(Math.max(maxValue, 1024));
|
||||||
|
|
||||||
|
// 横向网格与纵轴刻度
|
||||||
|
context.font = '11px "Segoe UI", "PingFang SC", sans-serif';
|
||||||
|
context.strokeStyle = '#eef2f8';
|
||||||
|
context.fillStyle = '#98a2b3';
|
||||||
|
context.lineWidth = 1;
|
||||||
|
context.textAlign = 'right';
|
||||||
|
context.textBaseline = 'middle';
|
||||||
|
|
||||||
|
for (let i = 0; i <= 4; i += 1) {
|
||||||
|
const y = padding.top + (chartHeight / 4) * i;
|
||||||
|
context.beginPath();
|
||||||
|
context.moveTo(padding.left, y);
|
||||||
|
context.lineTo(padding.left + chartWidth, y);
|
||||||
|
context.stroke();
|
||||||
|
const label = formatRate((scaleMax * (4 - i)) / 4).replace('/s', '');
|
||||||
|
context.fillText(label, padding.left - 8, y);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (points.length < 2) {
|
||||||
|
context.fillStyle = '#98a2b3';
|
||||||
|
context.textAlign = 'center';
|
||||||
|
context.textBaseline = 'middle';
|
||||||
|
context.fillText('正在采集数据…', width / 2, height / 2);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 横轴时间说明
|
||||||
|
const startSeconds = Math.round((points[points.length - 1].at - points[0].at) / 1000);
|
||||||
|
context.fillStyle = '#98a2b3';
|
||||||
|
context.textBaseline = 'top';
|
||||||
|
context.textAlign = 'left';
|
||||||
|
context.fillText(`${startSeconds} 秒前`, padding.left, padding.top + chartHeight + 5);
|
||||||
|
context.textAlign = 'right';
|
||||||
|
context.fillText('现在', padding.left + chartWidth, padding.top + chartHeight + 5);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把采样点映射到画布坐标。
|
||||||
|
* @param {number} index 序号
|
||||||
|
* @param {number} value 速率
|
||||||
|
* @returns {{x: number, y: number}}
|
||||||
|
*/
|
||||||
|
const toPoint = (index, value) => ({
|
||||||
|
x: padding.left + (chartWidth * index) / (points.length - 1),
|
||||||
|
y: padding.top + chartHeight - (chartHeight * Math.min(value, scaleMax)) / scaleMax,
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 绘制一条速率曲线(可带渐变填充)。
|
||||||
|
* @param {'up'|'down'} key 数据键
|
||||||
|
* @param {string} stroke 线条颜色
|
||||||
|
* @param {string} fill 填充颜色
|
||||||
|
*/
|
||||||
|
const drawSeries = (key, stroke, fill) => {
|
||||||
|
context.beginPath();
|
||||||
|
points.forEach((point, index) => {
|
||||||
|
const position = toPoint(index, point[key] || 0);
|
||||||
|
if (index === 0) context.moveTo(position.x, position.y);
|
||||||
|
else context.lineTo(position.x, position.y);
|
||||||
|
});
|
||||||
|
context.strokeStyle = stroke;
|
||||||
|
context.lineWidth = 1.6;
|
||||||
|
context.lineJoin = 'round';
|
||||||
|
context.lineCap = 'round';
|
||||||
|
context.stroke();
|
||||||
|
|
||||||
|
// 填充到基线的浅色区域,便于区分上下行
|
||||||
|
context.lineTo(padding.left + chartWidth, padding.top + chartHeight);
|
||||||
|
context.lineTo(padding.left, padding.top + chartHeight);
|
||||||
|
context.closePath();
|
||||||
|
context.fillStyle = fill;
|
||||||
|
context.fill();
|
||||||
|
};
|
||||||
|
|
||||||
|
drawSeries('down', '#2563eb', 'rgba(37, 99, 235, 0.10)');
|
||||||
|
drawSeries('up', '#0f9d63', 'rgba(15, 157, 99, 0.10)');
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatBytes(bytes) {
|
||||||
|
const value = Number(bytes) || 0;
|
||||||
|
if (value < 1024) return `${value} B`;
|
||||||
|
const units = ['KB', 'MB', 'GB', 'TB'];
|
||||||
|
let size = value / 1024;
|
||||||
|
let index = 0;
|
||||||
|
while (size >= 1024 && index < units.length - 1) {
|
||||||
|
size /= 1024;
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
return `${size.toFixed(size >= 100 ? 0 : size >= 10 ? 1 : 2)} ${units[index]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 运行时长格式化。
|
||||||
|
* @param {number} seconds 秒
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
function formatUptime(seconds) {
|
||||||
|
const total = Math.max(0, Math.floor(Number(seconds) || 0));
|
||||||
|
const day = Math.floor(total / 86400);
|
||||||
|
const hour = Math.floor((total % 86400) / 3600);
|
||||||
|
const minute = Math.floor((total % 3600) / 60);
|
||||||
|
const second = total % 60;
|
||||||
|
if (day > 0) return `${day} 天 ${hour} 小时 ${minute} 分`;
|
||||||
|
if (hour > 0) return `${hour} 小时 ${minute} 分 ${second} 秒`;
|
||||||
|
if (minute > 0) return `${minute} 分 ${second} 秒`;
|
||||||
|
return `${second} 秒`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置状态标签的文字与样式。
|
||||||
|
* @param {HTMLElement} element 标签元素
|
||||||
|
* @param {string} text 文案
|
||||||
|
* @param {'ok'|'off'|'bad'|'neutral'} [variant] 样式
|
||||||
|
*/
|
||||||
|
function setState(element, text, variant = 'ok') {
|
||||||
|
element.textContent = text;
|
||||||
|
element.className = `state ${variant === 'ok' ? '' : variant}`.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 渲染实时状态。
|
||||||
|
* @param {object} status 状态快照
|
||||||
|
*/
|
||||||
|
function renderStatus(status) {
|
||||||
|
state.status = status;
|
||||||
|
$('#uptime-pill').textContent = `运行时长 ${formatUptime(status.uptime)}`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 渲染单个代理卡片。
|
||||||
|
* @param {'http'|'socks5'} key 协议
|
||||||
|
*/
|
||||||
|
const renderProxy = (key) => {
|
||||||
|
const item = status[key];
|
||||||
|
const prefix = key === 'http' ? 'http' : 'socks';
|
||||||
|
const scheme = key === 'http' ? 'http' : 'socks5';
|
||||||
|
|
||||||
|
// 状态标签
|
||||||
|
const stateEl = $(`#${prefix}-state`);
|
||||||
|
if (item.error) setState(stateEl, '异常', 'bad');
|
||||||
|
else if (item.listening) setState(stateEl, item.authEnabled ? '运行中 · 需认证' : '运行中', 'ok');
|
||||||
|
else setState(stateEl, item.enabled ? '未监听' : '已停用', 'off');
|
||||||
|
|
||||||
|
// 地址
|
||||||
|
const addrEl = $(`#${prefix}-addr`);
|
||||||
|
if (item.listening) {
|
||||||
|
addrEl.textContent = `${scheme}://${item.host}:${item.actualPort}`;
|
||||||
|
addrEl.classList.remove('dim');
|
||||||
|
} else {
|
||||||
|
addrEl.textContent = item.enabled ? '等待监听…' : '未启用';
|
||||||
|
addrEl.classList.add('dim');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 指标
|
||||||
|
const bucket = status.stats[key] || {};
|
||||||
|
const rate = (status.stats.rates && status.stats.rates[key]) || { up: 0, down: 0 };
|
||||||
|
$(`#${prefix}-active`).textContent = String(bucket.active || 0);
|
||||||
|
$(`#${prefix}-total`).textContent = String(bucket.total || 0);
|
||||||
|
$(`#${prefix}-rate-down`).textContent = formatRate(rate.down);
|
||||||
|
$(`#${prefix}-rate-up`).textContent = formatRate(rate.up);
|
||||||
|
$(`#${prefix}-up`).textContent = formatBytes(bucket.bytesUp);
|
||||||
|
$(`#${prefix}-down`).textContent = formatBytes(bucket.bytesDown);
|
||||||
|
|
||||||
|
// 错误信息
|
||||||
|
const errorEl = $(`#${prefix}-error`);
|
||||||
|
if (item.error) {
|
||||||
|
errorEl.hidden = false;
|
||||||
|
errorEl.textContent = item.error;
|
||||||
|
} else {
|
||||||
|
errorEl.hidden = true;
|
||||||
|
errorEl.textContent = '';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
renderProxy('http');
|
||||||
|
renderProxy('socks5');
|
||||||
|
|
||||||
|
// 总览
|
||||||
|
const total = status.stats.total || {};
|
||||||
|
const totalRate = (status.stats.rates && status.stats.rates.total) || { up: 0, down: 0 };
|
||||||
|
$('#total-active').textContent = String(total.active || 0);
|
||||||
|
$('#total-total').textContent = String(total.total || 0);
|
||||||
|
$('#total-rate-down').textContent = formatRate(totalRate.down);
|
||||||
|
$('#total-rate-up').textContent = formatRate(totalRate.up);
|
||||||
|
$('#total-up').textContent = formatBytes(total.bytesUp);
|
||||||
|
$('#total-down').textContent = formatBytes(total.bytesDown);
|
||||||
|
|
||||||
|
// 实时网络状态面板
|
||||||
|
const peak = status.stats.peak || { up: 0, down: 0 };
|
||||||
|
$('#chart-down').textContent = formatRate(totalRate.down);
|
||||||
|
$('#chart-up').textContent = formatRate(totalRate.up);
|
||||||
|
$('#peak-down').textContent = formatRate(peak.down);
|
||||||
|
$('#peak-up').textContent = formatRate(peak.up);
|
||||||
|
$('#chart-active').textContent = String(total.active || 0);
|
||||||
|
drawChart(status.stats.history || []);
|
||||||
|
|
||||||
|
const filter = status.targetFilter || {};
|
||||||
|
const filterState = $('#filter-state');
|
||||||
|
if (filter.mode === 'allowAll') {
|
||||||
|
setState(filterState, '允许全部', 'neutral');
|
||||||
|
$('#filter-desc').textContent = '未限制目标 IP,任何地址都可以通过代理访问';
|
||||||
|
} else {
|
||||||
|
setState(filterState, `白名单 ${filter.ruleCount || 0} 条`, 'neutral');
|
||||||
|
$('#filter-desc').textContent = filter.ruleCount
|
||||||
|
? `仅允许:${(filter.allowList || []).slice(0, 4).join('、')}${filter.ruleCount > 4 ? ' …' : ''}`
|
||||||
|
: '白名单为空,所有请求都会被拒绝';
|
||||||
|
}
|
||||||
|
$('#filter-desc').classList.add('dim');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把配置填充到表单。
|
||||||
|
* @param {object} config 配置
|
||||||
|
*/
|
||||||
|
function fillForm(config) {
|
||||||
|
state.config = config;
|
||||||
|
|
||||||
|
$('#http-enabled').checked = Boolean(config.http.enabled);
|
||||||
|
$('#http-host').value = config.http.host || '';
|
||||||
|
$('#http-port').value = String(config.http.port ?? '');
|
||||||
|
$('#http-user').value = config.http.username || '';
|
||||||
|
$('#http-pass').value = config.http.password || '';
|
||||||
|
|
||||||
|
$('#socks-enabled').checked = Boolean(config.socks5.enabled);
|
||||||
|
$('#socks-host').value = config.socks5.host || '';
|
||||||
|
$('#socks-port').value = String(config.socks5.port ?? '');
|
||||||
|
$('#socks-user').value = config.socks5.username || '';
|
||||||
|
$('#socks-pass').value = config.socks5.password || '';
|
||||||
|
|
||||||
|
$('#admin-host').value = config.admin.host || '';
|
||||||
|
$('#admin-port').value = String(config.admin.port ?? '');
|
||||||
|
$('#admin-user').value = config.admin.username || '';
|
||||||
|
$('#admin-pass').value = config.admin.password || '';
|
||||||
|
|
||||||
|
const mode = config.targetFilter?.mode === 'allowList' ? 'allowList' : 'allowAll';
|
||||||
|
document.querySelectorAll('input[name="filter-mode"]').forEach((input) => {
|
||||||
|
input.checked = input.value === mode;
|
||||||
|
});
|
||||||
|
$('#filter-list').value = (config.targetFilter?.allowList || []).join('\n');
|
||||||
|
|
||||||
|
updateExamples(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从表单收集配置对象。
|
||||||
|
* @returns {object} 配置
|
||||||
|
*/
|
||||||
|
function collectForm() {
|
||||||
|
const modeInput = document.querySelector('input[name="filter-mode"]:checked');
|
||||||
|
const allowList = $('#filter-list')
|
||||||
|
.value.split('\n')
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.filter((line) => line.length > 0);
|
||||||
|
|
||||||
|
return {
|
||||||
|
admin: {
|
||||||
|
host: $('#admin-host').value.trim() || '127.0.0.1',
|
||||||
|
port: Number($('#admin-port').value),
|
||||||
|
username: $('#admin-user').value.trim(),
|
||||||
|
password: $('#admin-pass').value,
|
||||||
|
},
|
||||||
|
http: {
|
||||||
|
enabled: $('#http-enabled').checked,
|
||||||
|
host: $('#http-host').value.trim() || '0.0.0.0',
|
||||||
|
port: Number($('#http-port').value),
|
||||||
|
username: $('#http-user').value.trim(),
|
||||||
|
password: $('#http-pass').value,
|
||||||
|
},
|
||||||
|
socks5: {
|
||||||
|
enabled: $('#socks-enabled').checked,
|
||||||
|
host: $('#socks-host').value.trim() || '0.0.0.0',
|
||||||
|
port: Number($('#socks-port').value),
|
||||||
|
username: $('#socks-user').value.trim(),
|
||||||
|
password: $('#socks-pass').value,
|
||||||
|
},
|
||||||
|
targetFilter: {
|
||||||
|
mode: modeInput ? modeInput.value : 'allowAll',
|
||||||
|
allowList,
|
||||||
|
},
|
||||||
|
logLevel: state.config?.logLevel || 'info',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新接入示例文本。
|
||||||
|
* @param {object} config 配置
|
||||||
|
*/
|
||||||
|
function updateExamples(config) {
|
||||||
|
/**
|
||||||
|
* 把监听地址转换为示例里可直接使用的地址。
|
||||||
|
* @param {string} host 监听地址
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
const usableHost = (host) => {
|
||||||
|
const value = String(host || '127.0.0.1');
|
||||||
|
if (value === '0.0.0.0' || value === '::' || value === '[::]') return '127.0.0.1';
|
||||||
|
return value.includes(':') ? `[${value.replace(/^\[|\]$/g, '')}]` : value;
|
||||||
|
};
|
||||||
|
|
||||||
|
const httpAuth = config.http.username
|
||||||
|
? `${encodeURIComponent(config.http.username)}:${encodeURIComponent(config.http.password || '')}@`
|
||||||
|
: '';
|
||||||
|
const socksAuth = config.socks5.username
|
||||||
|
? `${encodeURIComponent(config.socks5.username)}:${encodeURIComponent(config.socks5.password || '')}@`
|
||||||
|
: '';
|
||||||
|
|
||||||
|
const httpTarget = `http://${httpAuth}${usableHost(config.http.host)}:${config.http.port}`;
|
||||||
|
const socksTarget = `socks5h://${socksAuth}${usableHost(config.socks5.host)}:${config.socks5.port}`;
|
||||||
|
|
||||||
|
$('#example-http').textContent = [
|
||||||
|
'# HTTP 代理(curl)',
|
||||||
|
`curl -x ${httpTarget} http://example.com`,
|
||||||
|
'',
|
||||||
|
'# HTTPS 走 HTTP 代理的 CONNECT 隧道',
|
||||||
|
`curl -x ${httpTarget} https://example.com`,
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
$('#example-socks').textContent = [
|
||||||
|
'# SOCKS5 代理(域名由代理解析)',
|
||||||
|
`curl -x ${socksTarget} https://example.com`,
|
||||||
|
'',
|
||||||
|
'# 浏览器 / 系统代理设置',
|
||||||
|
`协议:SOCKS5 地址:${usableHost(config.socks5.host)} 端口:${config.socks5.port}`,
|
||||||
|
].join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 显示提示信息。
|
||||||
|
* @param {string} message 文案
|
||||||
|
* @param {'ok'|'err'|'info'} [tone] 语气
|
||||||
|
*/
|
||||||
|
function showMessage(message, tone = 'info') {
|
||||||
|
const element = $('#save-msg');
|
||||||
|
element.textContent = message;
|
||||||
|
element.className = `msg ${tone === 'info' ? '' : tone}`.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 拉取状态并渲染 */
|
||||||
|
async function refreshStatus() {
|
||||||
|
try {
|
||||||
|
const status = await api('/api/status');
|
||||||
|
renderStatus(status);
|
||||||
|
} catch (err) {
|
||||||
|
$('#uptime-pill').textContent = '连接中断';
|
||||||
|
setState($('#http-state'), '不可用', 'bad');
|
||||||
|
setState($('#socks-state'), '不可用', 'bad');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 拉取配置并填充表单 */
|
||||||
|
async function loadConfig() {
|
||||||
|
const config = await api('/api/config');
|
||||||
|
state.dirty = false;
|
||||||
|
fillForm(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 拉取日志并渲染 */
|
||||||
|
async function refreshLogs() {
|
||||||
|
try {
|
||||||
|
const data = await api('/api/logs?limit=150');
|
||||||
|
const container = $('#logs');
|
||||||
|
if (!data.logs || data.logs.length === 0) {
|
||||||
|
container.innerHTML = '<p class="muted">暂无日志</p>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const html = data.logs
|
||||||
|
.map((item) => {
|
||||||
|
const time = new Date(item.time).toLocaleTimeString('zh-CN', { hour12: false });
|
||||||
|
const safeMessage = escapeHtml(item.message);
|
||||||
|
return `<div class="log-line"><span class="log-time">${time}</span><span class="log-level ${item.level}">${item.level}</span><span>${safeMessage}</span></div>`;
|
||||||
|
})
|
||||||
|
.join('');
|
||||||
|
container.innerHTML = html;
|
||||||
|
container.scrollTop = container.scrollHeight;
|
||||||
|
} catch (err) {
|
||||||
|
$('#logs').innerHTML = `<p class="muted">日志加载失败:${escapeHtml(err.message)}</p>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTML 转义,避免日志内容破坏页面结构。
|
||||||
|
* @param {string} text 原文
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
function escapeHtml(text) {
|
||||||
|
return String(text)
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 保存配置 */
|
||||||
|
async function saveConfig(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
const button = $('#save-btn');
|
||||||
|
const config = collectForm();
|
||||||
|
|
||||||
|
// 前端先做一次基础校验,减少无谓请求
|
||||||
|
for (const [label, item] of [
|
||||||
|
['HTTP 代理', config.http],
|
||||||
|
['SOCKS5 代理', config.socks5],
|
||||||
|
['配置页面', config.admin],
|
||||||
|
]) {
|
||||||
|
if (!Number.isInteger(item.port) || item.port < 1 || item.port > 65535) {
|
||||||
|
showMessage(`${label}的端口必须是 1-65535 的整数`, 'err');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!item.username && item.password) {
|
||||||
|
showMessage(`${label}填写了密码但没有用户名`, 'err');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
button.disabled = true;
|
||||||
|
showMessage('正在保存…');
|
||||||
|
try {
|
||||||
|
const result = await api('/api/config', { method: 'POST', body: JSON.stringify(config) });
|
||||||
|
state.dirty = false;
|
||||||
|
fillForm(result.config);
|
||||||
|
renderStatus(result.status);
|
||||||
|
if (result.restartRequired && result.adminAddress) {
|
||||||
|
showMessage(`已保存。配置页面地址已变更为 ${result.adminAddress}`, 'ok');
|
||||||
|
} else {
|
||||||
|
showMessage('已保存并生效', 'ok');
|
||||||
|
}
|
||||||
|
await refreshLogs();
|
||||||
|
} catch (err) {
|
||||||
|
showMessage(err.message, 'err');
|
||||||
|
} finally {
|
||||||
|
button.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 绑定事件并初始化 */
|
||||||
|
function init() {
|
||||||
|
$('#config-form').addEventListener('submit', saveConfig);
|
||||||
|
|
||||||
|
// 表单被修改后不再被轮询结果覆盖
|
||||||
|
$('#config-form').addEventListener('input', () => {
|
||||||
|
state.dirty = true;
|
||||||
|
});
|
||||||
|
$('#config-form').addEventListener('change', () => {
|
||||||
|
state.dirty = true;
|
||||||
|
if (state.config) {
|
||||||
|
// 端口 / 主机变化时即时更新接入示例
|
||||||
|
updateExamples(collectForm());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
$('#reload-btn').addEventListener('click', async () => {
|
||||||
|
try {
|
||||||
|
await loadConfig();
|
||||||
|
showMessage('已重新读取配置文件', 'ok');
|
||||||
|
} catch (err) {
|
||||||
|
showMessage(err.message, 'err');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
$('#logs-refresh').addEventListener('click', () => {
|
||||||
|
void refreshLogs();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 窗口尺寸变化时按新的画布宽度重绘趋势图
|
||||||
|
window.addEventListener('resize', () => {
|
||||||
|
if (state.status && state.status.stats) drawChart(state.status.stats.history || []);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 初始化数据
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
await loadConfig();
|
||||||
|
await refreshStatus();
|
||||||
|
await refreshLogs();
|
||||||
|
} catch (err) {
|
||||||
|
showMessage(`初始化失败:${err.message}`, 'err');
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
// 定时刷新状态与日志
|
||||||
|
setInterval(() => {
|
||||||
|
void refreshStatus();
|
||||||
|
}, 2000);
|
||||||
|
setInterval(() => {
|
||||||
|
void refreshLogs();
|
||||||
|
}, 5000);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', init);
|
||||||
|
})();
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Frost Network Proxy · 配置</title>
|
||||||
|
<link rel="stylesheet" href="/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="topbar">
|
||||||
|
<div class="brand">
|
||||||
|
<span class="logo">FN</span>
|
||||||
|
<div class="brand-text">
|
||||||
|
<h1>Frost Network Proxy</h1>
|
||||||
|
<p class="sub">HTTP / SOCKS5 代理控制台</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="topbar-right">
|
||||||
|
<span class="pill" id="uptime-pill">运行时长 --</span>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<!-- 实时状态 -->
|
||||||
|
<section class="grid">
|
||||||
|
<article class="card" id="card-http">
|
||||||
|
<div class="card-head">
|
||||||
|
<h2>HTTP 代理</h2>
|
||||||
|
<span class="state" id="http-state">加载中</span>
|
||||||
|
</div>
|
||||||
|
<p class="addr" id="http-addr">--</p>
|
||||||
|
<div class="metrics">
|
||||||
|
<div><span class="label">活跃连接</span><strong id="http-active">0</strong></div>
|
||||||
|
<div><span class="label">累计连接</span><strong id="http-total">0</strong></div>
|
||||||
|
<div><span class="label">下载速率</span><strong id="http-rate-down" class="rate">0 B/s</strong></div>
|
||||||
|
<div><span class="label">上传速率</span><strong id="http-rate-up" class="rate">0 B/s</strong></div>
|
||||||
|
<div><span class="label">累计下载</span><strong id="http-down">0 B</strong></div>
|
||||||
|
<div><span class="label">累计上传</span><strong id="http-up">0 B</strong></div>
|
||||||
|
</div>
|
||||||
|
<p class="error" id="http-error" hidden></p>
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<article class="card" id="card-socks5">
|
||||||
|
<div class="card-head">
|
||||||
|
<h2>SOCKS5 代理</h2>
|
||||||
|
<span class="state" id="socks-state">加载中</span>
|
||||||
|
</div>
|
||||||
|
<p class="addr" id="socks-addr">--</p>
|
||||||
|
<div class="metrics">
|
||||||
|
<div><span class="label">活跃连接</span><strong id="socks-active">0</strong></div>
|
||||||
|
<div><span class="label">累计连接</span><strong id="socks-total">0</strong></div>
|
||||||
|
<div><span class="label">下载速率</span><strong id="socks-rate-down" class="rate">0 B/s</strong></div>
|
||||||
|
<div><span class="label">上传速率</span><strong id="socks-rate-up" class="rate">0 B/s</strong></div>
|
||||||
|
<div><span class="label">累计下载</span><strong id="socks-down">0 B</strong></div>
|
||||||
|
<div><span class="label">累计上传</span><strong id="socks-up">0 B</strong></div>
|
||||||
|
</div>
|
||||||
|
<p class="error" id="socks-error" hidden></p>
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<article class="card" id="card-total">
|
||||||
|
<div class="card-head">
|
||||||
|
<h2>总览</h2>
|
||||||
|
<span class="state neutral" id="filter-state">--</span>
|
||||||
|
</div>
|
||||||
|
<p class="addr" id="filter-desc">--</p>
|
||||||
|
<div class="metrics">
|
||||||
|
<div><span class="label">活跃连接</span><strong id="total-active">0</strong></div>
|
||||||
|
<div><span class="label">累计连接</span><strong id="total-total">0</strong></div>
|
||||||
|
<div><span class="label">下载速率</span><strong id="total-rate-down" class="rate">0 B/s</strong></div>
|
||||||
|
<div><span class="label">上传速率</span><strong id="total-rate-up" class="rate">0 B/s</strong></div>
|
||||||
|
<div><span class="label">累计下载</span><strong id="total-down">0 B</strong></div>
|
||||||
|
<div><span class="label">累计上传</span><strong id="total-up">0 B</strong></div>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 实时带宽趋势 -->
|
||||||
|
<section class="panel">
|
||||||
|
<header class="panel-head">
|
||||||
|
<h2>实时网络状态</h2>
|
||||||
|
<div class="legend">
|
||||||
|
<span class="legend-item"><i class="dot down"></i>下载 <b id="chart-down">0 B/s</b></span>
|
||||||
|
<span class="legend-item"><i class="dot up"></i>上传 <b id="chart-up">0 B/s</b></span>
|
||||||
|
<span class="legend-item">峰值下载 <b id="peak-down">0 B/s</b></span>
|
||||||
|
<span class="legend-item">峰值上传 <b id="peak-up">0 B/s</b></span>
|
||||||
|
<span class="legend-item">连接数 <b id="chart-active">0</b></span>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<canvas id="bandwidth-chart" class="chart" height="170"></canvas>
|
||||||
|
<p class="muted chart-tip">最近 60 秒的上传 / 下载速率趋势,每 1 秒采样一次,纵轴为合计速率</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 配置表单 -->
|
||||||
|
<form id="config-form" autocomplete="off">
|
||||||
|
<section class="panel">
|
||||||
|
<header class="panel-head">
|
||||||
|
<h2>HTTP 代理</h2>
|
||||||
|
<label class="switch" title="启用 / 停用">
|
||||||
|
<input type="checkbox" id="http-enabled">
|
||||||
|
<span class="slider"></span>
|
||||||
|
</label>
|
||||||
|
</header>
|
||||||
|
<div class="fields">
|
||||||
|
<label class="field">
|
||||||
|
<span>监听地址</span>
|
||||||
|
<input type="text" id="http-host" placeholder="0.0.0.0">
|
||||||
|
<em>0.0.0.0 表示所有网卡,127.0.0.1 仅本机可用</em>
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>端口</span>
|
||||||
|
<input type="number" id="http-port" min="1" max="65535" placeholder="8080">
|
||||||
|
<em>客户端通过该端口访问 HTTP 代理</em>
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>用户名</span>
|
||||||
|
<input type="text" id="http-user" placeholder="留空表示不校验">
|
||||||
|
<em>填写后客户端必须带代理认证</em>
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>密码</span>
|
||||||
|
<input type="text" id="http-pass" placeholder="留空表示不校验">
|
||||||
|
<em>与用户名同时留空则无需认证</em>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<header class="panel-head">
|
||||||
|
<h2>SOCKS5 代理</h2>
|
||||||
|
<label class="switch" title="启用 / 停用">
|
||||||
|
<input type="checkbox" id="socks-enabled">
|
||||||
|
<span class="slider"></span>
|
||||||
|
</label>
|
||||||
|
</header>
|
||||||
|
<div class="fields">
|
||||||
|
<label class="field">
|
||||||
|
<span>监听地址</span>
|
||||||
|
<input type="text" id="socks-host" placeholder="0.0.0.0">
|
||||||
|
<em>0.0.0.0 表示所有网卡,127.0.0.1 仅本机可用</em>
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>端口</span>
|
||||||
|
<input type="number" id="socks-port" min="1" max="65535" placeholder="1080">
|
||||||
|
<em>客户端通过该端口访问 SOCKS5 代理</em>
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>用户名</span>
|
||||||
|
<input type="text" id="socks-user" placeholder="留空表示不校验">
|
||||||
|
<em>填写后启用 RFC 1929 用户名密码认证</em>
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>密码</span>
|
||||||
|
<input type="text" id="socks-pass" placeholder="留空表示不校验">
|
||||||
|
<em>与用户名同时留空则无需认证</em>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<header class="panel-head">
|
||||||
|
<h2>目标 IP 限制</h2>
|
||||||
|
<span class="hint-inline">决定允许代理到哪些目标地址</span>
|
||||||
|
</header>
|
||||||
|
<div class="radio-row">
|
||||||
|
<label class="radio">
|
||||||
|
<input type="radio" name="filter-mode" value="allowAll">
|
||||||
|
<span>允许全部目标</span>
|
||||||
|
</label>
|
||||||
|
<label class="radio">
|
||||||
|
<input type="radio" name="filter-mode" value="allowList">
|
||||||
|
<span>仅允许列表内的 IP</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<label class="field wide">
|
||||||
|
<span>IP / 网段列表(每行一条)</span>
|
||||||
|
<textarea id="filter-list" rows="6" placeholder="192.168.1.10 10.0.0.0/8 2001:db8::/32"></textarea>
|
||||||
|
<em>支持单 IP 与 CIDR 网段;域名会先解析成 IP 再判断;白名单模式下留空表示全部拒绝</em>
|
||||||
|
</label>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<header class="panel-head">
|
||||||
|
<h2>配置页面</h2>
|
||||||
|
<span class="hint-inline">修改监听地址或端口后需保存,页面会自动切换</span>
|
||||||
|
</header>
|
||||||
|
<div class="fields">
|
||||||
|
<label class="field">
|
||||||
|
<span>监听地址</span>
|
||||||
|
<input type="text" id="admin-host" placeholder="127.0.0.1">
|
||||||
|
<em>建议保持 127.0.0.1,仅本机可打开配置页面</em>
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>端口</span>
|
||||||
|
<input type="number" id="admin-port" min="1" max="65535" placeholder="8790">
|
||||||
|
<em>浏览器访问 http://该地址:端口</em>
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>用户名</span>
|
||||||
|
<input type="text" id="admin-user" placeholder="留空表示不校验">
|
||||||
|
<em>填写后打开配置页面需要登录</em>
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>密码</span>
|
||||||
|
<input type="text" id="admin-pass" placeholder="留空表示不校验">
|
||||||
|
<em>与用户名同时留空则无需登录</em>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="actions">
|
||||||
|
<button class="primary" type="submit" id="save-btn">保存并应用</button>
|
||||||
|
<button class="ghost" type="button" id="reload-btn">重新读取配置</button>
|
||||||
|
<span class="msg" id="save-msg"></span>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<!-- 接入示例 -->
|
||||||
|
<section class="panel">
|
||||||
|
<header class="panel-head">
|
||||||
|
<h2>接入示例</h2>
|
||||||
|
<span class="hint-inline">复制后按需修改主机与端口</span>
|
||||||
|
</header>
|
||||||
|
<pre class="code" id="example-http">--</pre>
|
||||||
|
<pre class="code" id="example-socks">--</pre>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 日志 -->
|
||||||
|
<section class="panel">
|
||||||
|
<header class="panel-head">
|
||||||
|
<h2>运行日志</h2>
|
||||||
|
<button class="ghost small" type="button" id="logs-refresh">刷新</button>
|
||||||
|
</header>
|
||||||
|
<div class="logs" id="logs"><p class="muted">加载中…</p></div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script src="/app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,623 @@
|
|||||||
|
/* ===== 全局变量与基础样式(浅色主题) ===== */
|
||||||
|
:root {
|
||||||
|
--bg: #f4f6fb;
|
||||||
|
--bg-soft: #eef2f9;
|
||||||
|
--panel: #ffffff;
|
||||||
|
--panel-2: #fbfcfe;
|
||||||
|
--border: #e2e8f2;
|
||||||
|
--text: #1b2430;
|
||||||
|
--muted: #6d7789;
|
||||||
|
--accent: #2563eb;
|
||||||
|
--accent-soft: rgba(37, 99, 235, 0.12);
|
||||||
|
--ok: #0f9d63;
|
||||||
|
--warn: #b25c00;
|
||||||
|
--err: #d92d20;
|
||||||
|
--radius: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
* {
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
html,
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
background:
|
||||||
|
radial-gradient(900px 500px at 12% -10%, rgba(37, 99, 235, 0.1), transparent 60%),
|
||||||
|
radial-gradient(700px 420px at 92% 0%, rgba(16, 185, 129, 0.1), transparent 55%),
|
||||||
|
var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
font-family: "Segoe UI", "PingFang SC", "Microsoft YaHei", system-ui, -apple-system, sans-serif;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.6;
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ===== 顶部栏 ===== */
|
||||||
|
.topbar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 16px;
|
||||||
|
padding: 22px clamp(16px, 5vw, 48px) 10px;
|
||||||
|
max-width: 1180px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo {
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 42px;
|
||||||
|
height: 42px;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: linear-gradient(140deg, #3b82f6, #0ea5a4);
|
||||||
|
color: #ffffff;
|
||||||
|
font-weight: 800;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
box-shadow: 0 6px 16px rgba(37, 99, 235, 0.22);
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-text h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 17px;
|
||||||
|
font-weight: 650;
|
||||||
|
letter-spacing: 0.2px;
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-text .sub {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pill {
|
||||||
|
padding: 6px 12px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--muted);
|
||||||
|
background: #ffffff;
|
||||||
|
white-space: nowrap;
|
||||||
|
box-shadow: 0 1px 2px rgba(16, 24, 40, 0.04);
|
||||||
|
}
|
||||||
|
|
||||||
|
main {
|
||||||
|
max-width: 1180px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 8px clamp(16px, 5vw, 48px) 64px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ===== 状态卡片 ===== */
|
||||||
|
.grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
padding: 16px 18px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
box-shadow: 0 1px 2px rgba(16, 24, 40, 0.04), 0 10px 24px rgba(16, 24, 40, 0.04);
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.state {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
font-size: 12px;
|
||||||
|
padding: 3px 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: rgba(15, 157, 99, 0.1);
|
||||||
|
color: #0b7d4f;
|
||||||
|
border: 1px solid rgba(15, 157, 99, 0.25);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.state::before {
|
||||||
|
content: "";
|
||||||
|
width: 6px;
|
||||||
|
height: 6px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: currentColor;
|
||||||
|
}
|
||||||
|
|
||||||
|
.state.off {
|
||||||
|
background: #f1f4f9;
|
||||||
|
color: var(--muted);
|
||||||
|
border-color: var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.state.bad {
|
||||||
|
background: rgba(217, 45, 32, 0.08);
|
||||||
|
color: #b42318;
|
||||||
|
border-color: rgba(217, 45, 32, 0.22);
|
||||||
|
}
|
||||||
|
|
||||||
|
.state.neutral {
|
||||||
|
background: rgba(37, 99, 235, 0.08);
|
||||||
|
color: #1d4ed8;
|
||||||
|
border-color: rgba(37, 99, 235, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.addr {
|
||||||
|
margin: 0;
|
||||||
|
font-family: "JetBrains Mono", "Cascadia Mono", Consolas, monospace;
|
||||||
|
font-size: 13px;
|
||||||
|
color: #1d4ed8;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
.addr.dim {
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.metrics {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 8px 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metrics > div {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2px;
|
||||||
|
padding: 8px 10px;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: #f7f9fd;
|
||||||
|
border: 1px solid #eef2f8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metrics .label {
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.metrics strong {
|
||||||
|
font-size: 15px;
|
||||||
|
font-weight: 600;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
color: #111a27;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 速率数值用主色突出显示 */
|
||||||
|
.metrics strong.rate {
|
||||||
|
color: #1d4ed8;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ===== 实时带宽趋势 ===== */
|
||||||
|
.legend {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 16px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.legend-item {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.legend-item b {
|
||||||
|
color: #111a27;
|
||||||
|
font-weight: 600;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dot {
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 50%;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dot.down {
|
||||||
|
background: #2563eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dot.up {
|
||||||
|
background: #0f9d63;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chart {
|
||||||
|
width: 100%;
|
||||||
|
height: 170px;
|
||||||
|
display: block;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: #fbfcfe;
|
||||||
|
border: 1px solid #eef2f8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chart-tip {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
margin: 0;
|
||||||
|
padding: 8px 10px;
|
||||||
|
border-radius: 10px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #b42318;
|
||||||
|
background: #fef3f2;
|
||||||
|
border: 1px solid #fecdca;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ===== 表单面板 ===== */
|
||||||
|
form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel {
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
padding: 18px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 14px;
|
||||||
|
box-shadow: 0 1px 2px rgba(16, 24, 40, 0.03), 0 10px 24px rgba(16, 24, 40, 0.03);
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-head h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.2px;
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.hint-inline {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.fields {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||||
|
gap: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field.wide {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field > span {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #44506a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field > em {
|
||||||
|
font-style: normal;
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--muted);
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="text"],
|
||||||
|
input[type="number"],
|
||||||
|
textarea {
|
||||||
|
width: 100%;
|
||||||
|
padding: 9px 12px;
|
||||||
|
border-radius: 10px;
|
||||||
|
border: 1px solid #dfe6f0;
|
||||||
|
background: #ffffff;
|
||||||
|
color: var(--text);
|
||||||
|
font-size: 13px;
|
||||||
|
font-family: inherit;
|
||||||
|
outline: none;
|
||||||
|
transition: border-color 0.15s ease, box-shadow 0.15s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
input:hover,
|
||||||
|
textarea:hover {
|
||||||
|
border-color: #cbd6e6;
|
||||||
|
}
|
||||||
|
|
||||||
|
input:focus,
|
||||||
|
textarea:focus {
|
||||||
|
border-color: rgba(37, 99, 235, 0.65);
|
||||||
|
box-shadow: 0 0 0 3px var(--accent-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea {
|
||||||
|
resize: vertical;
|
||||||
|
font-family: "JetBrains Mono", "Cascadia Mono", Consolas, monospace;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
input::placeholder,
|
||||||
|
textarea::placeholder {
|
||||||
|
color: #9aa4b5;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 开关 */
|
||||||
|
.switch {
|
||||||
|
position: relative;
|
||||||
|
display: inline-block;
|
||||||
|
width: 44px;
|
||||||
|
height: 24px;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.switch input {
|
||||||
|
opacity: 0;
|
||||||
|
width: 0;
|
||||||
|
height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.slider {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: #e3e9f3;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.18s ease, border-color 0.18s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.slider::before {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
left: 2px;
|
||||||
|
top: 2px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: #ffffff;
|
||||||
|
box-shadow: 0 1px 3px rgba(16, 24, 40, 0.22);
|
||||||
|
transition: transform 0.18s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.switch input:checked + .slider {
|
||||||
|
background: rgba(37, 99, 235, 0.28);
|
||||||
|
border-color: rgba(37, 99, 235, 0.45);
|
||||||
|
}
|
||||||
|
|
||||||
|
.switch input:checked + .slider::before {
|
||||||
|
transform: translateX(20px);
|
||||||
|
background: #ffffff;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 单选 */
|
||||||
|
.radio-row {
|
||||||
|
display: flex;
|
||||||
|
gap: 18px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.radio {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 13px;
|
||||||
|
cursor: pointer;
|
||||||
|
color: #33415c;
|
||||||
|
}
|
||||||
|
|
||||||
|
.radio input {
|
||||||
|
accent-color: var(--accent);
|
||||||
|
width: 15px;
|
||||||
|
height: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 按钮 */
|
||||||
|
.actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
font-family: inherit;
|
||||||
|
font-size: 13px;
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 9px 18px;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: transform 0.12s ease, background 0.15s ease, border-color 0.15s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:active {
|
||||||
|
transform: translateY(1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.primary {
|
||||||
|
background: linear-gradient(180deg, #3b82f6, #2563eb);
|
||||||
|
color: #ffffff;
|
||||||
|
font-weight: 600;
|
||||||
|
box-shadow: 0 8px 18px rgba(37, 99, 235, 0.22);
|
||||||
|
}
|
||||||
|
|
||||||
|
.primary:hover {
|
||||||
|
background: linear-gradient(180deg, #4f8dfa, #2f6ff0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.primary:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ghost {
|
||||||
|
background: #ffffff;
|
||||||
|
border-color: var(--border);
|
||||||
|
color: #33415c;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ghost:hover {
|
||||||
|
border-color: rgba(37, 99, 235, 0.45);
|
||||||
|
color: var(--accent);
|
||||||
|
background: #f7f9fd;
|
||||||
|
}
|
||||||
|
|
||||||
|
button.small {
|
||||||
|
padding: 5px 12px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--muted);
|
||||||
|
min-height: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg.ok {
|
||||||
|
color: #0b7d4f;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg.err {
|
||||||
|
color: var(--err);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ===== 示例代码 ===== */
|
||||||
|
.code {
|
||||||
|
margin: 0;
|
||||||
|
padding: 12px 14px;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: #f7f9fd;
|
||||||
|
border: 1px solid #e6ecf5;
|
||||||
|
color: #0b6b63;
|
||||||
|
font-family: "JetBrains Mono", "Cascadia Mono", Consolas, monospace;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.7;
|
||||||
|
overflow-x: auto;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ===== 日志 ===== */
|
||||||
|
.logs {
|
||||||
|
max-height: 280px;
|
||||||
|
overflow-y: auto;
|
||||||
|
border-radius: 10px;
|
||||||
|
border: 1px solid #e6ecf5;
|
||||||
|
background: #fafbfd;
|
||||||
|
padding: 10px 12px;
|
||||||
|
font-family: "JetBrains Mono", "Cascadia Mono", Consolas, monospace;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-line {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-time {
|
||||||
|
color: #98a2b3;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-level {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
width: 46px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-level.info {
|
||||||
|
color: #1d4ed8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-level.warn {
|
||||||
|
color: var(--warn);
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-level.error {
|
||||||
|
color: var(--err);
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-level.debug {
|
||||||
|
color: #7c8699;
|
||||||
|
}
|
||||||
|
|
||||||
|
.muted {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ===== 滚动条 ===== */
|
||||||
|
::-webkit-scrollbar {
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-track {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-thumb {
|
||||||
|
background: #d3dcea;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 2px solid transparent;
|
||||||
|
background-clip: content-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: #b7c4d8;
|
||||||
|
background-clip: content-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.topbar {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metrics {
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
/**
|
||||||
|
* 一次性自检脚本:核对页面元素 id 与脚本引用是否一致。
|
||||||
|
*/
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
|
||||||
|
const root = path.join(__dirname, '..');
|
||||||
|
const html = fs.readFileSync(path.join(root, 'public', 'index.html'), 'utf8');
|
||||||
|
const js = fs.readFileSync(path.join(root, 'public', 'app.js'), 'utf8');
|
||||||
|
const css = fs.readFileSync(path.join(root, 'public', 'style.css'), 'utf8');
|
||||||
|
|
||||||
|
const ids = new Set([...html.matchAll(/id="([^"]+)"/g)].map((m) => m[1]));
|
||||||
|
const used = new Set([...js.matchAll(/\$\('#([a-zA-Z0-9_-]+)'\)/g)].map((m) => m[1]));
|
||||||
|
const missing = [...used].filter((id) => !ids.has(id));
|
||||||
|
|
||||||
|
console.log('页面 id 数量:', ids.size);
|
||||||
|
console.log('脚本引用 id 数量:', used.size);
|
||||||
|
console.log('缺失的 id:', missing.length ? missing.join(', ') : '无');
|
||||||
|
|
||||||
|
const classes = ['card', 'metrics', 'panel', 'switch', 'state', 'log-line'];
|
||||||
|
console.log('CSS 关键类存在:', classes.every((name) => css.includes(`.${name}`)));
|
||||||
|
|
||||||
|
// 检查 CSS 花括号配对
|
||||||
|
const open = (css.match(/{/g) || []).length;
|
||||||
|
const close = (css.match(/}/g) || []).length;
|
||||||
|
console.log('CSS 花括号配对:', open === close, `(${open}/${close})`);
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 配置网页 + 管理 API。
|
||||||
|
* 页面本身是纯静态文件,数据通过 /api/* 读写。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const http = require('node:http');
|
||||||
|
const fsp = require('node:fs/promises');
|
||||||
|
const path = require('node:path');
|
||||||
|
const { normalizeConfig, saveConfig } = require('./config');
|
||||||
|
const { checkBasicHeader } = require('./auth');
|
||||||
|
const { listen } = require('./util');
|
||||||
|
|
||||||
|
const PUBLIC_DIR = path.join(__dirname, '..', 'public');
|
||||||
|
const MAX_BODY_BYTES = 1024 * 1024;
|
||||||
|
|
||||||
|
const MIME_TYPES = {
|
||||||
|
'.html': 'text/html; charset=utf-8',
|
||||||
|
'.css': 'text/css; charset=utf-8',
|
||||||
|
'.js': 'application/javascript; charset=utf-8',
|
||||||
|
'.json': 'application/json; charset=utf-8',
|
||||||
|
'.svg': 'image/svg+xml',
|
||||||
|
'.png': 'image/png',
|
||||||
|
'.ico': 'image/x-icon',
|
||||||
|
'.woff2': 'font/woff2',
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 输出 JSON 响应。
|
||||||
|
* @param {import('node:http').ServerResponse} res 响应
|
||||||
|
* @param {number} status 状态码
|
||||||
|
* @param {any} data 数据
|
||||||
|
*/
|
||||||
|
function sendJson(res, status, data) {
|
||||||
|
const body = JSON.stringify(data);
|
||||||
|
res.writeHead(status, {
|
||||||
|
'content-type': 'application/json; charset=utf-8',
|
||||||
|
'content-length': Buffer.byteLength(body),
|
||||||
|
'cache-control': 'no-store',
|
||||||
|
});
|
||||||
|
res.end(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读取请求体(限制大小)。
|
||||||
|
* @param {import('node:http').IncomingMessage} req 请求
|
||||||
|
* @returns {Promise<Buffer>}
|
||||||
|
*/
|
||||||
|
function readBody(req) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const chunks = [];
|
||||||
|
let size = 0;
|
||||||
|
req.on('data', (chunk) => {
|
||||||
|
size += chunk.length;
|
||||||
|
if (size > MAX_BODY_BYTES) {
|
||||||
|
reject(new Error('请求体过大'));
|
||||||
|
req.destroy();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
chunks.push(chunk);
|
||||||
|
});
|
||||||
|
req.on('end', () => resolve(Buffer.concat(chunks)));
|
||||||
|
req.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
class AdminServer {
|
||||||
|
/**
|
||||||
|
* @param {{manager: import('./proxyManager').ProxyManager, logger: import('./logger').Logger, configPath: string}} options 依赖
|
||||||
|
*/
|
||||||
|
constructor({ manager, logger, configPath }) {
|
||||||
|
this.manager = manager;
|
||||||
|
this.logger = logger;
|
||||||
|
this.configPath = configPath;
|
||||||
|
this.server = null;
|
||||||
|
this.config = null;
|
||||||
|
this.address = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动(或重启)管理服务器。
|
||||||
|
* @param {{host: string, port: number, username: string, password: string}} adminConfig 管理页面配置
|
||||||
|
* @returns {Promise<{host: string, port: number}>} 实际监听地址
|
||||||
|
*/
|
||||||
|
async start(adminConfig) {
|
||||||
|
await this.stop();
|
||||||
|
this.config = adminConfig;
|
||||||
|
|
||||||
|
const server = http.createServer((req, res) => {
|
||||||
|
void this.handle(req, res).catch((err) => {
|
||||||
|
this.logger.error(`[ADMIN] 处理请求异常:${err.message}`);
|
||||||
|
if (!res.headersSent) sendJson(res, 500, { error: '内部错误' });
|
||||||
|
else res.destroy();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await listen(server, adminConfig.port, adminConfig.host);
|
||||||
|
this.server = server;
|
||||||
|
const actual = server.address();
|
||||||
|
this.address = { host: adminConfig.host, port: actual.port };
|
||||||
|
this.logger.info(`[ADMIN] 配置页面已启动 http://${adminConfig.host}:${actual.port}`);
|
||||||
|
return this.address;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 停止管理服务器 */
|
||||||
|
async stop() {
|
||||||
|
const server = this.server;
|
||||||
|
if (!server) return;
|
||||||
|
this.server = null;
|
||||||
|
await new Promise((resolve) => {
|
||||||
|
server.close(() => resolve());
|
||||||
|
if (typeof server.closeAllConnections === 'function') server.closeAllConnections();
|
||||||
|
// 保险起见,最多等 1 秒
|
||||||
|
setTimeout(resolve, 1000).unref?.();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统一请求入口。
|
||||||
|
* @param {import('node:http').IncomingMessage} req 请求
|
||||||
|
* @param {import('node:http').ServerResponse} res 响应
|
||||||
|
*/
|
||||||
|
async handle(req, res) {
|
||||||
|
// 管理页面鉴权(可选)
|
||||||
|
if (this.config.username && !checkBasicHeader(this.config, req.headers.authorization)) {
|
||||||
|
const body = '需要登录配置页面。';
|
||||||
|
res.writeHead(401, {
|
||||||
|
'www-authenticate': 'Basic realm="Frost Proxy Admin", charset="UTF-8"',
|
||||||
|
'content-type': 'text/plain; charset=utf-8',
|
||||||
|
'content-length': Buffer.byteLength(body),
|
||||||
|
});
|
||||||
|
res.end(body);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
|
||||||
|
const pathname = url.pathname;
|
||||||
|
|
||||||
|
if (pathname === '/api/status' && req.method === 'GET') {
|
||||||
|
return sendJson(res, 200, this.manager.getStatus());
|
||||||
|
}
|
||||||
|
if (pathname === '/api/config' && req.method === 'GET') {
|
||||||
|
return sendJson(res, 200, this.manager.config);
|
||||||
|
}
|
||||||
|
if (pathname === '/api/logs' && req.method === 'GET') {
|
||||||
|
const limit = Math.min(Number(url.searchParams.get('limit')) || 120, 400);
|
||||||
|
return sendJson(res, 200, { logs: this.logger.recent(limit) });
|
||||||
|
}
|
||||||
|
if (pathname === '/api/config' && req.method === 'POST') {
|
||||||
|
return this.handleSaveConfig(req, res);
|
||||||
|
}
|
||||||
|
if (pathname.startsWith('/api/')) {
|
||||||
|
return sendJson(res, 404, { error: '接口不存在' });
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.serveStatic(pathname, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保存配置并应用。
|
||||||
|
* @param {import('node:http').IncomingMessage} req 请求
|
||||||
|
* @param {import('node:http').ServerResponse} res 响应
|
||||||
|
*/
|
||||||
|
async handleSaveConfig(req, res) {
|
||||||
|
let body;
|
||||||
|
try {
|
||||||
|
body = await readBody(req);
|
||||||
|
} catch (err) {
|
||||||
|
return sendJson(res, 400, { error: err.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
let raw;
|
||||||
|
try {
|
||||||
|
raw = body.length ? JSON.parse(body.toString('utf8')) : {};
|
||||||
|
} catch (err) {
|
||||||
|
return sendJson(res, 400, { error: `配置 JSON 解析失败:${err.message}` });
|
||||||
|
}
|
||||||
|
|
||||||
|
let config;
|
||||||
|
try {
|
||||||
|
config = normalizeConfig(raw);
|
||||||
|
} catch (err) {
|
||||||
|
return sendJson(res, 400, { error: err.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
const previousAdmin = this.manager.config.admin;
|
||||||
|
const adminChanged = previousAdmin.host !== config.admin.host || previousAdmin.port !== config.admin.port;
|
||||||
|
|
||||||
|
try {
|
||||||
|
saveConfig(this.configPath, config);
|
||||||
|
} catch (err) {
|
||||||
|
return sendJson(res, 500, { error: `写入配置文件失败:${err.message}` });
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.setLevel(config.logLevel);
|
||||||
|
const status = await this.manager.apply(config);
|
||||||
|
this.logger.info('[ADMIN] 配置已保存并应用');
|
||||||
|
|
||||||
|
sendJson(res, 200, {
|
||||||
|
ok: true,
|
||||||
|
config,
|
||||||
|
status,
|
||||||
|
restartRequired: adminChanged,
|
||||||
|
adminAddress: adminChanged ? `http://${config.admin.host}:${config.admin.port}` : null,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 管理端口变化时,先回复当前请求,再重启管理服务器
|
||||||
|
if (adminChanged) {
|
||||||
|
setImmediate(() => {
|
||||||
|
this.start(config.admin).catch((err) => {
|
||||||
|
this.logger.error(`[ADMIN] 重启失败:${err.message},请修改 config.json 后手动重启程序`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 静态文件服务。
|
||||||
|
* @param {string} pathname 请求路径
|
||||||
|
* @param {import('node:http').ServerResponse} res 响应
|
||||||
|
*/
|
||||||
|
async serveStatic(pathname, res) {
|
||||||
|
const relative = pathname === '/' ? 'index.html' : decodeURIComponent(pathname).replace(/^\/+/, '');
|
||||||
|
const filePath = path.resolve(PUBLIC_DIR, relative);
|
||||||
|
|
||||||
|
// 防止路径穿越
|
||||||
|
if (!filePath.startsWith(PUBLIC_DIR)) {
|
||||||
|
return sendJson(res, 403, { error: '禁止访问' });
|
||||||
|
}
|
||||||
|
|
||||||
|
let content;
|
||||||
|
try {
|
||||||
|
content = await fsp.readFile(filePath);
|
||||||
|
} catch {
|
||||||
|
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
|
||||||
|
res.end('404 Not Found');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ext = path.extname(filePath).toLowerCase();
|
||||||
|
res.writeHead(200, {
|
||||||
|
'content-type': MIME_TYPES[ext] || 'application/octet-stream',
|
||||||
|
'content-length': content.length,
|
||||||
|
'cache-control': ext === '.html' ? 'no-store' : 'max-age=60',
|
||||||
|
});
|
||||||
|
res.end(content);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { AdminServer, PUBLIC_DIR };
|
||||||
+88
@@ -0,0 +1,88 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 代理身份认证工具(HTTP Basic / SOCKS5 用户名密码共用一套校验逻辑)。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const crypto = require('node:crypto');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 定长比较字符串,避免通过响应时间猜测密码。
|
||||||
|
* @param {string} a 值一
|
||||||
|
* @param {string} b 值二
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
function safeEqual(a, b) {
|
||||||
|
const bufA = Buffer.from(String(a), 'utf8');
|
||||||
|
const bufB = Buffer.from(String(b), 'utf8');
|
||||||
|
if (bufA.length !== bufB.length) {
|
||||||
|
// 长度不同时也做一次等长比较,减少长度信息泄露
|
||||||
|
crypto.timingSafeEqual(bufA, bufA);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return crypto.timingSafeEqual(bufA, bufB);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 该监听器是否开启了认证(以是否配置用户名为准)。
|
||||||
|
* @param {{username?: string}} settings 监听器配置
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
function authRequired(settings) {
|
||||||
|
return Boolean(settings && settings.username);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验用户名密码。
|
||||||
|
* @param {{username?: string, password?: string}} settings 监听器配置
|
||||||
|
* @param {string} username 客户端提交的用户名
|
||||||
|
* @param {string} password 客户端提交的密码
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
function checkCredentials(settings, username, password) {
|
||||||
|
if (!authRequired(settings)) return true;
|
||||||
|
const userOk = safeEqual(settings.username, username || '');
|
||||||
|
const passOk = safeEqual(settings.password || '', password || '');
|
||||||
|
return userOk && passOk;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析 HTTP Basic 认证头。
|
||||||
|
* @param {string|undefined} header 形如 "Basic dXNlcjpwYXNz"
|
||||||
|
* @returns {{username: string, password: string}|null}
|
||||||
|
*/
|
||||||
|
function parseBasicHeader(header) {
|
||||||
|
if (!header) return null;
|
||||||
|
const match = /^Basic\s+([A-Za-z0-9+/=]+)\s*$/i.exec(String(header).trim());
|
||||||
|
if (!match) return null;
|
||||||
|
let decoded = '';
|
||||||
|
try {
|
||||||
|
decoded = Buffer.from(match[1], 'base64').toString('utf8');
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const index = decoded.indexOf(':');
|
||||||
|
if (index === -1) return null;
|
||||||
|
return { username: decoded.slice(0, index), password: decoded.slice(index + 1) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验 HTTP 请求里的 Proxy-Authorization / Authorization 头。
|
||||||
|
* @param {{username?: string, password?: string}} settings 监听器配置
|
||||||
|
* @param {string|undefined} header 认证头
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
function checkBasicHeader(settings, header) {
|
||||||
|
if (!authRequired(settings)) return true;
|
||||||
|
const credentials = parseBasicHeader(header);
|
||||||
|
if (!credentials) return false;
|
||||||
|
return checkCredentials(settings, credentials.username, credentials.password);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
safeEqual,
|
||||||
|
authRequired,
|
||||||
|
checkCredentials,
|
||||||
|
parseBasicHeader,
|
||||||
|
checkBasicHeader,
|
||||||
|
};
|
||||||
+203
@@ -0,0 +1,203 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 配置读取、校验与持久化。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
const { parseEntry } = require('./ipFilter');
|
||||||
|
|
||||||
|
/** 默认配置(首次启动时自动写入 config.json) */
|
||||||
|
const DEFAULT_CONFIG = {
|
||||||
|
admin: {
|
||||||
|
host: '127.0.0.1',
|
||||||
|
port: 8790,
|
||||||
|
username: '',
|
||||||
|
password: '',
|
||||||
|
},
|
||||||
|
http: {
|
||||||
|
enabled: true,
|
||||||
|
host: '0.0.0.0',
|
||||||
|
port: 8080,
|
||||||
|
username: '',
|
||||||
|
password: '',
|
||||||
|
},
|
||||||
|
socks5: {
|
||||||
|
enabled: true,
|
||||||
|
host: '0.0.0.0',
|
||||||
|
port: 1080,
|
||||||
|
username: '',
|
||||||
|
password: '',
|
||||||
|
},
|
||||||
|
targetFilter: {
|
||||||
|
mode: 'allowAll',
|
||||||
|
allowList: [],
|
||||||
|
},
|
||||||
|
logLevel: 'info',
|
||||||
|
};
|
||||||
|
|
||||||
|
const LOG_LEVELS = ['error', 'warn', 'info', 'debug'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 深拷贝一个纯 JSON 对象。
|
||||||
|
* @template T
|
||||||
|
* @param {T} value 源对象
|
||||||
|
* @returns {T}
|
||||||
|
*/
|
||||||
|
function clone(value) {
|
||||||
|
return JSON.parse(JSON.stringify(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验并补全“监听器”配置(HTTP / SOCKS5 / 管理页面)。
|
||||||
|
* @param {any} raw 原始配置片段(应已与默认值合并)
|
||||||
|
* @param {string} label 用于错误提示的名称
|
||||||
|
* @returns {{enabled: boolean, host: string, port: number, username: string, password: string}}
|
||||||
|
*/
|
||||||
|
function normalizeListener(raw, label) {
|
||||||
|
const source = raw && typeof raw === 'object' ? raw : {};
|
||||||
|
|
||||||
|
const port = Number(source.port);
|
||||||
|
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
||||||
|
throw new Error(`${label}端口不合法,应为 0-65535 的整数(0 表示随机端口)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const host = source.host === undefined || source.host === null ? '0.0.0.0' : String(source.host).trim();
|
||||||
|
if (!host) throw new Error(`${label}监听地址不能为空`);
|
||||||
|
|
||||||
|
const username = source.username == null ? '' : String(source.username);
|
||||||
|
const password = source.password == null ? '' : String(source.password);
|
||||||
|
if (!username && password) {
|
||||||
|
throw new Error(`${label}填写了密码但没有填写用户名,请同时填写或同时留空`);
|
||||||
|
}
|
||||||
|
if (username && username.includes(':')) {
|
||||||
|
throw new Error(`${label}用户名不能包含英文冒号`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
enabled: source.enabled !== false,
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验并补全完整配置。
|
||||||
|
* @param {any} raw 原始配置对象
|
||||||
|
* @returns {typeof DEFAULT_CONFIG} 规范化后的配置
|
||||||
|
* @throws {Error} 配置不合法时抛出中文错误信息
|
||||||
|
*/
|
||||||
|
function normalizeConfig(raw) {
|
||||||
|
const source = raw && typeof raw === 'object' ? raw : {};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用默认值补齐缺失字段后校验单个监听器。
|
||||||
|
* @param {any} section 配置片段
|
||||||
|
* @param {keyof typeof DEFAULT_CONFIG} key 默认值键名
|
||||||
|
* @param {string} label 显示名称
|
||||||
|
* @returns {{enabled: boolean, host: string, port: number, username: string, password: string}}
|
||||||
|
*/
|
||||||
|
const buildListener = (section, key, label) =>
|
||||||
|
normalizeListener({ ...DEFAULT_CONFIG[key], ...(section && typeof section === 'object' ? section : {}) }, label);
|
||||||
|
|
||||||
|
const config = {
|
||||||
|
admin: buildListener(source.admin, 'admin', '管理页面'),
|
||||||
|
http: buildListener(source.http, 'http', 'HTTP 代理'),
|
||||||
|
socks5: buildListener(source.socks5, 'socks5', 'SOCKS5 代理'),
|
||||||
|
targetFilter: {
|
||||||
|
mode: 'allowAll',
|
||||||
|
allowList: [],
|
||||||
|
},
|
||||||
|
logLevel: 'info',
|
||||||
|
};
|
||||||
|
|
||||||
|
// 管理页面没有“启用/停用”概念,去掉多余字段
|
||||||
|
delete config.admin.enabled;
|
||||||
|
|
||||||
|
// 管理页面必须固定端口,不允许随机
|
||||||
|
if (config.admin.port === 0) throw new Error('管理页面端口不能为 0');
|
||||||
|
|
||||||
|
// 目标 IP 过滤
|
||||||
|
const filterRaw = source.targetFilter && typeof source.targetFilter === 'object' ? source.targetFilter : {};
|
||||||
|
const mode = filterRaw.mode === 'allowList' ? 'allowList' : 'allowAll';
|
||||||
|
const allowList = Array.isArray(filterRaw.allowList) ? filterRaw.allowList : [];
|
||||||
|
const cleanedList = allowList.map((item) => String(item == null ? '' : item).trim()).filter(Boolean);
|
||||||
|
// 逐条解析,尽早发现非法 IP/CIDR
|
||||||
|
for (const entry of cleanedList) parseEntry(entry);
|
||||||
|
config.targetFilter = { mode, allowList: cleanedList };
|
||||||
|
|
||||||
|
// 日志级别
|
||||||
|
if (source.logLevel !== undefined) {
|
||||||
|
if (!LOG_LEVELS.includes(source.logLevel)) {
|
||||||
|
throw new Error(`日志级别不合法,可选值:${LOG_LEVELS.join(' / ')}`);
|
||||||
|
}
|
||||||
|
config.logLevel = source.logLevel;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 端口冲突检查:三个监听器必须使用不同端口
|
||||||
|
const used = [];
|
||||||
|
const listeners = [
|
||||||
|
['管理页面', config.admin, true],
|
||||||
|
['HTTP 代理', config.http, config.http.enabled],
|
||||||
|
['SOCKS5 代理', config.socks5, config.socks5.enabled],
|
||||||
|
];
|
||||||
|
for (const [label, listener, active] of listeners) {
|
||||||
|
if (!active) continue;
|
||||||
|
if (listener.port === 0) continue;
|
||||||
|
const conflict = used.find((item) => item.port === listener.port);
|
||||||
|
if (conflict) {
|
||||||
|
throw new Error(`${label}端口 ${listener.port} 与${conflict.label}端口冲突`);
|
||||||
|
}
|
||||||
|
used.push({ label, port: listener.port });
|
||||||
|
}
|
||||||
|
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读取配置文件;文件不存在时写入默认配置。
|
||||||
|
* @param {string} file 配置文件绝对路径
|
||||||
|
* @returns {typeof DEFAULT_CONFIG}
|
||||||
|
*/
|
||||||
|
function loadConfig(file) {
|
||||||
|
if (!fs.existsSync(file)) {
|
||||||
|
const config = clone(DEFAULT_CONFIG);
|
||||||
|
saveConfig(file, config);
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
const text = fs.readFileSync(file, 'utf8');
|
||||||
|
if (!text.trim()) {
|
||||||
|
const config = clone(DEFAULT_CONFIG);
|
||||||
|
saveConfig(file, config);
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
let raw;
|
||||||
|
try {
|
||||||
|
raw = JSON.parse(text);
|
||||||
|
} catch (err) {
|
||||||
|
throw new Error(`配置文件解析失败:${err.message}`);
|
||||||
|
}
|
||||||
|
return normalizeConfig(raw);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保存配置到磁盘。
|
||||||
|
* @param {string} file 配置文件绝对路径
|
||||||
|
* @param {typeof DEFAULT_CONFIG} config 配置对象
|
||||||
|
*/
|
||||||
|
function saveConfig(file, config) {
|
||||||
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||||
|
fs.writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`, 'utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
DEFAULT_CONFIG,
|
||||||
|
LOG_LEVELS,
|
||||||
|
normalizeConfig,
|
||||||
|
loadConfig,
|
||||||
|
saveConfig,
|
||||||
|
clone,
|
||||||
|
};
|
||||||
@@ -0,0 +1,368 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTP 代理服务。
|
||||||
|
* - 支持普通 HTTP 请求转发(绝对 URI 形式)
|
||||||
|
* - 支持 HTTPS / 任意 TCP 的 CONNECT 隧道
|
||||||
|
* - 支持 WebSocket(Upgrade)透传
|
||||||
|
* - 支持 Basic 代理认证与目标 IP 白名单
|
||||||
|
*/
|
||||||
|
|
||||||
|
const http = require('node:http');
|
||||||
|
const net = require('node:net');
|
||||||
|
const { checkBasicHeader } = require('./auth');
|
||||||
|
const { resolveAllowed } = require('./resolver');
|
||||||
|
const { bridge, splitHostPort, stripBrackets } = require('./util');
|
||||||
|
|
||||||
|
/** 复用连接到目标服务器,降低握手开销 */
|
||||||
|
const httpAgent = new http.Agent({ keepAlive: true, maxSockets: 256, keepAliveMsecs: 30000 });
|
||||||
|
|
||||||
|
const AUTH_REALM = 'Basic realm="Frost Network Proxy", charset="UTF-8"';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 返回 407 需要代理认证。
|
||||||
|
* @param {import('node:http').ServerResponse} res 响应对象
|
||||||
|
*/
|
||||||
|
function sendAuthRequired(res) {
|
||||||
|
const body = 'Proxy authentication required.';
|
||||||
|
res.writeHead(407, {
|
||||||
|
'proxy-authenticate': AUTH_REALM,
|
||||||
|
'content-type': 'text/plain; charset=utf-8',
|
||||||
|
'content-length': Buffer.byteLength(body),
|
||||||
|
});
|
||||||
|
res.end(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 返回纯文本响应。
|
||||||
|
* @param {import('node:http').ServerResponse} res 响应对象
|
||||||
|
* @param {number} status 状态码
|
||||||
|
* @param {string} message 内容
|
||||||
|
*/
|
||||||
|
function sendText(res, status, message) {
|
||||||
|
const body = `${message}\n`;
|
||||||
|
res.writeHead(status, {
|
||||||
|
'content-type': 'text/plain; charset=utf-8',
|
||||||
|
'content-length': Buffer.byteLength(body),
|
||||||
|
});
|
||||||
|
res.end(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理普通 HTTP 代理请求。
|
||||||
|
* @param {object} ctx 上下文
|
||||||
|
* @param {import('node:http').IncomingMessage} req 请求
|
||||||
|
* @param {import('node:http').ServerResponse} res 响应
|
||||||
|
*/
|
||||||
|
async function handleRequest(ctx, req, res) {
|
||||||
|
const settings = ctx.getSettings();
|
||||||
|
|
||||||
|
// 1. 认证
|
||||||
|
if (!checkBasicHeader(settings.http, req.headers['proxy-authorization'])) {
|
||||||
|
return sendAuthRequired(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 解析目标地址(HTTP 代理要求绝对 URI)
|
||||||
|
let target;
|
||||||
|
try {
|
||||||
|
target = new URL(req.url);
|
||||||
|
} catch {
|
||||||
|
return sendText(res, 400, '请求地址无效,HTTP 代理需要 absolute-form 请求,例如 GET http://example.com/ HTTP/1.1');
|
||||||
|
}
|
||||||
|
if (target.protocol !== 'http:') {
|
||||||
|
return sendText(res, 400, `不支持的协议:${target.protocol},HTTPS 请使用 CONNECT 隧道`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const host = stripBrackets(target.hostname);
|
||||||
|
const port = Number(target.port) || 80;
|
||||||
|
|
||||||
|
// 3. 白名单校验
|
||||||
|
let address;
|
||||||
|
try {
|
||||||
|
address = await resolveAllowed(host, settings.filter);
|
||||||
|
} catch (err) {
|
||||||
|
const status = err.code === 'EBLOCKED' ? 403 : 502;
|
||||||
|
ctx.logger.debug(`[HTTP] 拒绝请求 ${host}:${port} - ${err.message}`);
|
||||||
|
return sendText(res, status, err.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 组装上游请求头(去掉代理专用头)
|
||||||
|
const headers = { ...req.headers, host: target.host || host };
|
||||||
|
delete headers['proxy-authorization'];
|
||||||
|
delete headers['proxy-connection'];
|
||||||
|
|
||||||
|
const options = {
|
||||||
|
host: address,
|
||||||
|
port,
|
||||||
|
method: req.method,
|
||||||
|
path: `${target.pathname}${target.search}` || '/',
|
||||||
|
headers,
|
||||||
|
agent: httpAgent,
|
||||||
|
};
|
||||||
|
if (net.isIP(address) === 6) options.family = 6;
|
||||||
|
|
||||||
|
ctx.logger.debug(`[HTTP] ${req.method} ${host}:${port}${options.path} → ${address}`);
|
||||||
|
|
||||||
|
ctx.stats.open('http');
|
||||||
|
let released = false;
|
||||||
|
const release = () => {
|
||||||
|
if (released) return;
|
||||||
|
released = true;
|
||||||
|
ctx.stats.close('http');
|
||||||
|
};
|
||||||
|
|
||||||
|
const proxyReq = http.request(options);
|
||||||
|
|
||||||
|
req.on('data', (chunk) => ctx.stats.addUp('http', chunk.length));
|
||||||
|
|
||||||
|
proxyReq.on('response', (proxyRes) => {
|
||||||
|
res.writeHead(proxyRes.statusCode || 502, proxyRes.statusMessage, proxyRes.headers);
|
||||||
|
proxyRes.on('data', (chunk) => ctx.stats.addDown('http', chunk.length));
|
||||||
|
proxyRes.on('end', release);
|
||||||
|
proxyRes.on('error', () => res.destroy());
|
||||||
|
proxyRes.pipe(res);
|
||||||
|
});
|
||||||
|
|
||||||
|
proxyReq.on('error', (err) => {
|
||||||
|
ctx.logger.debug(`[HTTP] 上游连接失败 ${host}:${port} - ${err.message}`);
|
||||||
|
if (!res.headersSent) sendText(res, 502, `无法连接目标服务器:${err.message}`);
|
||||||
|
else res.destroy();
|
||||||
|
release();
|
||||||
|
});
|
||||||
|
|
||||||
|
res.on('close', () => {
|
||||||
|
proxyReq.destroy();
|
||||||
|
release();
|
||||||
|
});
|
||||||
|
|
||||||
|
req.pipe(proxyReq);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理 CONNECT 隧道请求(HTTPS 等)。
|
||||||
|
* @param {object} ctx 上下文
|
||||||
|
* @param {import('node:http').IncomingMessage} req 请求
|
||||||
|
* @param {import('node:net').Socket} socket 客户端 socket
|
||||||
|
* @param {Buffer} head 已读取的额外数据
|
||||||
|
*/
|
||||||
|
async function handleConnect(ctx, req, socket, head) {
|
||||||
|
const settings = ctx.getSettings();
|
||||||
|
socket.on('error', () => socket.destroy());
|
||||||
|
|
||||||
|
// 1. 认证
|
||||||
|
if (!checkBasicHeader(settings.http, req.headers['proxy-authorization'])) {
|
||||||
|
socket.end(
|
||||||
|
'HTTP/1.1 407 Proxy Authentication Required\r\n' +
|
||||||
|
`Proxy-Authenticate: ${AUTH_REALM}\r\n` +
|
||||||
|
'Content-Length: 0\r\nConnection: close\r\n\r\n',
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 解析目标
|
||||||
|
let target;
|
||||||
|
try {
|
||||||
|
target = splitHostPort(req.url, 443);
|
||||||
|
} catch (err) {
|
||||||
|
socket.end('HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 白名单校验
|
||||||
|
let address;
|
||||||
|
try {
|
||||||
|
address = await resolveAllowed(target.host, settings.filter);
|
||||||
|
} catch (err) {
|
||||||
|
const statusLine = err.code === 'EBLOCKED' ? '403 Forbidden' : '502 Bad Gateway';
|
||||||
|
socket.end(`HTTP/1.1 ${statusLine}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 建立隧道
|
||||||
|
const upstream = net.connect({ host: address, port: target.port });
|
||||||
|
upstream.setNoDelay(true);
|
||||||
|
|
||||||
|
ctx.stats.open('http');
|
||||||
|
let released = false;
|
||||||
|
const release = () => {
|
||||||
|
if (released) return;
|
||||||
|
released = true;
|
||||||
|
ctx.stats.close('http');
|
||||||
|
};
|
||||||
|
|
||||||
|
upstream.once('connect', () => {
|
||||||
|
socket.write('HTTP/1.1 200 Connection Established\r\nProxy-Agent: frost-network-proxy\r\n\r\n');
|
||||||
|
if (head && head.length) upstream.write(head);
|
||||||
|
bridge(socket, upstream, {
|
||||||
|
onUp: (bytes) => ctx.stats.addUp('http', bytes),
|
||||||
|
onDown: (bytes) => ctx.stats.addDown('http', bytes),
|
||||||
|
onClose: release,
|
||||||
|
});
|
||||||
|
ctx.logger.info(`[HTTP] CONNECT ${target.host}:${target.port} → ${address}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
upstream.once('error', (err) => {
|
||||||
|
ctx.logger.debug(`[HTTP] CONNECT 失败 ${target.host}:${target.port} - ${err.message}`);
|
||||||
|
if (!socket.destroyed) {
|
||||||
|
socket.end('HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n');
|
||||||
|
}
|
||||||
|
release();
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.once('close', () => {
|
||||||
|
if (!upstream.destroyed) upstream.destroy();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理 Upgrade 请求(WebSocket 等)。
|
||||||
|
* @param {object} ctx 上下文
|
||||||
|
* @param {import('node:http').IncomingMessage} req 请求
|
||||||
|
* @param {import('node:net').Socket} socket 客户端 socket
|
||||||
|
* @param {Buffer} head 已读取的额外数据
|
||||||
|
*/
|
||||||
|
async function handleUpgrade(ctx, req, socket, head) {
|
||||||
|
const settings = ctx.getSettings();
|
||||||
|
socket.on('error', () => socket.destroy());
|
||||||
|
|
||||||
|
if (!checkBasicHeader(settings.http, req.headers['proxy-authorization'])) {
|
||||||
|
socket.end(
|
||||||
|
'HTTP/1.1 407 Proxy Authentication Required\r\n' +
|
||||||
|
`Proxy-Authenticate: ${AUTH_REALM}\r\n` +
|
||||||
|
'Content-Length: 0\r\nConnection: close\r\n\r\n',
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let target;
|
||||||
|
try {
|
||||||
|
target = new URL(req.url);
|
||||||
|
} catch {
|
||||||
|
socket.end('HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const host = stripBrackets(target.hostname);
|
||||||
|
const port = Number(target.port) || 80;
|
||||||
|
|
||||||
|
let address;
|
||||||
|
try {
|
||||||
|
address = await resolveAllowed(host, settings.filter);
|
||||||
|
} catch (err) {
|
||||||
|
const statusLine = err.code === 'EBLOCKED' ? '403 Forbidden' : '502 Bad Gateway';
|
||||||
|
socket.end(`HTTP/1.1 ${statusLine}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const headers = { ...req.headers, host: target.host || host };
|
||||||
|
delete headers['proxy-authorization'];
|
||||||
|
delete headers['proxy-connection'];
|
||||||
|
|
||||||
|
ctx.stats.open('http');
|
||||||
|
let released = false;
|
||||||
|
const release = () => {
|
||||||
|
if (released) return;
|
||||||
|
released = true;
|
||||||
|
ctx.stats.close('http');
|
||||||
|
};
|
||||||
|
|
||||||
|
const proxyReq = http.request({
|
||||||
|
host: address,
|
||||||
|
port,
|
||||||
|
method: req.method,
|
||||||
|
path: `${target.pathname}${target.search}` || '/',
|
||||||
|
headers,
|
||||||
|
agent: httpAgent,
|
||||||
|
});
|
||||||
|
|
||||||
|
proxyReq.on('upgrade', (proxyRes, proxySocket, proxyHead) => {
|
||||||
|
// 原样回写 101 响应头
|
||||||
|
let raw = 'HTTP/1.1 101 Switching Protocols\r\n';
|
||||||
|
for (let i = 0; i < proxyRes.rawHeaders.length; i += 2) {
|
||||||
|
raw += `${proxyRes.rawHeaders[i]}: ${proxyRes.rawHeaders[i + 1]}\r\n`;
|
||||||
|
}
|
||||||
|
socket.write(`${raw}\r\n`);
|
||||||
|
if (proxyHead && proxyHead.length) socket.write(proxyHead);
|
||||||
|
if (head && head.length) proxySocket.write(head);
|
||||||
|
|
||||||
|
bridge(socket, proxySocket, {
|
||||||
|
onUp: (bytes) => ctx.stats.addUp('http', bytes),
|
||||||
|
onDown: (bytes) => ctx.stats.addDown('http', bytes),
|
||||||
|
onClose: release,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
proxyReq.on('response', (proxyRes) => {
|
||||||
|
// 目标不接受升级时,把原响应透传给客户端
|
||||||
|
forwardResponse(proxyRes);
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把普通响应透传到客户端 socket。
|
||||||
|
* @param {import('node:http').IncomingMessage} proxyRes 上游响应
|
||||||
|
*/
|
||||||
|
function forwardResponse(proxyRes) {
|
||||||
|
let raw = `HTTP/1.1 ${proxyRes.statusCode} ${proxyRes.statusMessage || ''}\r\n`;
|
||||||
|
for (let i = 0; i < proxyRes.rawHeaders.length; i += 2) {
|
||||||
|
raw += `${proxyRes.rawHeaders[i]}: ${proxyRes.rawHeaders[i + 1]}\r\n`;
|
||||||
|
}
|
||||||
|
socket.write(`${raw}\r\n`);
|
||||||
|
proxyRes.pipe(socket);
|
||||||
|
proxyRes.on('end', release);
|
||||||
|
}
|
||||||
|
|
||||||
|
proxyReq.on('error', (err) => {
|
||||||
|
ctx.logger.debug(`[HTTP] Upgrade 失败 ${host}:${port} - ${err.message}`);
|
||||||
|
if (!socket.destroyed) {
|
||||||
|
socket.end('HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n');
|
||||||
|
}
|
||||||
|
release();
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.once('close', () => {
|
||||||
|
proxyReq.destroy();
|
||||||
|
release();
|
||||||
|
});
|
||||||
|
|
||||||
|
proxyReq.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建 HTTP 代理服务器(尚未 listen)。
|
||||||
|
* @param {object} ctx 上下文:{ getSettings, logger, stats }
|
||||||
|
* @returns {import('node:http').Server}
|
||||||
|
*/
|
||||||
|
function createHttpProxyServer(ctx) {
|
||||||
|
const server = http.createServer();
|
||||||
|
|
||||||
|
server.on('request', (req, res) => {
|
||||||
|
void handleRequest(ctx, req, res).catch((err) => {
|
||||||
|
ctx.logger.error(`[HTTP] 处理请求异常:${err.message}`);
|
||||||
|
if (!res.headersSent) sendText(res, 500, '代理内部错误');
|
||||||
|
else res.destroy();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
server.on('connect', (req, socket, head) => {
|
||||||
|
void handleConnect(ctx, req, socket, head).catch((err) => {
|
||||||
|
ctx.logger.error(`[HTTP] CONNECT 异常:${err.message}`);
|
||||||
|
socket.destroy();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
server.on('upgrade', (req, socket, head) => {
|
||||||
|
void handleUpgrade(ctx, req, socket, head).catch((err) => {
|
||||||
|
ctx.logger.error(`[HTTP] Upgrade 异常:${err.message}`);
|
||||||
|
socket.destroy();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
server.on('clientError', (err, socket) => {
|
||||||
|
if (socket.writable) socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
|
||||||
|
else socket.destroy();
|
||||||
|
});
|
||||||
|
|
||||||
|
return server;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createHttpProxyServer };
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 程序入口:加载配置 → 启动代理 → 启动配置页面。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const path = require('node:path');
|
||||||
|
const { loadConfig } = require('./config');
|
||||||
|
const { Logger } = require('./logger');
|
||||||
|
const { ProxyManager } = require('./proxyManager');
|
||||||
|
const { AdminServer } = require('./adminServer');
|
||||||
|
|
||||||
|
const CONFIG_FILE = process.env.PROXY_CONFIG
|
||||||
|
? path.resolve(process.env.PROXY_CONFIG)
|
||||||
|
: path.join(__dirname, '..', 'config.json');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打印启动横幅。
|
||||||
|
* @param {object} config 配置
|
||||||
|
* @param {import('./proxyManager').ProxyManager} manager 管理器
|
||||||
|
* @param {import('./adminServer').AdminServer} admin 管理服务器
|
||||||
|
*/
|
||||||
|
function printBanner(config, manager, admin) {
|
||||||
|
const lines = [];
|
||||||
|
lines.push('');
|
||||||
|
lines.push(' Frost Network Proxy');
|
||||||
|
lines.push(' ─────────────────────────────────────────────');
|
||||||
|
if (admin.address) {
|
||||||
|
lines.push(` 配置页面 http://${admin.address.host}:${admin.address.port}`);
|
||||||
|
}
|
||||||
|
const httpStatus = manager.getStatus().http;
|
||||||
|
if (httpStatus.listening) {
|
||||||
|
lines.push(` HTTP 代理 http://${httpStatus.host}:${httpStatus.actualPort}${httpStatus.authEnabled ? '(需要认证)' : ''}`);
|
||||||
|
} else {
|
||||||
|
lines.push(' HTTP 代理 未启用');
|
||||||
|
}
|
||||||
|
const socksStatus = manager.getStatus().socks5;
|
||||||
|
if (socksStatus.listening) {
|
||||||
|
lines.push(` SOCKS5 代理 socks5://${socksStatus.host}:${socksStatus.actualPort}${socksStatus.authEnabled ? '(需要认证)' : ''}`);
|
||||||
|
} else {
|
||||||
|
lines.push(' SOCKS5 代理 未启用');
|
||||||
|
}
|
||||||
|
const filter = config.targetFilter;
|
||||||
|
lines.push(
|
||||||
|
` 目标 IP ${filter.mode === 'allowAll' ? '允许全部' : `白名单模式(${filter.allowList.length} 条规则)`}`,
|
||||||
|
);
|
||||||
|
lines.push(' ─────────────────────────────────────────────');
|
||||||
|
lines.push(' 按 Ctrl+C 退出');
|
||||||
|
lines.push('');
|
||||||
|
console.log(lines.join('\n'));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
let config;
|
||||||
|
try {
|
||||||
|
config = loadConfig(CONFIG_FILE);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`[FATAL] 配置加载失败:${err.message}`);
|
||||||
|
process.exit(1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const logger = new Logger(config.logLevel);
|
||||||
|
const manager = new ProxyManager({ config, logger, configPath: CONFIG_FILE });
|
||||||
|
|
||||||
|
await manager.apply(config);
|
||||||
|
|
||||||
|
const admin = new AdminServer({ manager, logger, configPath: CONFIG_FILE });
|
||||||
|
try {
|
||||||
|
await admin.start(config.admin);
|
||||||
|
} catch (err) {
|
||||||
|
logger.error(`[ADMIN] 配置页面启动失败:${manager.describeListenError(err)}`);
|
||||||
|
logger.error('[ADMIN] 代理服务仍在运行,请修改 config.json 中的 admin 端口后重启');
|
||||||
|
}
|
||||||
|
|
||||||
|
printBanner(config, manager, admin);
|
||||||
|
|
||||||
|
let shuttingDown = false;
|
||||||
|
const shutdown = (signal) => {
|
||||||
|
if (shuttingDown) return;
|
||||||
|
shuttingDown = true;
|
||||||
|
logger.info(`收到 ${signal},正在退出…`);
|
||||||
|
manager.stopAll();
|
||||||
|
void admin.stop();
|
||||||
|
setTimeout(() => process.exit(0), 200).unref();
|
||||||
|
};
|
||||||
|
|
||||||
|
process.on('SIGINT', () => shutdown('SIGINT'));
|
||||||
|
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
||||||
|
process.on('uncaughtException', (err) => {
|
||||||
|
logger.error(`未捕获异常:${err.stack || err.message}`);
|
||||||
|
});
|
||||||
|
process.on('unhandledRejection', (reason) => {
|
||||||
|
logger.error(`未处理的 Promise 拒绝:${reason && reason.stack ? reason.stack : reason}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void main();
|
||||||
+190
@@ -0,0 +1,190 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IP 白名单匹配工具。
|
||||||
|
* 支持单个 IPv4 / IPv6 地址,以及 CIDR 网段(例如 192.168.1.0/24、2001:db8::/32)。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const net = require('node:net');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 点分十进制 IPv4 转为 BigInt。
|
||||||
|
* @param {string} ip 例如 "192.168.1.10"
|
||||||
|
* @returns {bigint|null} 非法时返回 null
|
||||||
|
*/
|
||||||
|
function ipv4ToBigInt(ip) {
|
||||||
|
const parts = String(ip).split('.');
|
||||||
|
if (parts.length !== 4) return null;
|
||||||
|
let value = 0n;
|
||||||
|
for (const part of parts) {
|
||||||
|
if (!/^\d{1,3}$/.test(part)) return null;
|
||||||
|
const num = Number(part);
|
||||||
|
if (num > 255) return null;
|
||||||
|
value = (value << 8n) | BigInt(num);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IPv6 转为 BigInt,兼容 "::" 压缩写法以及尾部内嵌 IPv4 的写法。
|
||||||
|
* @param {string} ip 例如 "2001:db8::1"、"::ffff:192.168.0.1"
|
||||||
|
* @returns {bigint|null} 非法时返回 null
|
||||||
|
*/
|
||||||
|
function ipv6ToBigInt(ip) {
|
||||||
|
let text = String(ip).trim();
|
||||||
|
const extraGroups = [];
|
||||||
|
|
||||||
|
// 处理尾部内嵌 IPv4 的情况,把它拆成两个十六进制组
|
||||||
|
const dottedMatch = text.match(/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
|
||||||
|
if (dottedMatch) {
|
||||||
|
const v4 = ipv4ToBigInt(dottedMatch[1]);
|
||||||
|
if (v4 === null) return null;
|
||||||
|
extraGroups.push((v4 >> 16n).toString(16), (v4 & 0xffffn).toString(16));
|
||||||
|
text = text.slice(0, text.length - dottedMatch[1].length);
|
||||||
|
if (text.endsWith(':')) text = text.slice(0, -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let head = [];
|
||||||
|
let tail = [];
|
||||||
|
if (text.includes('::')) {
|
||||||
|
// 只允许出现一次 "::"
|
||||||
|
if (text.split('::').length > 2) return null;
|
||||||
|
const [h, t] = text.split('::');
|
||||||
|
head = h ? h.split(':') : [];
|
||||||
|
tail = t ? t.split(':') : [];
|
||||||
|
} else {
|
||||||
|
head = text ? text.split(':') : [];
|
||||||
|
}
|
||||||
|
tail = tail.concat(extraGroups);
|
||||||
|
|
||||||
|
const filled = 8 - head.length - tail.length;
|
||||||
|
if (filled < 0) return null;
|
||||||
|
const groups = head.concat(new Array(filled).fill('0'), tail);
|
||||||
|
|
||||||
|
let value = 0n;
|
||||||
|
for (const group of groups) {
|
||||||
|
if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return null;
|
||||||
|
value = (value << 16n) + BigInt(parseInt(group, 16));
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把任意 IP 字符串规格化为 { version, value }。
|
||||||
|
* IPv4-mapped 的 IPv6 地址(::ffff:a.b.c.d)会被归一成 IPv4,便于命中白名单。
|
||||||
|
* @param {string} ip IP 字符串
|
||||||
|
* @returns {{version: 4|6, value: bigint}|null}
|
||||||
|
*/
|
||||||
|
function toAddress(ip) {
|
||||||
|
let text = String(ip || '').trim();
|
||||||
|
if (!text) return null;
|
||||||
|
// 去掉 IPv6 的 zone id,例如 fe80::1%eth0
|
||||||
|
const zoneIndex = text.indexOf('%');
|
||||||
|
if (zoneIndex !== -1) text = text.slice(0, zoneIndex);
|
||||||
|
|
||||||
|
if (net.isIPv4(text)) {
|
||||||
|
const value = ipv4ToBigInt(text);
|
||||||
|
return value === null ? null : { version: 4, value };
|
||||||
|
}
|
||||||
|
if (net.isIPv6(text)) {
|
||||||
|
const mapped = text.match(/^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/i);
|
||||||
|
if (mapped) {
|
||||||
|
const value = ipv4ToBigInt(mapped[1]);
|
||||||
|
return value === null ? null : { version: 4, value };
|
||||||
|
}
|
||||||
|
const value = ipv6ToBigInt(text);
|
||||||
|
return value === null ? null : { version: 6, value };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析一条白名单规则(支持 IP 与 CIDR)。
|
||||||
|
* @param {string} entry 例如 "10.0.0.1"、"192.168.0.0/16"
|
||||||
|
* @returns {{version: 4|6, base: bigint, prefix: number, bits: number, text: string}}
|
||||||
|
* @throws {Error} 规则非法时抛出可读的中文错误
|
||||||
|
*/
|
||||||
|
function parseEntry(entry) {
|
||||||
|
const text = String(entry == null ? '' : entry).trim();
|
||||||
|
if (!text) throw new Error('存在空白的目标 IP 规则');
|
||||||
|
|
||||||
|
const segments = text.split('/');
|
||||||
|
if (segments.length > 2) throw new Error(`IP 规则格式错误:${text}`);
|
||||||
|
|
||||||
|
const address = toAddress(segments[0]);
|
||||||
|
if (!address) throw new Error(`无法识别的 IP 地址:${text}`);
|
||||||
|
|
||||||
|
const bits = address.version === 4 ? 32 : 128;
|
||||||
|
let prefix = bits;
|
||||||
|
if (segments[1] !== undefined) {
|
||||||
|
if (!/^\d{1,3}$/.test(segments[1])) throw new Error(`网段前缀格式错误:${text}`);
|
||||||
|
prefix = Number(segments[1]);
|
||||||
|
if (prefix > bits) throw new Error(`网段前缀超出范围(最大 ${bits}):${text}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { version: address.version, base: address.value, prefix, bits, text };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断某个 IP 值是否落在规则网段内。
|
||||||
|
* @param {{version: number, base: bigint, prefix: number, bits: number}} rule 规则
|
||||||
|
* @param {{version: number, value: bigint}} address 目标地址
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
function matchRule(rule, address) {
|
||||||
|
if (rule.version !== address.version) return false;
|
||||||
|
const shift = BigInt(rule.bits - rule.prefix);
|
||||||
|
// 前缀为 0 时全部匹配;其余情况比较高位是否一致
|
||||||
|
return (rule.base >> shift) === (address.value >> shift);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 目标 IP 过滤器。
|
||||||
|
* mode 为 "allowAll" 时全部放行;为 "allowList" 时仅放行列出的地址/网段。
|
||||||
|
*/
|
||||||
|
class IpFilter {
|
||||||
|
/**
|
||||||
|
* @param {{mode?: string, allowList?: string[]}} [options] 过滤配置
|
||||||
|
*/
|
||||||
|
constructor(options = {}) {
|
||||||
|
const mode = options.mode === 'allowList' ? 'allowList' : 'allowAll';
|
||||||
|
const allowList = Array.isArray(options.allowList) ? options.allowList : [];
|
||||||
|
this.mode = mode;
|
||||||
|
// 立即解析,配置非法时构造阶段就报错,避免运行期才暴露问题
|
||||||
|
this.rules = allowList
|
||||||
|
.map((item) => String(item || '').trim())
|
||||||
|
.filter((item) => item.length > 0)
|
||||||
|
.map((item) => parseEntry(item));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 是否处于“全部允许”模式 */
|
||||||
|
get allowAll() {
|
||||||
|
return this.mode === 'allowAll';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 规则条数 */
|
||||||
|
get size() {
|
||||||
|
return this.rules.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断目标 IP 是否允许代理。
|
||||||
|
* @param {string} ip 目标地址(域名请先解析成 IP)
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
allows(ip) {
|
||||||
|
if (this.allowAll) return true;
|
||||||
|
const address = toAddress(ip);
|
||||||
|
if (!address) return false;
|
||||||
|
// 白名单模式但没配置任何规则时,全部拒绝(更安全的默认行为)
|
||||||
|
return this.rules.some((rule) => matchRule(rule, address));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
IpFilter,
|
||||||
|
parseEntry,
|
||||||
|
toAddress,
|
||||||
|
ipv4ToBigInt,
|
||||||
|
ipv6ToBigInt,
|
||||||
|
};
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 轻量日志器:同时输出到控制台,并在内存里保留最近若干条供配置页面展示。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const LEVELS = ['error', 'warn', 'info', 'debug'];
|
||||||
|
|
||||||
|
class Logger {
|
||||||
|
/**
|
||||||
|
* @param {string} [level] 日志级别:error / warn / info / debug
|
||||||
|
*/
|
||||||
|
constructor(level = 'info') {
|
||||||
|
this.level = LEVELS.includes(level) ? level : 'info';
|
||||||
|
/** @type {{time: string, level: string, message: string}[]} */
|
||||||
|
this.buffer = [];
|
||||||
|
this.maxBuffer = 400;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 调整日志级别。
|
||||||
|
* @param {string} level 日志级别
|
||||||
|
*/
|
||||||
|
setLevel(level) {
|
||||||
|
if (LEVELS.includes(level)) this.level = level;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 写入一条日志。
|
||||||
|
* @param {'error'|'warn'|'info'|'debug'} level 级别
|
||||||
|
* @param {string} message 内容
|
||||||
|
*/
|
||||||
|
write(level, message) {
|
||||||
|
const entry = { time: new Date().toISOString(), level, message: String(message) };
|
||||||
|
this.buffer.push(entry);
|
||||||
|
if (this.buffer.length > this.maxBuffer) this.buffer.shift();
|
||||||
|
|
||||||
|
const line = `[${entry.time}] [${level.toUpperCase()}] ${message}`;
|
||||||
|
if (level === 'error') console.error(line);
|
||||||
|
else console.log(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string} message 内容 */
|
||||||
|
error(message) {
|
||||||
|
this.write('error', message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string} message 内容 */
|
||||||
|
warn(message) {
|
||||||
|
this.write('warn', message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string} message 内容 */
|
||||||
|
info(message) {
|
||||||
|
this.write('info', message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string} message 内容 */
|
||||||
|
debug(message) {
|
||||||
|
if (this.level === 'debug') this.write('debug', message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读取最近的日志。
|
||||||
|
* @param {number} [limit] 条数上限
|
||||||
|
* @returns {{time: string, level: string, message: string}[]}
|
||||||
|
*/
|
||||||
|
recent(limit = 200) {
|
||||||
|
return this.buffer.slice(-limit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { Logger, LEVELS };
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 代理服务管理器:根据配置启停 HTTP / SOCKS5 监听器,对外提供状态快照。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const { createHttpProxyServer } = require('./httpProxy');
|
||||||
|
const { createSocks5Server } = require('./socks5');
|
||||||
|
const { IpFilter } = require('./ipFilter');
|
||||||
|
const { TrafficStats } = require('./stats');
|
||||||
|
const { listen } = require('./util');
|
||||||
|
|
||||||
|
class ProxyManager {
|
||||||
|
/**
|
||||||
|
* @param {{config: object, logger: import('./logger').Logger, configPath?: string}} options 初始化参数
|
||||||
|
*/
|
||||||
|
constructor({ config, logger, configPath }) {
|
||||||
|
this.config = config;
|
||||||
|
this.logger = logger;
|
||||||
|
this.configPath = configPath;
|
||||||
|
|
||||||
|
this.stats = new TrafficStats();
|
||||||
|
// 启动带宽采样,采样点同时用于前端趋势图
|
||||||
|
this.stats.start();
|
||||||
|
this.filter = new IpFilter(config.targetFilter);
|
||||||
|
|
||||||
|
/** @type {import('node:http').Server|null} */
|
||||||
|
this.httpServer = null;
|
||||||
|
/** @type {import('node:net').Server|null} */
|
||||||
|
this.socksServer = null;
|
||||||
|
|
||||||
|
this.bound = { http: null, socks5: null };
|
||||||
|
this.errors = { http: null, socks5: null };
|
||||||
|
this.startedAt = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 供各协议模块读取的实时配置(认证、白名单支持热更新)。
|
||||||
|
* @returns {{http: object, socks5: object, filter: IpFilter}}
|
||||||
|
*/
|
||||||
|
getSettings() {
|
||||||
|
return {
|
||||||
|
http: this.config.http,
|
||||||
|
socks5: this.config.socks5,
|
||||||
|
filter: this.filter,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 应用一份新配置(按需重启端口)。
|
||||||
|
* @param {object} config 规范化后的配置
|
||||||
|
* @returns {Promise<object>} 最新状态
|
||||||
|
*/
|
||||||
|
async apply(config) {
|
||||||
|
this.config = config;
|
||||||
|
this.filter = new IpFilter(config.targetFilter);
|
||||||
|
|
||||||
|
await this.applyHttp();
|
||||||
|
await this.applySocks5();
|
||||||
|
return this.getStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 根据配置启动/重启 HTTP 代理 */
|
||||||
|
async applyHttp() {
|
||||||
|
const want = this.config.http;
|
||||||
|
const current = this.bound.http;
|
||||||
|
|
||||||
|
if (!want.enabled) {
|
||||||
|
this.stopListener('http');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this.httpServer && current && current.host === want.host && current.port === want.port) {
|
||||||
|
return; // 监听参数没变,配置已在 getSettings() 里热更新
|
||||||
|
}
|
||||||
|
this.stopListener('http');
|
||||||
|
|
||||||
|
const server = createHttpProxyServer({
|
||||||
|
getSettings: () => this.getSettings(),
|
||||||
|
logger: this.logger,
|
||||||
|
stats: this.stats,
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await listen(server, want.port, want.host);
|
||||||
|
} catch (err) {
|
||||||
|
this.errors.http = this.describeListenError(err);
|
||||||
|
this.logger.error(`[HTTP] 启动失败:${this.errors.http}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const actualPort = server.address().port;
|
||||||
|
server.on('error', (err) => {
|
||||||
|
this.errors.http = err.message;
|
||||||
|
this.logger.error(`[HTTP] 运行异常:${err.message}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
this.httpServer = server;
|
||||||
|
this.bound.http = { host: want.host, port: want.port, actualPort };
|
||||||
|
this.errors.http = null;
|
||||||
|
this.logger.info(`[HTTP] 代理已启动 http://${want.host}:${actualPort}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 根据配置启动/重启 SOCKS5 代理 */
|
||||||
|
async applySocks5() {
|
||||||
|
const want = this.config.socks5;
|
||||||
|
const current = this.bound.socks5;
|
||||||
|
|
||||||
|
if (!want.enabled) {
|
||||||
|
this.stopListener('socks5');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this.socksServer && current && current.host === want.host && current.port === want.port) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.stopListener('socks5');
|
||||||
|
|
||||||
|
const server = createSocks5Server({
|
||||||
|
getSettings: () => this.getSettings(),
|
||||||
|
logger: this.logger,
|
||||||
|
stats: this.stats,
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await listen(server, want.port, want.host);
|
||||||
|
} catch (err) {
|
||||||
|
this.errors.socks5 = this.describeListenError(err);
|
||||||
|
this.logger.error(`[SOCKS5] 启动失败:${this.errors.socks5}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const actualPort = server.address().port;
|
||||||
|
server.on('error', (err) => {
|
||||||
|
this.errors.socks5 = err.message;
|
||||||
|
this.logger.error(`[SOCKS5] 运行异常:${err.message}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
this.socksServer = server;
|
||||||
|
this.bound.socks5 = { host: want.host, port: want.port, actualPort };
|
||||||
|
this.errors.socks5 = null;
|
||||||
|
this.logger.info(`[SOCKS5] 代理已启动 socks5://${want.host}:${actualPort}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 停止指定监听器。已有的隧道连接会保留,等其自然结束。
|
||||||
|
* @param {'http'|'socks5'} name 监听器名称
|
||||||
|
*/
|
||||||
|
stopListener(name) {
|
||||||
|
const server = name === 'http' ? this.httpServer : this.socksServer;
|
||||||
|
if (!server) {
|
||||||
|
this.bound[name] = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
server.close();
|
||||||
|
// 关闭空闲连接,避免 keep-alive 拖住端口释放
|
||||||
|
if (typeof server.closeIdleConnections === 'function') server.closeIdleConnections();
|
||||||
|
} catch {
|
||||||
|
/* 忽略关闭异常 */
|
||||||
|
}
|
||||||
|
if (name === 'http') this.httpServer = null;
|
||||||
|
else this.socksServer = null;
|
||||||
|
this.bound[name] = null;
|
||||||
|
this.logger.info(`[${name.toUpperCase()}] 监听已停止`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 停止全部监听器(进程退出时使用) */
|
||||||
|
stopAll() {
|
||||||
|
for (const name of ['http', 'socks5']) {
|
||||||
|
const server = name === 'http' ? this.httpServer : this.socksServer;
|
||||||
|
if (!server) continue;
|
||||||
|
try {
|
||||||
|
server.close();
|
||||||
|
if (typeof server.closeAllConnections === 'function') server.closeAllConnections();
|
||||||
|
} catch {
|
||||||
|
/* 忽略关闭异常 */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.httpServer = null;
|
||||||
|
this.socksServer = null;
|
||||||
|
this.bound = { http: null, socks5: null };
|
||||||
|
this.stats.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把 listen 错误翻译成易读的中文。
|
||||||
|
* @param {NodeJS.ErrnoException} err 错误
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
describeListenError(err) {
|
||||||
|
if (err.code === 'EADDRINUSE') return `端口 ${err.port || ''} 已被占用,请更换端口`;
|
||||||
|
if (err.code === 'EACCES') return '没有权限监听该端口(1024 以下端口通常需要管理员权限)';
|
||||||
|
if (err.code === 'EADDRNOTAVAIL') return '监听地址在本机不存在,请检查 IP 是否属于本机网卡';
|
||||||
|
return err.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成状态快照,供配置页面展示。
|
||||||
|
* @returns {object}
|
||||||
|
*/
|
||||||
|
getStatus() {
|
||||||
|
const describe = (name, config) => {
|
||||||
|
const bound = this.bound[name];
|
||||||
|
return {
|
||||||
|
enabled: Boolean(config.enabled),
|
||||||
|
host: config.host,
|
||||||
|
port: config.port,
|
||||||
|
actualPort: bound ? bound.actualPort : null,
|
||||||
|
listening: Boolean(bound),
|
||||||
|
authEnabled: Boolean(config.username),
|
||||||
|
error: this.errors[name] || null,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
uptime: Math.floor((Date.now() - this.startedAt) / 1000),
|
||||||
|
startedAt: new Date(this.startedAt).toISOString(),
|
||||||
|
http: describe('http', this.config.http),
|
||||||
|
socks5: describe('socks5', this.config.socks5),
|
||||||
|
targetFilter: {
|
||||||
|
mode: this.config.targetFilter.mode,
|
||||||
|
allowList: this.config.targetFilter.allowList,
|
||||||
|
ruleCount: this.filter.size,
|
||||||
|
},
|
||||||
|
stats: this.stats.snapshot(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { ProxyManager };
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 目标地址解析 + 白名单校验。
|
||||||
|
* 所有协议在真正建立连接前都会走这里,保证“允许代理的目标 IP”规则统一生效。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const net = require('node:net');
|
||||||
|
const dns = require('node:dns');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析目标主机并在白名单中挑选可用 IP。
|
||||||
|
* @param {string} host 目标主机(域名或 IP)
|
||||||
|
* @param {import('./ipFilter').IpFilter} filter IP 过滤器
|
||||||
|
* @returns {Promise<string>} 可用的目标 IP
|
||||||
|
* @throws {Error} 带 code 的错误:EBLOCKED(被白名单拒绝)/ ENOTFOUND(解析失败)
|
||||||
|
*/
|
||||||
|
async function resolveAllowed(host, filter) {
|
||||||
|
const literal = net.isIP(host);
|
||||||
|
let addresses;
|
||||||
|
if (literal) {
|
||||||
|
addresses = [{ address: host, family: literal }];
|
||||||
|
} else {
|
||||||
|
addresses = await dns.promises.lookup(host, { all: true, verbatim: true });
|
||||||
|
if (!Array.isArray(addresses) || addresses.length === 0) {
|
||||||
|
const err = new Error(`无法解析目标域名:${host}`);
|
||||||
|
err.code = 'ENOTFOUND';
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const allowed = addresses.find((item) => filter.allows(item.address));
|
||||||
|
if (!allowed) {
|
||||||
|
const err = new Error(`目标 IP 不在允许列表:${addresses.map((item) => item.address).join(', ')}`);
|
||||||
|
err.code = 'EBLOCKED';
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
return allowed.address;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { resolveAllowed };
|
||||||
+319
@@ -0,0 +1,319 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SOCKS5 代理服务(RFC 1928 + RFC 1929 用户名密码认证)。
|
||||||
|
* 仅实现 CONNECT 命令;UDP ASSOCIATE / BIND 会返回“命令不支持”。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const net = require('node:net');
|
||||||
|
const { once } = require('node:events');
|
||||||
|
const { checkCredentials } = require('./auth');
|
||||||
|
const { resolveAllowed } = require('./resolver');
|
||||||
|
const { bridge } = require('./util');
|
||||||
|
|
||||||
|
const SOCKS_VERSION = 0x05;
|
||||||
|
const AUTH_VERSION = 0x01;
|
||||||
|
const CMD_CONNECT = 0x01;
|
||||||
|
|
||||||
|
const ATYP_IPV4 = 0x01;
|
||||||
|
const ATYP_DOMAIN = 0x03;
|
||||||
|
const ATYP_IPV6 = 0x04;
|
||||||
|
|
||||||
|
/** 应答码 */
|
||||||
|
const REP = {
|
||||||
|
SUCCEEDED: 0x00,
|
||||||
|
GENERAL_FAILURE: 0x01,
|
||||||
|
NOT_ALLOWED: 0x02,
|
||||||
|
NETWORK_UNREACHABLE: 0x03,
|
||||||
|
HOST_UNREACHABLE: 0x04,
|
||||||
|
CONNECTION_REFUSED: 0x05,
|
||||||
|
TTL_EXPIRED: 0x06,
|
||||||
|
CMD_NOT_SUPPORTED: 0x07,
|
||||||
|
ATYP_NOT_SUPPORTED: 0x08,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 带缓冲的 socket 读取器:让握手流程可以顺序 await 读取指定字节数。
|
||||||
|
*/
|
||||||
|
class SocketReader {
|
||||||
|
/**
|
||||||
|
* @param {import('node:net').Socket} socket 客户端 socket
|
||||||
|
*/
|
||||||
|
constructor(socket) {
|
||||||
|
this.socket = socket;
|
||||||
|
this.buffer = Buffer.alloc(0);
|
||||||
|
/** @type {{size: number, resolve: (data: Buffer|null) => void}[]} */
|
||||||
|
this.waiters = [];
|
||||||
|
this.closed = false;
|
||||||
|
this.onData = (chunk) => {
|
||||||
|
this.buffer = this.buffer.length ? Buffer.concat([this.buffer, chunk]) : chunk;
|
||||||
|
this.flush();
|
||||||
|
};
|
||||||
|
this.onClose = () => {
|
||||||
|
this.closed = true;
|
||||||
|
this.flush();
|
||||||
|
};
|
||||||
|
socket.on('data', this.onData);
|
||||||
|
socket.once('close', this.onClose);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 尽量满足等待中的读取请求 */
|
||||||
|
flush() {
|
||||||
|
while (this.waiters.length > 0) {
|
||||||
|
const waiter = this.waiters[0];
|
||||||
|
if (this.buffer.length >= waiter.size) {
|
||||||
|
this.waiters.shift();
|
||||||
|
const data = this.buffer.subarray(0, waiter.size);
|
||||||
|
this.buffer = this.buffer.subarray(waiter.size);
|
||||||
|
waiter.resolve(Buffer.from(data));
|
||||||
|
} else if (this.closed) {
|
||||||
|
this.waiters.shift();
|
||||||
|
waiter.resolve(null);
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读取指定字节数。
|
||||||
|
* @param {number} size 字节数
|
||||||
|
* @returns {Promise<Buffer|null>} 连接提前关闭时返回 null
|
||||||
|
*/
|
||||||
|
read(size) {
|
||||||
|
if (size <= 0) return Promise.resolve(Buffer.alloc(0));
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
this.waiters.push({ size, resolve });
|
||||||
|
this.flush();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解除监听,并返回尚未消费的剩余数据(可能已包含下一个请求)。
|
||||||
|
* @returns {Buffer} 剩余数据
|
||||||
|
*/
|
||||||
|
detach() {
|
||||||
|
this.socket.removeListener('data', this.onData);
|
||||||
|
this.socket.removeListener('close', this.onClose);
|
||||||
|
const leftover = this.buffer;
|
||||||
|
this.buffer = Buffer.alloc(0);
|
||||||
|
for (const waiter of this.waiters) waiter.resolve(null);
|
||||||
|
this.waiters = [];
|
||||||
|
return leftover;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送 SOCKS5 应答(BND.ADDR 固定填 0.0.0.0:0)。
|
||||||
|
* @param {import('node:net').Socket} socket 客户端 socket
|
||||||
|
* @param {number} rep 应答码
|
||||||
|
*/
|
||||||
|
function sendReply(socket, rep) {
|
||||||
|
if (socket.destroyed) return;
|
||||||
|
socket.write(Buffer.from([SOCKS_VERSION, rep, 0x00, ATYP_IPV4, 0, 0, 0, 0, 0, 0]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把 16 字节 IPv6 转成标准字符串。
|
||||||
|
* @param {Buffer} buffer 16 字节地址
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
function formatIPv6(buffer) {
|
||||||
|
const groups = [];
|
||||||
|
for (let i = 0; i < 16; i += 2) groups.push(buffer.readUInt16BE(i).toString(16));
|
||||||
|
return groups.join(':');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 连接错误映射为 SOCKS5 应答码。
|
||||||
|
* @param {NodeJS.ErrnoException} err 错误
|
||||||
|
* @returns {number}
|
||||||
|
*/
|
||||||
|
function mapConnectError(err) {
|
||||||
|
switch (err && err.code) {
|
||||||
|
case 'ECONNREFUSED':
|
||||||
|
return REP.CONNECTION_REFUSED;
|
||||||
|
case 'ENETUNREACH':
|
||||||
|
return REP.NETWORK_UNREACHABLE;
|
||||||
|
case 'EHOSTUNREACH':
|
||||||
|
case 'ETIMEDOUT':
|
||||||
|
return REP.HOST_UNREACHABLE;
|
||||||
|
default:
|
||||||
|
return REP.GENERAL_FAILURE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理单个 SOCKS5 连接。
|
||||||
|
* @param {object} ctx 上下文
|
||||||
|
* @param {import('node:net').Socket} socket 客户端 socket
|
||||||
|
* @param {string} remote 客户端地址(用于日志)
|
||||||
|
*/
|
||||||
|
async function handleConnection(ctx, socket, remote) {
|
||||||
|
const settings = ctx.getSettings();
|
||||||
|
const auth = settings.socks5;
|
||||||
|
const reader = new SocketReader(socket);
|
||||||
|
let statsOpen = false;
|
||||||
|
|
||||||
|
socket.setNoDelay(true);
|
||||||
|
socket.on('error', () => socket.destroy());
|
||||||
|
|
||||||
|
try {
|
||||||
|
// ---------- 1. 版本与方法协商 ----------
|
||||||
|
const greeting = await reader.read(2);
|
||||||
|
if (!greeting) return;
|
||||||
|
if (greeting[0] !== SOCKS_VERSION) {
|
||||||
|
ctx.logger.debug(`[SOCKS5] 非法版本 ${greeting[0]},来自 ${remote}`);
|
||||||
|
socket.destroy();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const methodCount = greeting[1];
|
||||||
|
if (methodCount === 0) {
|
||||||
|
socket.end(Buffer.from([SOCKS_VERSION, 0xff]));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const methods = await reader.read(methodCount);
|
||||||
|
if (!methods) return;
|
||||||
|
|
||||||
|
const needAuth = Boolean(auth.username);
|
||||||
|
if (needAuth) {
|
||||||
|
if (!methods.includes(0x02)) {
|
||||||
|
socket.end(Buffer.from([SOCKS_VERSION, 0xff]));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
socket.write(Buffer.from([SOCKS_VERSION, 0x02]));
|
||||||
|
|
||||||
|
// ---------- 2. 用户名密码认证 ----------
|
||||||
|
const versionByte = await reader.read(2);
|
||||||
|
if (!versionByte) return;
|
||||||
|
if (versionByte[0] !== AUTH_VERSION) {
|
||||||
|
socket.destroy();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const userNameLength = versionByte[1];
|
||||||
|
const userNameBuf = userNameLength ? await reader.read(userNameLength) : Buffer.alloc(0);
|
||||||
|
if (userNameBuf === null) return;
|
||||||
|
const passLengthBuf = await reader.read(1);
|
||||||
|
if (!passLengthBuf) return;
|
||||||
|
const passLength = passLengthBuf[0];
|
||||||
|
const passwordBuf = passLength ? await reader.read(passLength) : Buffer.alloc(0);
|
||||||
|
if (passwordBuf === null) return;
|
||||||
|
|
||||||
|
const ok = checkCredentials(auth, userNameBuf.toString('utf8'), passwordBuf.toString('utf8'));
|
||||||
|
socket.write(Buffer.from([AUTH_VERSION, ok ? 0x00 : 0x01]));
|
||||||
|
if (!ok) {
|
||||||
|
ctx.logger.warn(`[SOCKS5] 认证失败,来自 ${remote}`);
|
||||||
|
socket.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (!methods.includes(0x00)) {
|
||||||
|
socket.end(Buffer.from([SOCKS_VERSION, 0xff]));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
socket.write(Buffer.from([SOCKS_VERSION, 0x00]));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 3. 请求解析 ----------
|
||||||
|
const requestHead = await reader.read(4);
|
||||||
|
if (!requestHead) return;
|
||||||
|
if (requestHead[0] !== SOCKS_VERSION) {
|
||||||
|
socket.destroy();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const command = requestHead[1];
|
||||||
|
const addressType = requestHead[3];
|
||||||
|
|
||||||
|
if (command !== CMD_CONNECT) {
|
||||||
|
ctx.logger.debug(`[SOCKS5] 不支持的命令 ${command},来自 ${remote}`);
|
||||||
|
sendReply(socket, REP.CMD_NOT_SUPPORTED);
|
||||||
|
socket.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let host = '';
|
||||||
|
if (addressType === ATYP_IPV4) {
|
||||||
|
const buffer = await reader.read(4);
|
||||||
|
if (!buffer) return;
|
||||||
|
host = Array.from(buffer).join('.');
|
||||||
|
} else if (addressType === ATYP_IPV6) {
|
||||||
|
const buffer = await reader.read(16);
|
||||||
|
if (!buffer) return;
|
||||||
|
host = formatIPv6(buffer);
|
||||||
|
} else if (addressType === ATYP_DOMAIN) {
|
||||||
|
const lengthBuf = await reader.read(1);
|
||||||
|
if (!lengthBuf) return;
|
||||||
|
const nameBuf = await reader.read(lengthBuf[0]);
|
||||||
|
if (!nameBuf) return;
|
||||||
|
host = nameBuf.toString('utf8');
|
||||||
|
} else {
|
||||||
|
sendReply(socket, REP.ATYP_NOT_SUPPORTED);
|
||||||
|
socket.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const portBuf = await reader.read(2);
|
||||||
|
if (!portBuf) return;
|
||||||
|
const port = portBuf.readUInt16BE(0);
|
||||||
|
|
||||||
|
// ---------- 4. 白名单校验 ----------
|
||||||
|
let address;
|
||||||
|
try {
|
||||||
|
address = await resolveAllowed(host, settings.filter);
|
||||||
|
} catch (err) {
|
||||||
|
ctx.logger.warn(`[SOCKS5] 拒绝 ${host}:${port} - ${err.message}`);
|
||||||
|
sendReply(socket, err.code === 'EBLOCKED' ? REP.NOT_ALLOWED : REP.HOST_UNREACHABLE);
|
||||||
|
socket.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 5. 建立连接并转发 ----------
|
||||||
|
// 先把已缓冲的后续数据取出来,避免握手期间的数据丢失
|
||||||
|
const leftover = reader.detach();
|
||||||
|
|
||||||
|
const upstream = net.connect({ host: address, port });
|
||||||
|
upstream.setNoDelay(true);
|
||||||
|
try {
|
||||||
|
await once(upstream, 'connect');
|
||||||
|
} catch (err) {
|
||||||
|
ctx.logger.debug(`[SOCKS5] 连接失败 ${host}:${port} - ${err.message}`);
|
||||||
|
sendReply(socket, mapConnectError(err));
|
||||||
|
socket.end();
|
||||||
|
upstream.destroy();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sendReply(socket, REP.SUCCEEDED);
|
||||||
|
if (leftover.length > 0) upstream.write(leftover);
|
||||||
|
|
||||||
|
ctx.stats.open('socks5');
|
||||||
|
statsOpen = true;
|
||||||
|
ctx.logger.info(`[SOCKS5] ${remote} → ${host}:${port} (${address})`);
|
||||||
|
|
||||||
|
bridge(socket, upstream, {
|
||||||
|
onUp: (bytes) => ctx.stats.addUp('socks5', bytes),
|
||||||
|
onDown: (bytes) => ctx.stats.addDown('socks5', bytes),
|
||||||
|
onClose: () => ctx.stats.close('socks5'),
|
||||||
|
});
|
||||||
|
statsOpen = false; // 交给 bridge 的 onClose 处理
|
||||||
|
} catch (err) {
|
||||||
|
ctx.logger.debug(`[SOCKS5] 连接处理异常 ${remote} - ${err.message}`);
|
||||||
|
socket.destroy();
|
||||||
|
} finally {
|
||||||
|
if (statsOpen) ctx.stats.close('socks5');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建 SOCKS5 服务器(尚未 listen)。
|
||||||
|
* @param {object} ctx 上下文:{ getSettings, logger, stats }
|
||||||
|
* @returns {import('node:net').Server}
|
||||||
|
*/
|
||||||
|
function createSocks5Server(ctx) {
|
||||||
|
return net.createServer((socket) => {
|
||||||
|
const remote = `${socket.remoteAddress || '未知'}:${socket.remotePort || 0}`;
|
||||||
|
void handleConnection(ctx, socket, remote);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createSocks5Server };
|
||||||
+174
@@ -0,0 +1,174 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 连接数、累计流量与实时带宽统计。
|
||||||
|
* 带宽通过定时采样累计字节数的差值计算,并保留最近 60 个采样点用于绘制趋势。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const PROTOCOLS = ['http', 'socks5'];
|
||||||
|
const DEFAULT_SAMPLE_INTERVAL = 1000;
|
||||||
|
const DEFAULT_HISTORY_LIMIT = 60;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成一份空的统计单元。
|
||||||
|
* @returns {{active: number, total: number, bytesUp: number, bytesDown: number}}
|
||||||
|
*/
|
||||||
|
function emptyBucket() {
|
||||||
|
return { active: 0, total: 0, bytesUp: 0, bytesDown: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成一份空的速率单元。
|
||||||
|
* @returns {{up: number, down: number}}
|
||||||
|
*/
|
||||||
|
function emptyRate() {
|
||||||
|
return { up: 0, down: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
class TrafficStats {
|
||||||
|
/**
|
||||||
|
* @param {{sampleInterval?: number, historyLimit?: number}} [options] 采样参数
|
||||||
|
*/
|
||||||
|
constructor(options = {}) {
|
||||||
|
this.sampleInterval = options.sampleInterval || DEFAULT_SAMPLE_INTERVAL;
|
||||||
|
this.historyLimit = options.historyLimit || DEFAULT_HISTORY_LIMIT;
|
||||||
|
/** @type {NodeJS.Timeout|null} */
|
||||||
|
this.timer = null;
|
||||||
|
this.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 清空所有累计值与采样数据 */
|
||||||
|
reset() {
|
||||||
|
this.data = {};
|
||||||
|
for (const protocol of PROTOCOLS) this.data[protocol] = emptyBucket();
|
||||||
|
|
||||||
|
/** @type {Record<string, {up: number, down: number}>} */
|
||||||
|
this.rates = { http: emptyRate(), socks5: emptyRate(), total: emptyRate() };
|
||||||
|
this.peak = emptyRate();
|
||||||
|
/** @type {{at: number, up: number, down: number}[]} */
|
||||||
|
this.history = [];
|
||||||
|
this.lastSample = {
|
||||||
|
at: Date.now(),
|
||||||
|
http: { bytesUp: 0, bytesDown: 0 },
|
||||||
|
socks5: { bytesUp: 0, bytesDown: 0 },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 启动定时采样(不会阻塞进程退出) */
|
||||||
|
start() {
|
||||||
|
if (this.timer) return;
|
||||||
|
this.timer = setInterval(() => this.sample(), this.sampleInterval);
|
||||||
|
if (typeof this.timer.unref === 'function') this.timer.unref();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 停止定时采样 */
|
||||||
|
stop() {
|
||||||
|
if (!this.timer) return;
|
||||||
|
clearInterval(this.timer);
|
||||||
|
this.timer = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 采样一次,计算各协议当前的上下行速率。
|
||||||
|
* @returns {{up: number, down: number}} 合计速率
|
||||||
|
*/
|
||||||
|
sample() {
|
||||||
|
const now = Date.now();
|
||||||
|
const elapsed = Math.max(0.001, (now - this.lastSample.at) / 1000);
|
||||||
|
|
||||||
|
let totalUp = 0;
|
||||||
|
let totalDown = 0;
|
||||||
|
|
||||||
|
for (const protocol of PROTOCOLS) {
|
||||||
|
const bucket = this.data[protocol];
|
||||||
|
const last = this.lastSample[protocol];
|
||||||
|
const up = Math.max(0, (bucket.bytesUp - last.bytesUp) / elapsed);
|
||||||
|
const down = Math.max(0, (bucket.bytesDown - last.bytesDown) / elapsed);
|
||||||
|
|
||||||
|
this.rates[protocol] = { up: Math.round(up), down: Math.round(down) };
|
||||||
|
this.lastSample[protocol] = { bytesUp: bucket.bytesUp, bytesDown: bucket.bytesDown };
|
||||||
|
|
||||||
|
totalUp += up;
|
||||||
|
totalDown += down;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.rates.total = { up: Math.round(totalUp), down: Math.round(totalDown) };
|
||||||
|
this.peak.up = Math.max(this.peak.up, this.rates.total.up);
|
||||||
|
this.peak.down = Math.max(this.peak.down, this.rates.total.down);
|
||||||
|
|
||||||
|
this.history.push({ at: now, up: this.rates.total.up, down: this.rates.total.down });
|
||||||
|
while (this.history.length > this.historyLimit) this.history.shift();
|
||||||
|
|
||||||
|
this.lastSample.at = now;
|
||||||
|
return this.rates.total;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 新建一条连接。
|
||||||
|
* @param {'http'|'socks5'} protocol 协议
|
||||||
|
*/
|
||||||
|
open(protocol) {
|
||||||
|
const bucket = this.data[protocol];
|
||||||
|
if (!bucket) return;
|
||||||
|
bucket.active += 1;
|
||||||
|
bucket.total += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 连接结束。
|
||||||
|
* @param {'http'|'socks5'} protocol 协议
|
||||||
|
*/
|
||||||
|
close(protocol) {
|
||||||
|
const bucket = this.data[protocol];
|
||||||
|
if (!bucket) return;
|
||||||
|
bucket.active = Math.max(0, bucket.active - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 记录上行字节数(客户端 → 目标)。
|
||||||
|
* @param {'http'|'socks5'} protocol 协议
|
||||||
|
* @param {number} bytes 字节数
|
||||||
|
*/
|
||||||
|
addUp(protocol, bytes) {
|
||||||
|
const bucket = this.data[protocol];
|
||||||
|
if (bucket) bucket.bytesUp += bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 记录下行字节数(目标 → 客户端)。
|
||||||
|
* @param {'http'|'socks5'} protocol 协议
|
||||||
|
* @param {number} bytes 字节数
|
||||||
|
*/
|
||||||
|
addDown(protocol, bytes) {
|
||||||
|
const bucket = this.data[protocol];
|
||||||
|
if (bucket) bucket.bytesDown += bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 导出统计快照(累计值 + 实时速率 + 趋势 + 峰值)。
|
||||||
|
* @returns {Record<string, any>}
|
||||||
|
*/
|
||||||
|
snapshot() {
|
||||||
|
const result = {};
|
||||||
|
const total = emptyBucket();
|
||||||
|
for (const protocol of PROTOCOLS) {
|
||||||
|
const bucket = this.data[protocol];
|
||||||
|
result[protocol] = { ...bucket };
|
||||||
|
total.active += bucket.active;
|
||||||
|
total.total += bucket.total;
|
||||||
|
total.bytesUp += bucket.bytesUp;
|
||||||
|
total.bytesDown += bucket.bytesDown;
|
||||||
|
}
|
||||||
|
result.total = total;
|
||||||
|
result.rates = {
|
||||||
|
http: { ...this.rates.http },
|
||||||
|
socks5: { ...this.rates.socks5 },
|
||||||
|
total: { ...this.rates.total },
|
||||||
|
};
|
||||||
|
result.peak = { ...this.peak };
|
||||||
|
result.history = this.history.slice();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { TrafficStats };
|
||||||
+153
@@ -0,0 +1,153 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通用工具:TCP 监听封装、双向管道桥接。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const net = require('node:net');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 以 Promise 形式监听端口。
|
||||||
|
* @param {import('node:net').Server} server 服务器实例
|
||||||
|
* @param {number} port 端口(0 表示随机)
|
||||||
|
* @param {string} host 监听地址
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
function listen(server, port, host) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const onError = (err) => {
|
||||||
|
server.removeListener('listening', onListening);
|
||||||
|
reject(err);
|
||||||
|
};
|
||||||
|
const onListening = () => {
|
||||||
|
server.removeListener('error', onError);
|
||||||
|
resolve();
|
||||||
|
};
|
||||||
|
server.once('error', onError);
|
||||||
|
server.once('listening', onListening);
|
||||||
|
server.listen(port, host);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在两端 socket 之间建立双向隧道,并在任一端出错/断开时一并销毁。
|
||||||
|
* @param {import('node:net').Socket} client 客户端一侧
|
||||||
|
* @param {import('node:net').Socket} upstream 目标一侧
|
||||||
|
* @param {{onUp?: (bytes: number) => void, onDown?: (bytes: number) => void, onClose?: () => void}} [hooks] 统计回调
|
||||||
|
* @returns {{destroy: () => void}}
|
||||||
|
*/
|
||||||
|
function bridge(client, upstream, hooks = {}) {
|
||||||
|
let closed = false;
|
||||||
|
|
||||||
|
const destroyAll = () => {
|
||||||
|
if (!client.destroyed) client.destroy();
|
||||||
|
if (!upstream.destroyed) upstream.destroy();
|
||||||
|
};
|
||||||
|
|
||||||
|
const finish = () => {
|
||||||
|
if (closed) return;
|
||||||
|
closed = true;
|
||||||
|
if (typeof hooks.onClose === 'function') hooks.onClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
// 任一方向收到数据时统计流量(与 pipe 并行,不会影响数据流)
|
||||||
|
if (typeof hooks.onUp === 'function') {
|
||||||
|
client.on('data', (chunk) => hooks.onUp(chunk.length));
|
||||||
|
}
|
||||||
|
if (typeof hooks.onDown === 'function') {
|
||||||
|
upstream.on('data', (chunk) => hooks.onDown(chunk.length));
|
||||||
|
}
|
||||||
|
|
||||||
|
client.on('error', destroyAll);
|
||||||
|
upstream.on('error', destroyAll);
|
||||||
|
client.on('close', () => {
|
||||||
|
finish();
|
||||||
|
if (!upstream.destroyed) upstream.destroy();
|
||||||
|
});
|
||||||
|
upstream.on('close', () => {
|
||||||
|
finish();
|
||||||
|
if (!client.destroyed) client.destroy();
|
||||||
|
});
|
||||||
|
|
||||||
|
client.pipe(upstream);
|
||||||
|
upstream.pipe(client);
|
||||||
|
|
||||||
|
return { destroy: destroyAll };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断 socket 是否已关闭,各 Node 版本兼容写法。
|
||||||
|
* @param {import('node:net').Socket} socket socket
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
function isClosed(socket) {
|
||||||
|
return socket.destroyed || socket.readyState === 'closed';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把 host:port 字符串拆开,兼容 IPv6 的方括号写法。
|
||||||
|
* @param {string} value 例如 "example.com:443"、"[::1]:8080"
|
||||||
|
* @param {number} defaultPort 缺省端口
|
||||||
|
* @returns {{host: string, port: number}}
|
||||||
|
* @throws {Error} 格式非法时抛出
|
||||||
|
*/
|
||||||
|
function splitHostPort(value, defaultPort) {
|
||||||
|
const text = String(value || '').trim();
|
||||||
|
if (!text) throw new Error('目标地址为空');
|
||||||
|
|
||||||
|
if (text.startsWith('[')) {
|
||||||
|
const end = text.indexOf(']');
|
||||||
|
if (end === -1) throw new Error(`目标地址格式错误:${text}`);
|
||||||
|
const host = text.slice(1, end);
|
||||||
|
const rest = text.slice(end + 1);
|
||||||
|
let port = defaultPort;
|
||||||
|
if (rest) {
|
||||||
|
if (!rest.startsWith(':')) throw new Error(`目标地址格式错误:${text}`);
|
||||||
|
port = Number(rest.slice(1));
|
||||||
|
}
|
||||||
|
if (!isValidPort(port)) throw new Error(`目标端口不合法:${text}`);
|
||||||
|
return { host, port };
|
||||||
|
}
|
||||||
|
|
||||||
|
const first = text.indexOf(':');
|
||||||
|
if (first === -1) return { host: text, port: defaultPort };
|
||||||
|
if (first !== text.lastIndexOf(':')) {
|
||||||
|
// 多个冒号但没加方括号,视为纯 IPv6 地址
|
||||||
|
return { host: text, port: defaultPort };
|
||||||
|
}
|
||||||
|
|
||||||
|
const host = text.slice(0, first);
|
||||||
|
const port = Number(text.slice(first + 1));
|
||||||
|
if (!host) throw new Error(`目标地址格式错误:${text}`);
|
||||||
|
if (!isValidPort(port)) throw new Error(`目标端口不合法:${text}`);
|
||||||
|
return { host, port };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验端口号。
|
||||||
|
* @param {number} port 端口
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
function isValidPort(port) {
|
||||||
|
return Number.isInteger(port) && port > 0 && port <= 65535;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 去掉 IPv6 地址两侧的方括号。
|
||||||
|
* @param {string} host 主机名
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
function stripBrackets(host) {
|
||||||
|
const text = String(host || '');
|
||||||
|
return text.startsWith('[') && text.endsWith(']') ? text.slice(1, -1) : text;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
listen,
|
||||||
|
bridge,
|
||||||
|
isClosed,
|
||||||
|
splitHostPort,
|
||||||
|
isValidPort,
|
||||||
|
stripBrackets,
|
||||||
|
net,
|
||||||
|
};
|
||||||
@@ -0,0 +1,474 @@
|
|||||||
|
'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();
|
||||||
|
}
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user