Files

597 lines
20 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 配置页面脚本:拉取状态 / 读写配置 / 展示日志。
* 无框架依赖,直接使用原生 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, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
/** 保存配置 */
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);
})();