From f14e4e3a4771b3fb0a622c1401ed22d41647cd72 Mon Sep 17 00:00:00 2001 From: Orion Date: Wed, 4 Nov 2026 17:34:10 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(core):=20=E5=BC=95=E5=85=A5?= =?UTF-8?q?=E5=9C=B0=E5=8C=BA=E8=A7=A3=E6=9E=90=E7=BC=93=E5=AD=98=E6=9C=BA?= =?UTF-8?q?=E5=88=B6=E5=B9=B6=E4=BC=98=E5=8C=96=E5=91=BD=E5=90=8D=E9=80=BB?= =?UTF-8?q?=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 新增 cache.js 实现地区解析结果的缓存功能 * 引入 WeakMap 优化 regionResolver 内存管理 * 扩展地区代码集以支持 UK 等特殊地区标识 * 重构别名解析逻辑,提高代码复用性与性能 --- substore/cache.js | 227 +++++++++++++++++++++++++++++++++++++++++++++ substore/rename.js | 173 +++++++++++++++++----------------- 2 files changed, 313 insertions(+), 87 deletions(-) create mode 100644 substore/cache.js diff --git a/substore/cache.js b/substore/cache.js new file mode 100644 index 0000000..3c0bf00 --- /dev/null +++ b/substore/cache.js @@ -0,0 +1,227 @@ +// Fetch inside Sub-Store; preserve following operators and cache only validated nodes. +// Parameters: url (required), ua (optional), strict=1 for fresh validation, +// cacheTtlSeconds=300, cacheFallback=1 to allow the last verified snapshot on failure. +// fetchProfile: generic (default), flowercloud, yinyun, amy, or ytoo. +// flowercloud/ytoo also include their previously adjacent repair/filter operators. +// useProxyEnv=1 preserves environment proxy handling; omitted keeps direct requests. +async function operator(proxies = [], targetPlatform, context) { + const { execFile } = require('node:child_process'); + const { createHash } = require('node:crypto'); + const args = $arguments || {}; + const profile = String(args.fetchProfile || 'generic'); + const enabled = value => value === true || value === 1 || value === '1' || value === 'true'; + const strict = enabled(args.strict); + const maxBytes = 4 * 1024 * 1024; + const marker = '\nSUB_HTTP_STATUS:'; + const rawUrl = String(args.url || '').trim(); + const ua = String(args.ua || 'clash-verge/v2.5.10'); + let url; + try { url = new URL(rawUrl); } catch { throw new Error('Subscription: invalid source URL'); } + if (url.protocol !== 'https:' || url.username || url.password || /[\r\n]/.test(rawUrl + ua)) { + throw new Error('Subscription: HTTPS source without embedded login is required'); + } + const source = Object.values(context?.source || {}).find(item => item?.name); + const scope = source?.name || String(args.subscriptionName || 'subscription'); + const cachePrefix = profile === 'amy' ? '#amy-curl-verified-' + : profile === 'yinyun' ? '#subscription-curl-verified-yinyun-notice-v2-' + : '#subscription-curl-verified-'; + const cacheIdentity = profile === 'amy' ? rawUrl : scope + '\0' + rawUrl + '\0' + ua; + const key = cachePrefix + createHash('sha256').update(cacheIdentity).digest('hex'); + const ttlValue = Number(args.cacheTtlSeconds ?? 300); + const ttlMs = Number.isFinite(ttlValue) ? Math.max(0, Math.min(ttlValue, 86400)) * 1000 : 300000; + const quote = value => '"' + value.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"'; + + function parseVerified(body) { + if (typeof body !== 'string' || !body.trim() || Buffer.byteLength(body) > maxBytes) { + throw new Error('Subscription: empty or oversized response'); + } + if (/ !p || !p.type || !p.server)) { + throw new Error('Subscription: response contains no valid proxy nodes'); + } + if (profile === 'yinyun') { + // Notice-only responses are not a usable subscription and must never replace the cache. + const isNotice = proxy => /^(?:永久官网|TG频道)\s*[::]/i.test(String(proxy.name || '').trim()); + if (!result.some(proxy => !isNotice(proxy))) { + throw new Error('Subscription: upstream returned only notice nodes'); + } + } + if (profile === 'ytoo') { + const infoName = /^\s*(?:获取|到期|重置|流量)\s*[::]/; + if (!result.some(proxy => !infoName.test(String(proxy.name || '')))) { + throw new Error('Subscription: response contains only information nodes'); + } + // Preserve this provider's Clash hosts aliases on every fresh or cached parse. + const yamlProfile = ProxyUtils.yaml.parse(body); + const hosts = yamlProfile && typeof yamlProfile === 'object' && yamlProfile.dns?.['use-hosts'] !== false + ? yamlProfile.hosts : undefined; + if (hosts && typeof hosts === 'object' && !Array.isArray(hosts)) { + result = result.map(proxy => { + let server = proxy.server; + const visited = new Set(); + while (Object.prototype.hasOwnProperty.call(hosts, server)) { + if (visited.has(server)) throw new Error('Subscription: cyclic upstream hosts mapping'); + visited.add(server); + const target = hosts[server]; + if (typeof target !== 'string' || !target.trim() || /[\s/?#]/.test(target)) { + throw new Error('Subscription: unsupported upstream hosts mapping'); + } + server = target.trim(); + } + return server === proxy.server ? proxy : { ...proxy, server }; + }); + } + } + if (source) for (const proxy of result) { + proxy._subName = source.name; + proxy._subDisplayName = source.displayName; + const collection = context?.source?._collection; + if (collection) { + proxy._collectionName = collection.name; + proxy._collectionDisplayName = collection.displayName; + } + } + return result; + } + + function validFlow(value) { + if (typeof value !== 'string' || value.length > 8192 || /[\r\n]/.test(value)) return undefined; + try { + const info = flowUtils.parseFlowHeaders(value); + if (info && Number.isFinite(info.total) && Number.isFinite(info.usage?.download) + && Number.isFinite(info.usage?.upload) && (info.expires === undefined || Number.isFinite(info.expires))) return value.trim(); + } catch {} + return undefined; + } + + // Upstream gives a calendar date only. Use +08:00 midnight for display; + // a real upstream expire field always takes precedence, including expire=0. + function flowWithExpiryDate(value, nodes) { + const info = validFlow(value); + if (!info || /(?:^|;)\s*expire\s*=/i.test(info)) return info; + const dates = new Set(); + for (const node of nodes || []) { + const match = /^\s*到期时间\s*[::]\s*(\d{4})-(\d{2})-(\d{2})\s*$/.exec(String(node.name || '')); + if (match) dates.add(match.slice(1).join('-')); + } + if (dates.size !== 1) return info; + const [year, month, day] = [...dates][0].split('-').map(Number); + const utc = Date.UTC(year, month - 1, day); + const check = new Date(utc); + if (check.getUTCFullYear() !== year || check.getUTCMonth() !== month - 1 || check.getUTCDate() !== day) return info; + const expires = (utc - 8 * 3600000) / 1000; + if (!Number.isSafeInteger(expires) || expires <= 0) return info; + return info + '; expire=' + expires; + } + + function publishFlow(value, nodes) { + const info = profile === 'amy' ? flowWithExpiryDate(value, nodes) : validFlow(value); + if (!info || !source?.name) return; + const subs = $substore.read('subs'); + if (!Array.isArray(subs)) return; + const current = subs.find(item => item.name === source.name); + const sameOrigin = current?.process?.some(item => item.type === 'Script Operator' + && item.args?.arguments?.url === rawUrl + && String(item.args.arguments.ua || 'clash-verge/v2.5.10') === ua); + if (!sameOrigin) return; + const changed = current.subUserinfo !== info; + current.subUserinfo = info; + source.subUserinfo = info; + if (changed) $substore.write(subs, 'subs'); + } + + function splitResponse(response) { + let rest = response; + let headers = {}; + while (/^HTTP\/\d(?:\.\d)?\s+\d{3}(?:\s|$)/.test(rest)) { + const end = /\r?\n\r?\n/.exec(rest); + if (!end || end.index > 65536) throw new Error('Subscription: invalid response headers'); + headers = {}; + for (const line of rest.slice(0, end.index).split(/\r?\n/).slice(1)) { + const colon = line.indexOf(':'); + if (colon > 0) headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim(); + } + rest = rest.slice(end.index + end[0].length); + } + return { body: rest, flowInfo: validFlow(headers['subscription-userinfo']) }; + } + + function finish(nodes) { + if (profile === 'flowercloud') { + const sourceServer = /^(6ed68gz8-2ad3|2ad30bj6-fc51|fc513sh2-6ed6)[.]aws-agent[.]com$/; + const repaired = nodes.map(proxy => { + if (typeof proxy.server !== "string" || !sourceServer.test(proxy.server)) return proxy; + const server = String(proxy.name || "").includes("德国") + ? "bad18bj2-1f25.apt-agent.org" + : "b36d5gz0-2ac1.apt-agent.org"; + return { ...proxy, server }; + }); + const pattern = new RegExp("^\\s*(?:Traffic|Expire)\\s*[::]", "i"); + return repaired.filter(proxy => !pattern.test(String(proxy.name || ""))); + } + if (profile === 'ytoo') { + return nodes.filter(proxy => !/^\s*(?:获取|到期|重置|流量)\s*[::]/.test(String(proxy.name || ''))) + .map(proxy => ({ ...proxy, name: String(proxy.name || '').replace(/\[(\d+(?:\.\d+)?)\]\s*$/, ' $1x') })); + } + return nodes; + } + + let cached; + try { + const stored = $substore.read(key); + const value = typeof stored === 'string' ? JSON.parse(stored) : stored; + if (value && Number.isFinite(value.savedAt) && typeof value.body === 'string') { + cached = { savedAt: value.savedAt, proxies: parseVerified(value.body), flowInfo: validFlow(value.flowInfo) }; + } + } catch { cached = undefined; } + if (!strict && cached && Date.now() - cached.savedAt >= 0 && Date.now() - cached.savedAt < ttlMs) { + publishFlow(cached.flowInfo, cached.proxies); + return finish(cached.proxies); + } + + try { + const settings = 'url = ' + quote(rawUrl) + '\nuser-agent = ' + quote(ua) + '\n'; + const curlArgs = [ + '--disable', '--config', '-', '--silent', '--show-error', '--fail', '--dump-header', '-', + '--location', '--max-redirs', '3', '--proto', '=https', '--proto-redir', '=https', + ...(enabled(args.useProxyEnv) ? [] : ['--noproxy', '*']), + '--connect-timeout', '8', '--max-time', '18', + '--max-filesize', String(maxBytes), '--write-out', marker + '%{http_code}' + ]; + const output = await new Promise((resolve, reject) => { + const child = execFile('/usr/bin/curl', curlArgs, { + encoding: 'utf8', timeout: 20000, killSignal: 'SIGKILL', maxBuffer: maxBytes + 65536 + }, (error, stdout) => { + if (error) { + const safeCode = /^[A-Z_0-9]+$/.test(String(error.code)) ? String(error.code) : 'FAILED'; + reject(new Error('Subscription: curl request failed (' + safeCode + ')')); + } else resolve(stdout); + }); + child.stdin.on('error', () => {}); + child.stdin.end(settings); + }); + const split = output.lastIndexOf(marker); + if (split < 0) throw new Error('Subscription: missing HTTP status'); + const status = output.slice(split + marker.length).trim(); + if (status !== '200') throw new Error('Subscription: unexpected upstream HTTP status'); + const response = splitResponse(output.slice(0, split)); + const body = response.body; + const result = parseVerified(body); + const flowInfo = response.flowInfo || cached?.flowInfo; + $substore.write({ savedAt: Date.now(), body, flowInfo }, key); + publishFlow(flowInfo, result); + return finish(result); + } catch (error) { + if (!strict && enabled(args.cacheFallback) && cached) { + $substore.info('Subscription: upstream request failed; using the last verified subscription snapshot'); + publishFlow(cached.flowInfo, cached.proxies); + return finish(cached.proxies); + } + throw error; + } +} diff --git a/substore/rename.js b/substore/rename.js index 740d121..396b294 100644 --- a/substore/rename.js +++ b/substore/rename.js @@ -109,7 +109,10 @@ async function loadRenameUtils() { const normalizeRegionCode = regionCode => regionCode === 'GB' ? 'UK' : regionCode; -const createRegionResolver = utils => { +const regionResolverCache = new WeakMap(); +const regionCodeSet = new Set([...ISO_REGION_CODES, 'UK']); + +const createAliasRegionResolver = utils => { // 静态别名覆盖常见缩写和中英文名称;Intl 补充运行环境支持的地区名。 const aliases = []; const seenAliases = Object.create(null); @@ -145,17 +148,19 @@ const createRegionResolver = utils => { }); } - const compiledAliases = aliases.map(([alias, regionCode]) => { - const escapedAlias = utils.escapeRegex(alias); - const usesLatinBoundary = /^[A-Za-z0-9].*[A-Za-z0-9]$/.test(alias); - return { - aliasLength: alias.length, - regionCode, - regex: usesLatinBoundary - ? new RegExp(`(^|[^A-Za-z])(${escapedAlias})(?=$|[^A-Za-z])`, 'i') - : new RegExp(`(${escapedAlias})`, 'i') - }; + // 最早出现、同位置最长的别名优先;稳定排序保留同名别名的原始优先级。 + const aliasRegions = new Map(); + const latinAliases = []; + const otherAliases = []; + aliases.sort((first, second) => second[0].length - first[0].length); + aliases.forEach(([alias, regionCode]) => { + const key = alias.toLowerCase(); + if (!aliasRegions.has(key)) aliasRegions.set(key, regionCode); + const target = /^[A-Za-z0-9].*[A-Za-z0-9]$/.test(alias) ? latinAliases : otherAliases; + target.push(utils.escapeRegex(alias)); }); + const latinAliasRegex = new RegExp(`(^|[^A-Za-z])(${latinAliases.join('|')})(?=$|[^A-Za-z])`, 'i'); + const otherAliasRegex = new RegExp(`(${otherAliases.join('|')})`, 'i'); const regionCodeRegex = new RegExp( `(^|[^A-Za-z])(${[...ISO_REGION_CODES, 'UK'].join('|')})(?=$|[^A-Za-z])`, 'g' @@ -174,14 +179,16 @@ const createRegionResolver = utils => { } }; - compiledAliases.forEach(item => { - const match = cleanName.match(item.regex); - if (!match) return; - - const aliasText = match[2] || match[1] || match[0]; - const prefixLength = match[2] ? match[0].length - aliasText.length : 0; - consider(match.index + prefixLength, item.aliasLength, item.regionCode); - }); + const latinMatch = latinAliasRegex.exec(cleanName); + if (latinMatch) { + consider(latinMatch.index + latinMatch[1].length, latinMatch[2].length, + aliasRegions.get(latinMatch[2].toLowerCase())); + } + const otherMatch = otherAliasRegex.exec(cleanName); + if (otherMatch) { + consider(otherMatch.index, otherMatch[1].length, + aliasRegions.get(otherMatch[1].toLowerCase())); + } regionCodeRegex.lastIndex = 0; for (const match of cleanName.matchAll(regionCodeRegex)) { @@ -197,6 +204,21 @@ const createRegionResolver = utils => { }; }; +const createRegionResolver = utils => { + if (regionResolverCache.has(utils)) return regionResolverCache.get(utils); + let aliasResolver; + const resolve = (name, leadingFlag) => { + const cleanName = String(name || ''); + // 标准短码直接识别;首次遇到原始名称时才构建完整别名规则。 + const prefix = cleanName.match(/^([A-Z]{2}) \d{2,}(?=$|[^0-9])/); + if (prefix && regionCodeSet.has(prefix[1])) return normalizeRegionCode(prefix[1]); + if (!aliasResolver) aliasResolver = createAliasRegionResolver(utils); + return aliasResolver(cleanName, leadingFlag); + }; + regionResolverCache.set(utils, resolve); + return resolve; +}; + const multiplierOf = name => { if (/(?:实验性|實驗性|experimental)/i.test(name)) return '0.2x'; @@ -246,28 +268,23 @@ const createAirportGroupResolver = airports => { async function operator(proxies) { const utils = await loadRenameUtils(); const regionCodeOf = createRegionResolver(utils); - const airportGroupOf = createAirportGroupResolver(proxies - .filter(proxy => proxy && typeof proxy === 'object' && typeof proxy.name === 'string') - .map(proxy => splitAirportSuffix( - proxy.name, - typeof proxy._subName === 'string' ? proxy._subName : '', - utils - ).airport)); - // 记录首次出现顺序,使排序结果稳定且不依赖机场或地区名称的字典序。 - const airportOrder = Object.create(null); - const regionOrderByAirport = Object.create(null); - const normalizedItems = []; + const parsedItems = []; const passthroughItems = []; - let nextAirportOrder = 0; - + const airports = new Set(); proxies.forEach((proxy, originalIndex) => { if (!proxy || typeof proxy !== 'object' || typeof proxy.name !== 'string') { - passthroughItems.push({ originalIndex, proxy }); + passthroughItems.push({ proxy, originalIndex }); return; } - const declaredAirport = typeof proxy._subName === 'string' ? proxy._subName : ''; const { airport, coreName } = splitAirportSuffix(proxy.name, declaredAirport, utils); + airports.add(airport); + parsedItems.push({ airport, coreName, proxy, originalIndex }); + }); + const airportGroupOf = createAirportGroupResolver(airports); + // Map 按首次出现顺序遍历,分桶即可稳定分组,无需全量排序。 + const airportBuckets = new Map(); + parsedItems.forEach(({ airport, coreName, proxy, originalIndex }) => { const airportGroup = airportGroupOf(airport); const { flag: leadingFlag, text } = utils.splitLeadingFlag(coreName); const regionCode = /\bEmby\b/i.test(text) ? 'EMBY' : regionCodeOf(text, leadingFlag); @@ -276,62 +293,44 @@ async function operator(proxies) { return; } - if (airportOrder[airportGroup] === undefined) { - airportOrder[airportGroup] = nextAirportOrder++; - regionOrderByAirport[airportGroup] = Object.create(null); + let regionBuckets = airportBuckets.get(airportGroup); + if (!regionBuckets) { + regionBuckets = new Map(); + airportBuckets.set(airportGroup, regionBuckets); } - const regionOrder = regionOrderByAirport[airportGroup]; - if (regionOrder[regionCode] === undefined) { - regionOrder[regionCode] = Object.keys(regionOrder).length; + let items = regionBuckets.get(regionCode); + if (!items) { + items = []; + regionBuckets.set(regionCode, items); } - normalizedItems.push({ - airport, - airportGroup, - airportOrder: airportOrder[airportGroup], - coreName, - originalIndex, - proxy, - regionCode, - regionOrder: regionOrder[regionCode] + items.push({ airport, coreName, proxy, regionCode }); + }); + + const output = []; + airportBuckets.forEach(regionBuckets => regionBuckets.forEach(items => { + items.forEach((item, index) => { + const sequence = String(index + 1).padStart(2, '0'); + const multiplier = multiplierOf(item.coreName); + const dedicatedIp = hasDedicatedIp(item.coreName); + const residential = hasResidential(item.coreName); + const regionLabel = item.regionCode; + const flag = item.regionCode === 'EMBY' + ? '🏴‍☠️' + : utils.regionCodeToFlag(REGION_FLAG_DISPLAY_OVERRIDES[item.regionCode] || item.regionCode); + + item.proxy.name = [ + [flag, regionLabel, sequence].filter(Boolean).join(' '), + multiplier ? `[${multiplier}]` : '', + dedicatedIp ? '[DIP]' : '', + residential ? '[RESI]' : '', + item.airport ? `- ${item.airport}` : '' + ].filter(Boolean).join(' '); + output.push(item.proxy); }); - }); + })); - // 将同机场、同地区的节点集中,同时保留各组内原始顺序。 - normalizedItems.sort((firstItem, secondItem) => ( - firstItem.airportOrder - secondItem.airportOrder || - firstItem.regionOrder - secondItem.regionOrder || - firstItem.originalIndex - secondItem.originalIndex - )); - - const sequenceCountsByAirport = Object.create(null); - normalizedItems.forEach(item => { - // 序号按机场和地区分别计数,最终名称只保留规范化字段。 - const sequenceCounts = sequenceCountsByAirport[item.airportGroup] || ( - sequenceCountsByAirport[item.airportGroup] = Object.create(null) - ); - sequenceCounts[item.regionCode] = (sequenceCounts[item.regionCode] || 0) + 1; - const sequence = String(sequenceCounts[item.regionCode]).padStart(2, '0'); - const multiplier = multiplierOf(item.coreName); - const dedicatedIp = hasDedicatedIp(item.coreName); - const residential = hasResidential(item.coreName); - const regionLabel = item.regionCode; - const flag = item.regionCode === 'EMBY' - ? '🏴‍☠️' - : utils.regionCodeToFlag(REGION_FLAG_DISPLAY_OVERRIDES[item.regionCode] || item.regionCode); - - item.proxy.name = [ - [flag, regionLabel, sequence].filter(Boolean).join(' '), - multiplier ? `[${multiplier}]` : '', - dedicatedIp ? '[DIP]' : '', - residential ? '[RESI]' : '', - item.airport ? `- ${item.airport}` : '' - ].filter(Boolean).join(' '); - }); - - // 不可识别或无效节点不改名,按原始顺序追加在末尾。 + // 无效节点与未知地区节点来自不同遍历,按输入顺序合并追加。 passthroughItems.sort((firstItem, secondItem) => firstItem.originalIndex - secondItem.originalIndex); - return [ - ...normalizedItems.map(item => item.proxy), - ...passthroughItems.map(item => item.proxy) - ]; + for (const item of passthroughItems) output.push(item.proxy); + return output; }