* 新增 cache.js 实现地区解析结果的缓存功能 * 引入 WeakMap 优化 regionResolver 内存管理 * 扩展地区代码集以支持 UK 等特殊地区标识 * 重构别名解析逻辑,提高代码复用性与性能
228 lines
11 KiB
JavaScript
228 lines
11 KiB
JavaScript
// 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 (/<!doctype\s+html|<html\b|blocked by waf/i.test(body.slice(0, 2048))) {
|
||
throw new Error('Subscription: upstream returned an error page');
|
||
}
|
||
let result;
|
||
try { result = ProxyUtils.parse(body); }
|
||
catch { throw new Error('Subscription: subscription parsing failed'); }
|
||
if (!Array.isArray(result) || result.length === 0 || result.some(p => !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;
|
||
}
|
||
}
|