refactor(core): ♻️ 优化配置管理与正则匹配逻辑
针对 telegram 机器人和脚本逻辑进行了重构: - 在 tg-bot.js 中新增 deleteCfg 函数,用于物理删除数据库配置并同步清除内存缓存,防止旧值误读。 - 在 sntp-rename.js 中提取了 normalizeKey 和 escapeRegex 工具函数,并改用数组展开运算符进行排序,提升了代码的健壮性和可读性。
This commit is contained in:
@@ -26,28 +26,30 @@ function operator(proxies) {
|
||||
// 目的:无论节点名叫 "gtm 0.5x" 还是 "GTM0.5X",都能稳定映射
|
||||
const normalizedMap = {};
|
||||
const originalKeys = Object.keys(featureMap);
|
||||
const normalizeKey = key => key.toUpperCase().replace(/\s+/g, '');
|
||||
const escapeRegex = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
for (const key of originalKeys) {
|
||||
const safeKey = key.toUpperCase().replace(/\s+/g, '');
|
||||
normalizedMap[safeKey] = featureMap[key];
|
||||
normalizedMap[normalizeKey(key)] = featureMap[key];
|
||||
}
|
||||
|
||||
// 2. 动态构建复合正则表达式 (核心引擎)
|
||||
// 按字符串长度降序排序,彻底解决 "短路匹配" (Short-Circuit) 问题
|
||||
const sortedKeys = originalKeys.sort((a, b) => b.length - a.length);
|
||||
const sortedKeys = [...originalKeys].sort((a, b) => b.length - a.length);
|
||||
|
||||
const regexParts = sortedKeys.map(key => {
|
||||
// 自动转义正则特殊字符 (防注入报错)
|
||||
const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const escapedKey = key.trim().split(/\s+/).filter(Boolean).map(escapeRegex).join('\\s*');
|
||||
|
||||
// 智能边界处理:如果关键词仅由字母和数字组成 (如 S1, BGP),追加 \b 边界
|
||||
// 智能边界处理:如果关键词首尾都是字母或数字,就追加 \b 边界
|
||||
// 这样能防止配置的 "S1" 错误匹配到 "US1" 或 "TLS1.3"
|
||||
if (/^[A-Za-z0-9]+$/.test(key)) {
|
||||
const trimmedKey = key.trim();
|
||||
if (/^[A-Za-z0-9]/.test(trimmedKey) && /[A-Za-z0-9]$/.test(trimmedKey)) {
|
||||
return `\\b${escapedKey}\\b`;
|
||||
}
|
||||
return escapedKey;
|
||||
});
|
||||
|
||||
// 动态拼接出类似: /(GTM\ 0\.5x|\bAnytls\b|\bBGP\b|...)/i
|
||||
// 动态拼接出类似: /(GTM\s*0\.5x|\bAnytls\b|\bBGP\b|...)/i
|
||||
const featureRegex = new RegExp(`(${regexParts.join('|')})`, 'i');
|
||||
|
||||
// 缓存后缀匹配正则,避免循环内重复创建
|
||||
@@ -63,7 +65,7 @@ function operator(proxies) {
|
||||
if (!match) return p; // 未命中配置库,直接放行
|
||||
|
||||
// B. 清洗提取到的特征词,并去 O(1) 字典中取值
|
||||
const mapKey = match[1].toUpperCase().replace(/\s+/g, '');
|
||||
const mapKey = normalizeKey(match[1]);
|
||||
const injectPayload = normalizedMap[mapKey];
|
||||
|
||||
if (!injectPayload) return p; // 兜底安全校验
|
||||
|
||||
Reference in New Issue
Block a user