/** * Sub-Store 节点 [Host] 替换脚本 * 功能:优先从 context.raw 读取 Surge 原文解析 [Host] 段并替换剩余节点的 p.server(无 context.raw 时回退 URL 拉取);节点为空或拉取异常时回退本地缓存 * 作者:https://github.com/Rabbit-Spec * 版本:0.0.5 */ const TLS_PROTOCOLS = new Set(["trojan", "anytls", "hysteria", "hysteria2", "tuic", "juicity"]); const IGNORED_HOST_KEYS = new Set(["localhost", "*.local"]); const IGNORED_HOST_VALUES = new Set(["0.0.0.0", "::", "127.0.0.1", "::1", "localhost"]); async function operator(proxies = [], targetPlatform, context) { const $ = $substore; const sources = []; for (const [key, value] of Object.entries(context?.source || {})) { if (!key.startsWith("_") && value && typeof value === "object" && (value.url || value.content || value.source)) { sources.push({ key, meta: value }); } } if (sources.length === 0) { return Array.isArray(proxies) ? proxies : []; } const hasProxies = Array.isArray(proxies) && proxies.length > 0; // 单订阅模式:直接作用于剩余全部节点,或为空时回退缓存节点 if (sources.length === 1) { const { key, meta } = sources[0]; const proxiesCacheKey = `substore_host_sync_proxies_${key}`; if (!hasProxies) { const cached = readCache(proxiesCacheKey, $); if (Array.isArray(cached?.proxies) && cached.proxies.length > 0) { const ts = cached.updatedAt ? new Date(cached.updatedAt).toISOString() : "unknown"; console.log(`[HostSync][${key}] 当前节点为空,回退上次缓存节点(${cached.proxies.length} 个, ${ts})`); return cached.proxies; } console.log(`[HostSync][${key}] 当前节点为空,无可用节点缓存`); return []; } const hostMap = await resolveHostMap($, key, meta, context, true); if (!hasRules(hostMap)) { if (hostMap !== null && !readCache(proxiesCacheKey, $)) { writeCache(proxiesCacheKey, { updatedAt: Date.now(), proxies }, $); } return proxies; } let replaced = 0; const result = proxies.map((p) => { if (applyHostMapping(p, hostMap)) replaced++; return p; }); writeCache(proxiesCacheKey, { updatedAt: Date.now(), proxies: result }, $); console.log(`[HostSync][${key}] 共 ${proxies.length} 个节点,替换 ${replaced} 个 (来源: ${hostMap.origin})`); return result; } // 组合订阅模式:仅处理筛选后仍有节点的子订阅,按 p.subName 隔离替换,或为空时回退缓存节点 const colName = context?.source?._collection?.name || sources.map((s) => s.key).sort().join(","); const proxiesCacheKey = `substore_host_sync_proxies_col_${colName}`; if (!hasProxies) { const cached = readCache(proxiesCacheKey, $); if (Array.isArray(cached?.proxies) && cached.proxies.length > 0) { const ts = cached.updatedAt ? new Date(cached.updatedAt).toISOString() : "unknown"; console.log(`[HostSync][Collection] 当前节点为空,回退上次缓存节点(${cached.proxies.length} 个, ${ts})`); return cached.proxies; } console.log("[HostSync][Collection] 当前节点为空,无可用节点缓存"); return []; } const activeSubs = new Set(proxies.map((p) => p?.subName).filter(Boolean)); const activeSources = sources.filter((s) => activeSubs.has(s.key)); if (activeSources.length === 0) { return proxies; } const mapBySub = new Map(); await Promise.all( activeSources.map(async ({ key, meta }) => { const hostMap = await resolveHostMap($, key, meta, context, false); if (hasRules(hostMap)) { mapBySub.set(key, hostMap); } }) ); if (mapBySub.size === 0) { return proxies; } let replaced = 0; const result = proxies.map((p) => { const hostMap = mapBySub.get(p?.subName); if (hostMap && applyHostMapping(p, hostMap)) replaced++; return p; }); const origins = Array.from(new Set(Array.from(mapBySub.values(), (m) => m.origin))).join(","); writeCache(proxiesCacheKey, { updatedAt: Date.now(), proxies: result }, $); console.log(`[HostSync][Collection] 共 ${proxies.length} 个节点,替换 ${replaced} 个 (来源: ${origins})`); return result; } async function resolveHostMap($, subKey, subMeta, context, isSingle) { const cacheKey = `substore_host_sync_${subKey}`; // Step A: 优先直接读取 Sub-Store 已获取的 context.raw / 本地订阅内容,避免二次请求 const rawContent = extractRawContent(context, subKey, subMeta, isSingle); if (rawContent) { const body = String(rawContent).replace(/^\uFEFF/, ""); if (!isHtmlError(body) && isSurgeConfig(body)) { const parsed = parseSurgeHostSection(body); if (hasRules(parsed)) { writeCache(cacheKey, { updatedAt: Date.now(), ...parsed }, $); return { ...parsed, origin: "context.raw" }; } const cachedMap = fallbackFromCache($, subKey, cacheKey, "context.raw 无有效 [Host]"); if (cachedMap) return cachedMap; return { ...parsed, origin: "context.raw" }; } if (isHtmlError(body) || !subMeta?.url) { const cachedMap = fallbackFromCache($, subKey, cacheKey, "context.raw 非有效 Surge 配置"); if (cachedMap) return cachedMap; console.log(`[HostSync][${subKey}] context.raw 非有效 Surge 配置,无可用缓存`); return null; } } // Step B: 兼容旧版 Sub-Store(无 context.raw)或非 Surge 原始内容时回退 URL 拉取 if (subMeta?.url) { try { const req = { url: subMeta.url, headers: { "User-Agent": subMeta.ua || "Surge/3350", }, timeout: 8000, }; if (subMeta.proxy) { req.policy = subMeta.proxy; } const res = await $.http.get(req); const status = res?.status ?? res?.statusCode; if (status !== undefined && (status < 200 || status >= 300)) { throw new Error(`HTTP ${status}`); } const rawBody = typeof res === "string" ? res : (res?.body || ""); const body = String(rawBody).replace(/^\uFEFF/, ""); if (!body || isHtmlError(body)) { throw new Error("响应为空或返回 HTML 错误页"); } if (!isSurgeConfig(body)) { throw new Error("响应不含有效 Surge 配置段"); } const parsed = parseSurgeHostSection(body); if (hasRules(parsed)) { writeCache(cacheKey, { updatedAt: Date.now(), ...parsed }, $); return { ...parsed, origin: "http" }; } const cachedMap = fallbackFromCache($, subKey, cacheKey, "本次响应无有效 [Host]"); if (cachedMap) return cachedMap; return { ...parsed, origin: "http" }; } catch (err) { const cachedMap = fallbackFromCache($, subKey, cacheKey, `拉取失败(${err?.message || err})`); if (cachedMap) return cachedMap; console.log(`[HostSync][${subKey}] 拉取失败(${err?.message || err}),无可用缓存`); return null; } } // Step C: 无 context.raw 且无远程 URL return fallbackFromCache($, subKey, cacheKey, "无可用订阅原文"); } function extractRawContent(context, subKey, subMeta, isSingle) { const raw = context?.raw; if (typeof raw === "string") { return isSingle ? raw : ""; } if (Array.isArray(raw)) { return isSingle ? readRawEntry(raw) : ""; } if (raw && typeof raw === "object") { const hit = readRawEntry(raw[subKey]); if (hit) return hit; } return readRawEntry(subMeta?.content); } function readRawEntry(entry) { if (!entry) return ""; if (typeof entry === "string") return entry; if (Array.isArray(entry)) { return entry.map(readRawEntry).filter(Boolean).join("\n"); } if (typeof entry === "object") { for (const field of ["raw", "content", "body", "text"]) { if (typeof entry[field] === "string" && entry[field]) { return entry[field]; } } } return ""; } function isHtmlError(body) { return /^\s*( 0 || (hostMap.wildcardRules || []).length > 0; } function applyHostMapping(p, hostMap) { if (!p || !p.server) return false; const oldServer = String(p.server).trim(); const newServer = resolveHost(oldServer, hostMap.exactMap, hostMap.wildcardRules); if (newServer && newServer.toLowerCase() !== oldServer.toLowerCase()) { if (!p.sni && !isIP(oldServer) && isTlsProxy(p)) { p.sni = oldServer; } p.server = newServer; return true; } return false; } function parseSurgeHostSection(content) { const exactMap = {}; const wildcardMap = new Map(); const lines = String(content).replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n").split("\n"); let inHost = false; for (const rawLine of lines) { const line = rawLine.trim(); if (!line || line.startsWith("#") || line.startsWith(";") || line.startsWith("//")) { continue; } const section = line.match(/^\[([^\]]+)\]$/); if (section) { inHost = section[1].trim().toLowerCase() === "host"; continue; } if (!inHost) continue; const clean = line.replace(/\s+(?:#|;|\/\/).*$/, "").trim(); const eqIdx = clean.indexOf("="); if (eqIdx <= 0) continue; const key = clean.slice(0, eqIdx).trim().toLowerCase(); const val = clean.slice(eqIdx + 1).trim().split(",")[0].trim().replace(/^["']|["']$/g, "").trim(); if ( !key || !val || IGNORED_HOST_KEYS.has(key) || IGNORED_HOST_VALUES.has(val.toLowerCase()) || /^(server:|script:|system$)/i.test(val) ) { continue; } if (key.startsWith("*.") && key.length > 2) { wildcardMap.set(key.slice(1), val); } else if (!key.includes("*")) { exactMap[key] = val; } } const wildcardRules = Array.from(wildcardMap, ([suffix, target]) => ({ suffix, target })) .sort((a, b) => b.suffix.length - a.suffix.length); return { exactMap, wildcardRules }; } function resolveHost(host, exactMap, wildcardRules) { let current = String(host).trim(); const visited = new Set([current.toLowerCase()]); for (let hop = 0; hop < 5; hop++) { const lower = current.toLowerCase(); let next = exactMap[lower]; if (!next && wildcardRules.length > 0) { for (const rule of wildcardRules) { if (lower.endsWith(rule.suffix) && lower.length > rule.suffix.length) { next = rule.target; break; } } } if (!next) break; const nextLower = next.toLowerCase(); if (visited.has(nextLower)) break; visited.add(nextLower); current = next; } return current; } function isTlsProxy(p) { return Boolean(p.tls) || TLS_PROTOCOLS.has(String(p.type || "").toLowerCase()); } function isIP(str) { return /^(\d{1,3}\.){3}\d{1,3}$/.test(str) || str.includes(":"); }