'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, };