diff --git a/CLAUDE.md b/CLAUDE.md index 52c15591d..1d633b866 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -13,7 +13,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## 项目概览 -Sublink Worker 是多平台代理订阅转换器:将各类协议(ShadowSocks/VMess/VLESS/Hysteria2/Trojan/TUIC)转为客户端配置(Sing-Box/Clash/Xray/Surge)。同一份代码跑在 Cloudflare Workers / Node.js / Vercel / Docker 上。技术栈:Hono(Web/JSX SSR)+ Vitest + Wrangler + esbuild + ioredis。 +Sublink Worker 是多平台代理订阅转换器:将各类协议(ShadowSocks/VMess/VLESS/Hysteria2/Trojan/TUIC)转为客户端配置(Sing-Box/Clash/Xray/Surge/Quantumult X)。同一份代码跑在 Cloudflare Workers / Node.js / Vercel / Docker 上。技术栈:Hono(Web/JSX SSR)+ Vitest + Wrangler + esbuild + ioredis。 ## 常用命令 @@ -47,18 +47,21 @@ Sublink Worker 是多平台代理订阅转换器:将各类协议(ShadowSocks ## 协议解析与配置构建 -**ProxyParser**(`src/parsers/ProxyParser.js`)按 URL scheme 分发到 `src/parsers/protocols/Parser.js`。HTTP(S) 订阅走 `httpSubscriptionFetcher` → `subscriptionContentParser`,自动识别 Sing-Box JSON / Clash YAML / Surge INI / Base64 列表。 +**ProxyParser**(`src/parsers/ProxyParser.js`)按 URL scheme 分发到 `src/parsers/protocols/Parser.js`。HTTP(S) 订阅走 `httpSubscriptionFetcher` → `subscriptionContentParser`,自动识别 Sing-Box JSON / Clash YAML / Surge INI / Quantumult X 节点行 / Base64 列表。 返回值约定: - 协议 parser:`{ tag, type, ...protocolFields }` -- 订阅级 parser:`{ type: 'yamlConfig'|'singboxConfig'|'surgeConfig', config, proxies }` +- 订阅级 parser:`{ type: 'yamlConfig'|'singboxConfig'|'surgeConfig'|'quanxConfig', config, proxies }`(类型集合见 `BaseConfigBuilder` 的 `CONFIG_RESULT_TYPES`) +- 解析不出节点的输入行/订阅记入 builder 的 `inputDiagnostics`(QuanX 无节点时的 400 会列出) **新增协议**:在 `src/parsers/protocols/` 加 parser,并在 `ProxyParser.js` 的 `protocolParsers` map 注册。 -**Builder 模式**:`SingboxConfigBuilder` / `ClashConfigBuilder` / `SurgeConfigBuilder` 都继承 `BaseConfigBuilder`。子类必须实现:`getProxies()`、`getProxyName(proxy)`、`convertProxy(proxy)`、`addProxyToConfig(proxy)`、`addAutoSelectGroup(list)`、`addNodeSelectGroup(list)`、`addOutboundGroups(outbounds, list)`、`addCustomRuleGroups(list)`、`addFallBackGroup(list)`、`addCountryGroups()`、`formatConfig()`。 +**Builder 模式**:`SingboxConfigBuilder` / `ClashConfigBuilder` / `SurgeConfigBuilder` / `QuanxConfigBuilder` 都继承 `BaseConfigBuilder`。子类必须实现:`getProxies()`、`getProxyName(proxy)`、`convertProxy(proxy)`、`addProxyToConfig(proxy)`、`addAutoSelectGroup(list)`、`addNodeSelectGroup(list)`、`addOutboundGroups(outbounds, list)`、`addCustomRuleGroups(list)`、`addFallBackGroup(list)`、`addCountryGroups()`、`formatConfig()`。 **Config Override**:订阅含完整配置时,`applyConfigOverrides()` 合并非代理字段到 base config;blacklist(proxies、rules、rule-providers)永远不被覆盖;Clash `proxy-groups` 可被订阅覆盖以保留用户分组结构。 +QuanX(`/quanx`,短链前缀 `q`):不支持 hysteria2/tuic/grpc/xhttp/httpupgrade 等,节点输出为注释;一个可用节点都没有时返回 400 并列出跳过原因(不生成全 direct 配置);远程规则复用 Surge 规则源,依赖 `resource_parser_url` + `opt-parser=true` 在设备端转换;不接受订阅的 config override;拉上游订阅默认用 `clash.meta` UA(不转发 QuanX UA,也不用 curl)。基础配置(`configId` 前缀 `quanx_`)由服务端解析 INI 存为 `{ sections: { name: [lines] } }`,`[general]` 按 key 合并,`policy/server_local/filter_*` 永远由生成逻辑决定。`list=true` 只输出节点行(用作 QX 节点资源);TLS SNI 统一写 `tls-host`,`obfs-host` 只承载 ws/http Host(对齐 Sub-Store)。 + 国家分组逻辑在 `src/utils.js#groupProxiesByCountry`。 ## 测试 diff --git a/src/app/createApp.jsx b/src/app/createApp.jsx index 58f0b245f..9725eb040 100644 --- a/src/app/createApp.jsx +++ b/src/app/createApp.jsx @@ -9,6 +9,7 @@ import { UpdateChecker } from '../components/UpdateChecker.jsx'; import { SingboxConfigBuilder } from '../builders/SingboxConfigBuilder.js'; import { ClashConfigBuilder } from '../builders/ClashConfigBuilder.js'; import { SurgeConfigBuilder } from '../builders/SurgeConfigBuilder.js'; +import { QuanxConfigBuilder } from '../builders/QuanxConfigBuilder.js'; import { createTranslator, resolveLanguage } from '../i18n/index.js'; import { encodeBase64, tryDecodeSubscriptionLines } from '../utils.js'; import { APP_NAME, APP_SUBTITLE } from '../constants.js'; @@ -19,6 +20,7 @@ import { normalizeRuntime } from '../runtime/runtimeConfig.js'; import { PREDEFINED_RULE_SETS, SING_BOX_CONFIG, SING_BOX_CONFIG_V1_11, generateSubconverterConfig } from '../config/index.js'; const DEFAULT_USER_AGENT = 'curl/7.74.0'; +const QUANX_UPSTREAM_USER_AGENT = 'clash.meta'; export function createApp(bindings = {}) { const runtime = normalizeRuntime(bindings); @@ -217,6 +219,55 @@ export function createApp(bindings = {}) { } }); + app.get('/quanx', async (c) => { + try { + const config = c.req.query('config'); + if (!config) { + return c.text('Missing config parameter', 400); + } + + const selectedRules = parseSelectedRules(c.req.query('selectedRules')); + const customRules = parseJsonArray(c.req.query('customRules')); + // Panels pick the response format from the UA; curl often gets an empty/HTML answer and + // the QX app's own UA gets QX lines. A Clash UA yields the most widely served and most + // completely parsed format (Clash YAML); UA-agnostic sources (e.g. 3x-ui) are unaffected. + const ua = c.req.query('ua') || QUANX_UPSTREAM_USER_AGENT; + const groupByCountry = parseBooleanFlag(c.req.query('group_by_country')); + const includeAutoSelect = c.req.query('include_auto_select') !== 'false'; + const configId = c.req.query('configId'); + const lang = c.get('lang'); + + let baseConfig; + if (configId?.startsWith('quanx_')) { + const storage = requireConfigStorage(services.configStorage); + baseConfig = await storage.getConfigById(configId); + } + + const builder = new QuanxConfigBuilder( + config, + selectedRules, + customRules, + baseConfig, + lang, + ua, + groupByCountry, + includeAutoSelect + ); + // list=true serves only node lines, for use as a QX node resource ([server_remote]) + const output = parseBooleanFlag(c.req.query('list')) + ? await builder.buildNodeList() + : await builder.build(); + + const userinfo = builder.getSubscriptionUserinfo(); + if (userinfo) { + c.header('subscription-userinfo', userinfo); + } + return c.text(output); + } catch (error) { + return handleError(c, error, runtime.logger); + } + }); + app.get('/subconverter', (c) => { try { const rawSelectedRules = c.req.query('selectedRules'); @@ -350,6 +401,7 @@ export function createApp(bindings = {}) { app.get('/b/:code', redirectHandler('singbox')); app.get('/c/:code', redirectHandler('clash')); app.get('/x/:code', redirectHandler('xray')); + app.get('/q/:code', redirectHandler('quanx')); app.post('/config', async (c) => { try { @@ -382,13 +434,13 @@ export function createApp(bindings = {}) { const prefix = pathParts[1]; const shortCode = pathParts[2]; - if (!['b', 'c', 'x', 's'].includes(prefix)) return c.text(t('invalidShortUrl'), 400); + if (!['b', 'c', 'x', 's', 'q'].includes(prefix)) return c.text(t('invalidShortUrl'), 400); const shortLinks = requireShortLinkService(services.shortLinks); const originalParam = await shortLinks.resolveShortCode(shortCode); if (!originalParam) return c.text(t('shortUrlNotFound'), 404); - const mapping = { b: 'singbox', c: 'clash', x: 'xray', s: 'surge' }; + const mapping = { b: 'singbox', c: 'clash', x: 'xray', s: 'surge', q: 'quanx' }; const originalUrl = `${urlObj.origin}/${mapping[prefix]}${originalParam}`; return c.json({ originalUrl }); } catch (error) { diff --git a/src/builders/BaseConfigBuilder.js b/src/builders/BaseConfigBuilder.js index 353a5438a..d4e93d81a 100644 --- a/src/builders/BaseConfigBuilder.js +++ b/src/builders/BaseConfigBuilder.js @@ -1,8 +1,18 @@ import { ProxyParser } from '../parsers/index.js'; -import { createStableProviderName, deepCopy, tryDecodeSubscriptionLines, decodeBase64 } from '../utils.js'; +import { createStableProviderName, deepCopy, tryDecodeSubscriptionLines, decodeBase64, stripInvisibleChars, previewInput } from '../utils.js'; import { createTranslator } from '../i18n/index.js'; import { generateRules, getOutbounds, PREDEFINED_RULE_SETS } from '../config/index.js'; +// Share links without a `#name` fragment parse with an empty tag and were silently dropped; +// name them after their endpoint so they still reach the output. +function withFallbackTag(item) { + if (item?.tag || !item?.type || !item?.server) return item; + return { ...item, tag: `${item.type} ${item.server}:${item.server_port}` }; +} + +// Subscription-level parser results that carry a proxies array (see subscriptionContentParser) +const CONFIG_RESULT_TYPES = new Set(['yamlConfig', 'singboxConfig', 'surgeConfig', 'quanxConfig']); + export class BaseConfigBuilder { constructor(inputString, baseConfig, lang, userAgent, groupByCountry = false, includeAutoSelect = true) { this.inputString = inputString; @@ -18,6 +28,8 @@ export class BaseConfigBuilder { this.providerNodeNames = []; // node names from provider subscriptions, for country enumeration only this.autoProviderDescriptors = undefined; this.subscriptionUserinfo = undefined; + // Input lines that yielded no proxy, kept so callers can explain an empty result + this.inputDiagnostics = []; } async build() { @@ -28,7 +40,7 @@ export class BaseConfigBuilder { } async parseCustomItems() { - const input = this.inputString || ''; + const input = stripInvisibleChars(this.inputString || ''); const parsedItems = []; // Import the content parser for direct input parsing @@ -93,8 +105,18 @@ export class BaseConfigBuilder { try { const fetchResult = await fetchSubscriptionWithFormat(trimmedUrl, this.userAgent); + if (!fetchResult) { + this.inputDiagnostics.push(`failed to fetch subscription: ${previewInput(trimmedUrl)}`); + } if (fetchResult) { const { content, format, url: originalUrl, subscriptionUserinfo } = fetchResult; + const parsedBefore = parsedItems.length; + // A fetched-but-unusable subscription is otherwise indistinguishable from empty input + const noteIfEmpty = () => { + if (parsedItems.length === parsedBefore) { + this.inputDiagnostics.push(`subscription returned no usable nodes: ${previewInput(trimmedUrl)} (content starts with: ${previewInput(content, 40)})`); + } + }; if (subscriptionUserinfo && !this.subscriptionUserinfo) { this.subscriptionUserinfo = subscriptionUserinfo; @@ -111,7 +133,7 @@ export class BaseConfigBuilder { // Otherwise parse the content as usual const result = parseSubscriptionContent(content); - if (result && typeof result === 'object' && (result.type === 'yamlConfig' || result.type === 'singboxConfig' || result.type === 'surgeConfig')) { + if (result && typeof result === 'object' && CONFIG_RESULT_TYPES.has(result.type)) { if (result.config) { this.applyConfigOverrides(result.config); } @@ -122,6 +144,7 @@ export class BaseConfigBuilder { } }); } + noteIfEmpty(); continue; } // Handle array of URIs or other formats @@ -137,17 +160,18 @@ export class BaseConfigBuilder { } } } + noteIfEmpty(); } } catch (error) { console.error('Error processing HTTP subscription:', error); + this.inputDiagnostics.push(`error processing subscription: ${previewInput(trimmedUrl)} (${previewInput(error?.message, 80)})`); } continue; } // Non-HTTP URLs (protocol URIs like ss://, vmess://, etc.) const result = await ProxyParser.parse(processedUrl, this.userAgent); - // Handle yamlConfig, singboxConfig, and surgeConfig types (they have the same structure) - if (result && typeof result === 'object' && (result.type === 'yamlConfig' || result.type === 'singboxConfig' || result.type === 'surgeConfig')) { + if (result && typeof result === 'object' && CONFIG_RESULT_TYPES.has(result.type)) { if (result.config) { this.applyConfigOverrides(result.config); } @@ -173,6 +197,8 @@ export class BaseConfigBuilder { } } else if (result) { parsedItems.push(result); + } else if (trimmedUrl) { + this.inputDiagnostics.push(`unrecognized input: ${previewInput(processedUrl)}`); } } } @@ -381,7 +407,7 @@ export class BaseConfigBuilder { } addCustomItems(customItems) { - const validItems = customItems.filter(item => item != null); + const validItems = customItems.filter(item => item != null).map(withFallbackTag); validItems.forEach(item => { if (item?.tag) { const convertedProxy = this.convertProxy(item); diff --git a/src/builders/ClashConfigBuilder.js b/src/builders/ClashConfigBuilder.js index 8fe853bac..3de75b6ad 100644 --- a/src/builders/ClashConfigBuilder.js +++ b/src/builders/ClashConfigBuilder.js @@ -47,6 +47,19 @@ function getClashUdpValue(proxy, defaultEnabled = true) { return defaultEnabled; } +// Xray-core >= 26.9.8 REALITY servers require an X25519MLKEM768 key share, which mihomo only +// sends when asked; without it the handshake fails with "REALITY authentication failed". +// Set here rather than on the shared proxy model, which is copied verbatim into sing-box output. +function getClashRealityOpts(proxy) { + const reality = proxy.tls?.reality; + if (!reality?.enabled) return undefined; + return { + 'public-key': reality.public_key, + 'short-id': reality.short_id, + 'support-x25519mlkem768': true + }; +} + export class ClashConfigBuilder extends BaseConfigBuilder { constructor(inputString, selectedRules, customRules, baseConfig, lang, userAgent, groupByCountry = false, enableClashUI = false, externalController, externalUiDownloadUrl, includeAutoSelect = true) { if (!baseConfig) { @@ -202,10 +215,7 @@ export class ClashConfigBuilder extends BaseConfigBuilder { path: proxy.transport.path, headers: proxy.transport.headers } : undefined, - 'reality-opts': proxy.tls?.reality?.enabled ? { - 'public-key': proxy.tls.reality.public_key, - 'short-id': proxy.tls.reality.short_id, - } : undefined, + 'reality-opts': getClashRealityOpts(proxy), 'grpc-opts': proxy.transport?.type === 'grpc' ? { 'grpc-service-name': proxy.transport.service_name, } : undefined, @@ -252,10 +262,7 @@ export class ClashConfigBuilder extends BaseConfigBuilder { path: proxy.transport.path, headers: proxy.transport.headers } : undefined, - 'reality-opts': proxy.tls?.reality?.enabled ? { - 'public-key': proxy.tls.reality.public_key, - 'short-id': proxy.tls.reality.short_id, - } : undefined, + 'reality-opts': getClashRealityOpts(proxy), 'grpc-opts': proxy.transport?.type === 'grpc' ? { 'grpc-service-name': proxy.transport.service_name, } : undefined, diff --git a/src/builders/QuanxConfigBuilder.js b/src/builders/QuanxConfigBuilder.js new file mode 100644 index 000000000..4dcf89aee --- /dev/null +++ b/src/builders/QuanxConfigBuilder.js @@ -0,0 +1,538 @@ +import { BaseConfigBuilder } from './BaseConfigBuilder.js'; +import { groupProxiesByCountry } from '../utils.js'; +import { QUANX_CONFIG, SURGE_SITE_RULE_SET_BASEURL, SURGE_IP_RULE_SET_BASEURL, generateRules, DIRECT_DEFAULT_RULES } from '../config/index.js'; +import { addProxyWithDedup } from './helpers/proxyHelpers.js'; +import { buildSelectorMembers, buildNodeSelectMembers, buildCustomRuleMembers, uniqueNames } from './helpers/groupBuilder.js'; +import { parsePluginString } from '../parsers/protocols/shadowsocksParser.js'; +import { InvalidPayloadError } from '../services/errors.js'; + +// Syntax reference: https://github.com/crossutility/Quantumult-X/blob/master/sample.conf + +const SS_METHODS = new Set([ + 'none', 'rc4-md5', 'rc4-md5-6', 'aes-128-cfb', 'aes-192-cfb', 'aes-256-cfb', + 'aes-128-ctr', 'aes-192-ctr', 'aes-256-ctr', 'bf-cfb', 'cast5-cfb', 'des-cfb', 'rc2-cfb', + 'salsa20', 'chacha20', 'chacha20-ietf', 'aes-128-gcm', 'aes-192-gcm', 'aes-256-gcm', + 'chacha20-ietf-poly1305', 'xchacha20-ietf-poly1305', + '2022-blake3-aes-128-gcm', '2022-blake3-aes-256-gcm' +]); + +const VMESS_METHODS = new Set(['none', 'aes-128-gcm', 'chacha20-poly1305']); + +const BUILTIN_POLICIES = { DIRECT: 'direct', REJECT: 'reject' }; + +// Only the params subconverter has long emitted for QX, to stay compatible with older QX builds +const LATENCY_PARAMS = 'check-interval=600'; + +const REMOTE_UPDATE_INTERVAL = 86400; + +// Built from the subscription and selected rules; a base config cannot override them, +// mirroring how Clash base configs never override proxies/rules. +const GENERATED_SECTIONS = new Set(['policy', 'server_local', 'filter_remote', 'filter_local']); + +const SECTION_ORDER = [ + 'general', 'dns', 'policy', 'server_remote', 'filter_remote', 'rewrite_remote', + 'server_local', 'filter_local', 'rewrite_local', 'task_local', 'http_backend', 'mitm' +]; + +function generalKey(line) { + const index = line.indexOf('='); + return index === -1 ? line : line.slice(0, index).trim(); +} + +// [general] merges per key so a user profile keeps defaults it omits (notably +// resource_parser_url, which the generated filter_remote lines depend on). +// Other sections are taken from the user config wholesale when present. +export function mergeQuanxSections(defaults = {}, user = {}) { + // Null prototype: stored section names are user data and may be "__proto__" + const merged = Object.assign(Object.create(null), defaults); + Object.entries(user || {}).forEach(([name, lines]) => { + if (GENERATED_SECTIONS.has(name)) return; + if (name === 'general') { + const userKeys = new Set(lines.map(generalKey)); + merged.general = [...(defaults.general || []).filter(line => !userKeys.has(generalKey(line))), ...lines]; + } else { + merged[name] = [...lines]; + } + }); + return merged; +} + +// QX splits lines on commas and key=value pairs on '=' with no escaping, so names must avoid both +export function sanitizeQuanxName(name) { + return String(name ?? '').replace(/[\r\n]+/g, ' ').replace(/,/g, ',').replace(/=/g, '=').trim(); +} + +class UnsupportedProxyError extends Error { } + +function unsupported(reason) { + throw new UnsupportedProxyError(reason); +} + +// A raw comma would silently shift every following parameter, so refuse instead +function param(key, value) { + const str = String(value); + if (/[,\r\n]/.test(str)) { + unsupported(`${key} contains a comma or newline`); + } + return `${key}=${str}`; +} + +function formatServer(server, port) { + if (!server || !port) unsupported('missing server or port'); + // Subscription data is untrusted: a delimiter here would split or inject config lines + if (/[,\s]/.test(String(server))) unsupported('server contains a delimiter'); + if (!/^\d+$/.test(String(port))) unsupported('invalid port'); + const host = String(server).includes(':') && !String(server).startsWith('[') ? `[${server}]` : server; + return `${host}:${port}`; +} + +function firstValue(value) { + return Array.isArray(value) ? value[0] : value; +} + +function getHostHeader(transport) { + const headers = transport?.headers; + if (!headers || typeof headers !== 'object') return undefined; + return firstValue(headers.host ?? headers.Host); +} + +// Sing-Box keeps SIP003 plugin_opts as a "k=v;flag" string, other sources give an object +function normalizePluginOpts(opts) { + if (typeof opts === 'string') return parsePluginString(`plugin;${opts}`)?.plugin_opts || {}; + return opts && typeof opts === 'object' ? opts : {}; +} + +function getPath(transport) { + return firstValue(transport?.path); +} + +function isTlsEnabled(proxy) { + return !!proxy.tls?.enabled; +} + +function tlsCommonParams(tls) { + const reality = tls?.reality; + if (reality?.enabled) { + // Reality authenticates the server itself; the official sample sets no tls-verification here + if (!reality.public_key) unsupported('reality without public key'); + const parts = [param('reality-base64-pubkey', reality.public_key)]; + if (reality.short_id) parts.push(param('reality-hex-shortid', reality.short_id)); + return parts; + } + return [param('tls-verification', !tls?.insecure)]; +} + +function udpRelay(proxy) { + // Same default as the Clash builder: enabled unless the source explicitly disables it + return param('udp-relay', proxy.udp !== false); +} + +// Shared by vmess/vless. SNI goes to tls-host and obfs-host only carries the ws/http Host, +// matching Sub-Store's QX producer (widely used in practice), so Host != SNI stays expressible. +function v2rayTransportParams(proxy) { + const transport = proxy.transport; + const type = transport?.type || 'tcp'; + const tls = isTlsEnabled(proxy); + const sni = proxy.tls?.server_name; + const parts = []; + + if (type === 'tcp') { + if (tls) parts.push('obfs=over-tls'); + } else if (type === 'ws') { + parts.push(tls ? 'obfs=wss' : 'obfs=ws'); + const host = getHostHeader(transport) || (tls ? sni : undefined); + if (host) parts.push(param('obfs-host', host)); + parts.push(param('obfs-uri', getPath(transport) || '/')); + } else if (type === 'http') { + if (tls) unsupported('http obfs over tls'); + parts.push('obfs=http'); + const host = getHostHeader(transport); + if (host) parts.push(param('obfs-host', host)); + parts.push(param('obfs-uri', getPath(transport) || '/')); + } else { + unsupported(`transport ${type}`); + } + + if (tls) { + if (sni) parts.push(param('tls-host', sni)); + parts.push(...tlsCommonParams(proxy.tls)); + } + return parts; +} + +function convertShadowsocks(proxy) { + const method = proxy.method || 'none'; + if (!SS_METHODS.has(method)) unsupported(`cipher ${method}`); + const parts = [ + `shadowsocks=${formatServer(proxy.server, proxy.server_port)}`, + param('method', method), + param('password', proxy.password ?? '') + ]; + + if (proxy.plugin) { + const opts = normalizePluginOpts(proxy.plugin_opts); + if (proxy.plugin === 'obfs' || proxy.plugin === 'obfs-local') { + const mode = opts.mode || 'http'; + if (mode !== 'http' && mode !== 'tls') unsupported(`obfs mode ${mode}`); + parts.push(param('obfs', mode)); + if (opts.host) parts.push(param('obfs-host', opts.host)); + if (mode === 'http' && opts.path) parts.push(param('obfs-uri', opts.path)); + } else if (proxy.plugin === 'v2ray-plugin' && (!opts.mode || opts.mode === 'websocket')) { + const tls = opts.tls === true || opts.tls === 'true'; + parts.push(tls ? 'obfs=wss' : 'obfs=ws'); + if (opts.host) parts.push(param('obfs-host', opts.host)); + parts.push(param('obfs-uri', opts.path || '/')); + } else { + unsupported(`plugin ${proxy.plugin}`); + } + } + + parts.push(udpRelay(proxy)); + return parts; +} + +function convertVmess(proxy) { + const security = proxy.security || 'auto'; + const method = security === 'zero' ? 'none' : (VMESS_METHODS.has(security) ? security : 'chacha20-poly1305'); + return [ + `vmess=${formatServer(proxy.server, proxy.server_port)}`, + param('method', method), + param('password', proxy.uuid ?? ''), + ...v2rayTransportParams(proxy), + param('aead', !(Number(proxy.alter_id) > 0)), + udpRelay(proxy) + ]; +} + +function convertVless(proxy) { + const parts = [ + `vless=${formatServer(proxy.server, proxy.server_port)}`, + 'method=none', + param('password', proxy.uuid ?? ''), + ...v2rayTransportParams(proxy) + ]; + if (proxy.flow) { + // -udp443 is a client-side Xray switch (allow UDP/443); the wire protocol and the + // server's flow are plain vision, which is the only flow QX speaks. + const flow = proxy.flow === 'xtls-rprx-vision-udp443' ? 'xtls-rprx-vision' : proxy.flow; + if (flow !== 'xtls-rprx-vision') unsupported(`flow ${proxy.flow}`); + if (!isTlsEnabled(proxy)) unsupported('vision flow without tls'); + parts.push(param('vless-flow', flow)); + } + parts.push(udpRelay(proxy)); + return parts; +} + +function convertTrojan(proxy) { + const parts = [ + `trojan=${formatServer(proxy.server, proxy.server_port)}`, + param('password', proxy.password ?? '') + ]; + const type = proxy.transport?.type || 'tcp'; + const sni = proxy.tls?.server_name; + if (proxy.tls && proxy.tls.enabled === false) unsupported('trojan without tls'); + + if (type === 'ws') { + // QX only supports websocket over tls for trojan + parts.push('obfs=wss'); + const host = getHostHeader(proxy.transport) || sni; + if (host) parts.push(param('obfs-host', host)); + parts.push(param('obfs-uri', getPath(proxy.transport) || '/')); + } else if (type === 'tcp') { + parts.push('over-tls=true'); + } else { + unsupported(`transport ${type}`); + } + if (sni) parts.push(param('tls-host', sni)); + + parts.push(...tlsCommonParams(proxy.tls)); + parts.push(udpRelay(proxy)); + return parts; +} + +function convertAnytls(proxy) { + const parts = [ + `anytls=${formatServer(proxy.server, proxy.server_port)}`, + param('password', proxy.password ?? ''), + 'over-tls=true' + ]; + if (proxy.tls?.server_name) parts.push(param('tls-host', proxy.tls.server_name)); + parts.push(...tlsCommonParams(proxy.tls)); + parts.push(udpRelay(proxy)); + return parts; +} + +const CONVERTERS = { + shadowsocks: convertShadowsocks, + vmess: convertVmess, + vless: convertVless, + trojan: convertTrojan, + anytls: convertAnytls +}; + +export function formatQuanxProxy(proxy) { + return `${proxy.body}, tag=${proxy.tag}`; +} + +export class QuanxConfigBuilder extends BaseConfigBuilder { + constructor(inputString, selectedRules, customRules, baseConfig, lang, userAgent, groupByCountry, includeAutoSelect = true) { + super(inputString, QUANX_CONFIG, lang, userAgent, groupByCountry, includeAutoSelect); + this.config.sections = mergeQuanxSections(QUANX_CONFIG.sections, baseConfig?.sections); + this.selectedRules = selectedRules; + this.customRules = customRules; + this.countryGroupNames = []; + this.manualGroupName = null; + this.unsupportedProxies = []; + this.config.proxies = []; + this.config.policies = []; + } + + // Overrides from Clash/Sing-Box/Surge subscriptions use foreign keys and group syntax + // that would corrupt a QX profile; only their proxies are kept. + applyConfigOverrides() { } + + getProxies() { + return this.config.proxies; + } + + getProxyName(proxy) { + return proxy.tag; + } + + // Proxies are kept as { tag, body } so dedup/renaming only touches the tag + convertProxy(proxy) { + const tag = sanitizeQuanxName(proxy.tag); + const converter = CONVERTERS[proxy.type]; + try { + if (!converter) unsupported(`type ${proxy.type}`); + if (!tag) unsupported('empty name'); + return { tag, body: converter(proxy).join(', ') }; + } catch (error) { + // One malformed node must not break the whole profile + const reason = error instanceof UnsupportedProxyError ? error.message : 'invalid proxy'; + // Reasons echo subscription values; a newline would escape the comment line + this.unsupportedProxies.push(`${tag || proxy.type} - ${reason}`.replace(/[\r\n]+/g, ' ')); + return null; + } + } + + addProxyToConfig(proxy) { + addProxyWithDedup(this.config.proxies, proxy, { + isSame: (a, b) => a.body === b.body + }); + } + + hasPolicy(name) { + return this.config.policies.some(policy => policy.name === name); + } + + addPolicy(name, type, members) { + const policyName = sanitizeQuanxName(name); + if (!policyName || this.hasPolicy(policyName)) return; + this.config.policies.push({ name: policyName, type, members: uniqueNames(members) }); + } + + buildSelectorOptions(proxyList) { + return buildSelectorMembers({ + proxyList, + translator: this.t, + groupByCountry: this.groupByCountry, + manualGroupName: this.manualGroupName, + countryGroupNames: this.countryGroupNames, + includeAutoSelect: this.includeAutoSelect + }); + } + + addAutoSelectGroup(proxyList) { + if (!this.includeAutoSelect) return; + this.addPolicy(this.t('outboundNames.Auto Select'), 'url-latency-benchmark', proxyList); + } + + addNodeSelectGroup(proxyList) { + this.addPolicy(this.t('outboundNames.Node Select'), 'static', buildNodeSelectMembers({ + proxyList, + translator: this.t, + includeAutoSelect: this.includeAutoSelect + })); + } + + addOutboundGroups(outbounds, proxyList) { + outbounds.forEach(outbound => { + if (outbound === 'Node Select') return; + let options = this.buildSelectorOptions(proxyList); + if (DIRECT_DEFAULT_RULES.has(outbound)) { + options = ['DIRECT', ...options.filter(p => p !== 'DIRECT')]; + } + this.addPolicy(this.t(`outboundNames.${outbound}`), 'static', options); + }); + } + + addCustomRuleGroups(proxyList) { + if (!Array.isArray(this.customRules)) return; + this.customRules.forEach(rule => { + this.addPolicy(rule.name, 'static', buildCustomRuleMembers({ + proxyList, + translator: this.t, + manualGroupName: this.manualGroupName, + includeAutoSelect: this.includeAutoSelect + })); + }); + } + + addFallBackGroup(proxyList) { + this.addPolicy(this.t('outboundNames.Fall Back'), 'static', this.buildSelectorOptions(proxyList)); + } + + addCountryGroups() { + const proxies = this.getProxies(); + const countryGroups = groupProxiesByCountry(proxies, { getName: proxy => proxy.tag }); + const manualProxyNames = proxies.map(proxy => proxy.tag); + const manualGroupName = manualProxyNames.length > 0 ? sanitizeQuanxName(this.t('outboundNames.Manual Switch')) : null; + if (manualGroupName) { + this.addPolicy(manualGroupName, 'static', manualProxyNames); + } + + const countryGroupNames = Object.keys(countryGroups) + .sort((a, b) => a.localeCompare(b)) + .map(country => { + const { emoji, name, proxies: members } = countryGroups[country]; + const groupName = sanitizeQuanxName(`${emoji} ${name}`); + this.addPolicy(groupName, 'url-latency-benchmark', members); + return groupName; + }); + + const nodeSelectName = sanitizeQuanxName(this.t('outboundNames.Node Select')); + const nodeSelect = this.config.policies.find(policy => policy.name === nodeSelectName); + if (nodeSelect) { + nodeSelect.members = uniqueNames(buildNodeSelectMembers({ + proxyList: [], + translator: this.t, + groupByCountry: true, + manualGroupName, + countryGroupNames, + includeAutoSelect: this.includeAutoSelect + })); + } + this.countryGroupNames = countryGroupNames; + this.manualGroupName = manualGroupName; + } + + formatPolicy({ name, type, members }) { + const mapped = members.map(member => BUILTIN_POLICIES[member] || sanitizeQuanxName(member)); + // QX rejects empty policies and latency tests need real servers + if (mapped.length === 0) { + return `static=${name}, direct`; + } + // QX refuses a latency group with a single member (subconverter downgrades it the same way) + if (type === 'url-latency-benchmark' && mapped.length >= 2) { + return `url-latency-benchmark=${name}, ${mapped.join(', ')}, ${LATENCY_PARAMS}`; + } + return `static=${name}, ${mapped.join(', ')}`; + } + + policyName(outbound) { + return sanitizeQuanxName(this.t(`outboundNames.${outbound}`)); + } + + buildRemoteFilters(rules) { + const lines = []; + const usedTags = new Set(); + const add = (url, id, policy) => { + let tag = sanitizeQuanxName(`${id} - ${policy}`); + for (let i = 2; usedTags.has(tag); i++) tag = sanitizeQuanxName(`${id} - ${policy} ${i}`); + usedTags.add(tag); + lines.push(`${url}, tag=${tag}, force-policy=${policy}, update-interval=${REMOTE_UPDATE_INTERVAL}, opt-parser=true, enabled=true`); + }; + // Domain lists first so IP lists (which need DNS) are evaluated last + rules.forEach(rule => (rule.site_rules || []).filter(Boolean).forEach(site => { + add(`${SURGE_SITE_RULE_SET_BASEURL}${site}.conf`, `geosite:${site}`, rule.policy); + })); + rules.forEach(rule => (rule.ip_rules || []).filter(Boolean).forEach(ip => { + add(`${SURGE_IP_RULE_SET_BASEURL}${ip}.txt`, `geoip:${ip}`, rule.policy); + })); + return lines; + } + + buildLocalFilters(rules) { + const lines = []; + const push = (type, value, policy) => { + const str = typeof value === 'string' ? value.trim() : ''; + if (!str || /[,\s]/.test(str)) return; + lines.push(`${type}, ${str}, ${policy}`); + }; + rules.forEach(rule => (rule.domain_suffix || []).forEach(v => push('host-suffix', v, rule.policy))); + rules.forEach(rule => (rule.domain_keyword || []).forEach(v => push('host-keyword', v, rule.policy))); + rules.forEach(rule => (rule.ip_cidr || []).forEach(v => { + push(typeof v === 'string' && v.includes(':') ? 'ip6-cidr' : 'ip-cidr', v, rule.policy); + })); + rules.forEach(rule => (rule.src_ip_cidr || []).forEach(v => { + if (typeof v === 'string' && v.trim()) { + lines.push(`# source IP rules are not supported by Quantumult X, skipped: ${v.trim().replace(/[\r\n]+/g, '')}`); + } + })); + lines.push(`final, ${this.policyName('Fall Back')}`); + return lines; + } + + nodeLines() { + return [ + ...this.config.proxies.map(formatQuanxProxy), + ...this.unsupportedProxies.map(item => `# Unsupported by Quantumult X: ${item}`) + ]; + } + + // Bare server lines for a QX [server_remote] resource, like Sub-Store/subconverter node lists + formatNodeList() { + return this.nodeLines().join('\n') + '\n'; + } + + // Without a usable node every policy would collapse to direct and the profile would + // silently stop proxying, so fail loudly with the per-node reasons instead. + assertHasProxies() { + if (this.config.proxies.length > 0) return; + const list = (title, items) => items.length > 0 ? `\n${title}:\n${items.map(item => `- ${item}`).join('\n')}` : ''; + throw new InvalidPayloadError( + 'No Quantumult X compatible nodes found (QX supports ss/vmess/vless/trojan/anytls over tcp/ws/http only).' + + list('Skipped', this.unsupportedProxies) + + list('Not parsed', this.inputDiagnostics) + ); + } + + addSelectors() { + this.assertHasProxies(); + super.addSelectors(); + } + + // Skips policy/rule generation that build() would do and a node list never uses + async buildNodeList() { + this.addCustomItems(await this.parseCustomItems()); + this.assertHasProxies(); + return this.formatNodeList(); + } + + formatConfig() { + const customRules = Array.isArray(this.customRules) ? this.customRules : []; + // Copy: generateRules reverses customRules in place and formatConfig runs twice per request. + // It prepends one entry per custom rule, so the first customRules.length entries are custom; + // their names are user-defined and must not go through i18n (policies are created the same way). + const rules = generateRules(this.selectedRules, [...customRules]).map((rule, index) => ({ + ...rule, + policy: index < customRules.length ? sanitizeQuanxName(rule.outbound) : this.policyName(rule.outbound) + })).filter(rule => rule.policy); // a nameless custom rule has no policy to point at + const generated = { + policy: this.config.policies.map(policy => this.formatPolicy(policy)), + filter_remote: this.buildRemoteFilters(rules), + server_local: this.nodeLines(), + filter_local: this.buildLocalFilters(rules) + }; + const sections = this.config.sections || {}; + const names = [...SECTION_ORDER, ...Object.keys(sections).filter(name => !SECTION_ORDER.includes(name))]; + + return names + .map(name => { + const lines = Object.hasOwn(generated, name) ? generated[name] : (Object.hasOwn(sections, name) ? sections[name] : []); + return [`[${name}]`, ...lines].join('\n'); + }) + .join('\n\n') + '\n'; + } +} diff --git a/src/components/Form.jsx b/src/components/Form.jsx index 31218b9aa..aa98711a6 100644 --- a/src/components/Form.jsx +++ b/src/components/Form.jsx @@ -10,7 +10,8 @@ const LINK_FIELDS = [ { key: 'xray', labelKey: 'xrayLink' }, { key: 'singbox', labelKey: 'singboxLink' }, { key: 'clash', labelKey: 'clashLink' }, - { key: 'surge', labelKey: 'surgeLink' } + { key: 'surge', labelKey: 'surgeLink' }, + { key: 'quanx', labelKey: 'quanxLink' } ]; export const Form = (props) => { @@ -250,6 +251,7 @@ export const Form = (props) => { + diff --git a/src/components/formLogic.js b/src/components/formLogic.js index 57f401f33..dc601d0c3 100644 --- a/src/components/formLogic.js +++ b/src/components/formLogic.js @@ -314,6 +314,14 @@ export const formLogicFn = (t) => { this.configValidationState = 'success'; this.configValidationMessage = window.APP_TRANSLATIONS.validYamlConfig || 'YAML config is valid'; + } else if (this.configType === 'quanx') { + // Full parsing happens server-side on save; only catch obviously wrong input here + if (!/^\s*\[[^\]\r\n]+\]\s*$/m.test(content)) { + throw new Error('Quantumult X config needs [section] headers, e.g. [general]'); + } + this.configValidationState = 'success'; + this.configValidationMessage = + window.APP_TRANSLATIONS.validIniConfig || 'INI config is valid'; } else if (this.configType === 'surge') { parseSurgeConfigInput(this.configEditor); this.configValidationState = 'success'; @@ -397,7 +405,8 @@ export const formLogicFn = (t) => { xray: origin + '/xray?' + queryString, singbox: origin + '/singbox?' + queryString, clash: origin + '/clash?' + queryString, - surge: origin + '/surge?' + queryString + surge: origin + '/surge?' + queryString, + quanx: origin + '/quanx?' + queryString }; // Scroll to results @@ -465,7 +474,8 @@ export const formLogicFn = (t) => { xray: 'x', singbox: 'b', clash: 'c', - surge: 's' + surge: 's', + quanx: 'q' }; shortened[type] = `${origin}/${prefixMap[type]}/${returnedCode}`; @@ -511,14 +521,14 @@ export const formLogicFn = (t) => { try { const url = new URL(text); - // Check if it matches our short link pattern: /[bcxs]/[code] - const pathMatch = url.pathname.match(/^\/([bcxs])\/([a-zA-Z0-9_-]+)$/); + // Check if it matches our short link pattern: /[bcxsq]/[code] + const pathMatch = url.pathname.match(/^\/([bcxsq])\/([a-zA-Z0-9_-]+)$/); if (pathMatch) { return true; } // Check if it's a full subscription URL with query params - const fullMatch = url.pathname.match(/^\/(singbox|clash|xray|surge)$/); + const fullMatch = url.pathname.match(/^\/(singbox|clash|xray|surge|quanx)$/); if (fullMatch && url.search) { return true; } @@ -546,7 +556,7 @@ export const formLogicFn = (t) => { } // Check if it's a short link - const shortMatch = urlToParse.pathname.match(/^\/([bcxs])\/([a-zA-Z0-9_-]+)$/); + const shortMatch = urlToParse.pathname.match(/^\/([bcxsq])\/([a-zA-Z0-9_-]+)$/); if (shortMatch) { // It's a short link, resolve it first diff --git a/src/config/index.js b/src/config/index.js index 9738cc1cd..89c1fd99f 100644 --- a/src/config/index.js +++ b/src/config/index.js @@ -41,3 +41,4 @@ export { generateSubconverterConfig } from './subconverterConfig.js'; export { SING_BOX_CONFIG, SING_BOX_CONFIG_V1_11 } from './singboxConfig.js'; export { CLASH_CONFIG } from './clashConfig.js'; export { SURGE_CONFIG } from './surgeConfig.js'; +export { QUANX_CONFIG, QUANX_RESOURCE_PARSER_URL } from './quanxConfig.js'; diff --git a/src/config/quanxConfig.js b/src/config/quanxConfig.js new file mode 100644 index 000000000..82050734f --- /dev/null +++ b/src/config/quanxConfig.js @@ -0,0 +1,29 @@ +/** + * Quantumult X Configuration + * Base configuration template for Quantumult X client + */ + +// Remote rule lists are reused from the Surge rule source (2-column Surge rule-set format), +// which Quantumult X cannot read natively; the resource parser converts them on device. +export const QUANX_RESOURCE_PARSER_URL = 'https://fastly.jsdelivr.net/gh/KOP-XIAO/QuantumultX@master/Scripts/resource-parser.js'; + +// Same shape as a user base config saved via /config (see utils/quanxConfigParser.js) +export const QUANX_CONFIG = { + sections: { + general: [ + `resource_parser_url = ${QUANX_RESOURCE_PARSER_URL}`, + // Domestic probe: foreign/vendor-neutral URLs time out on some CN networks and QX then + // reports no connectivity + 'network_check_url = http://www.baidu.com/', + 'server_check_url = http://www.gstatic.com/generate_204', + 'server_check_timeout = 3000', + 'dns_exclusion_list = *.cmpassport.com, *.jegotrip.com.cn, *.icitymobile.mobi, id6.me', + 'excluded_routes = 239.255.255.250/32' + ], + dns: [ + 'no-ipv6', + 'server = 223.5.5.5', + 'server = 119.29.29.29' + ] + } +}; diff --git a/src/i18n/index.js b/src/i18n/index.js index 84ad13e51..042f69b99 100644 --- a/src/i18n/index.js +++ b/src/i18n/index.js @@ -134,7 +134,7 @@ export const translations = { }, generalSettings: '通用设置', groupByCountry: '按国家分组', - groupByCountryTip: '仅 Clash/Surge/SingBox 生效', + groupByCountryTip: '仅 Clash/Surge/SingBox/QuanX 生效', includeAutoSelect: '包含自动选择分组', UASettings: '自定义UserAgent', UAtip: '默认值curl/7.74.0', @@ -143,6 +143,7 @@ export const translations = { singboxLink: 'SingBox 链接', clashLink: 'Clash 链接', surgeLink: 'Surge 链接', + quanxLink: 'Quantumult X 链接', copied: '已复制!', shortening: '正在生成短链接...', alreadyShortened: '链接已经是短链接了!', @@ -296,7 +297,7 @@ export const translations = { }, generalSettings: 'General Settings', groupByCountry: 'Group by Country', - groupByCountryTip: 'Clash/Surge/SingBox only', + groupByCountryTip: 'Clash/Surge/SingBox/QuanX only', includeAutoSelect: 'Include Auto Select Group', UASettings: 'Custom UserAgent', UAtip: 'By default it will use curl/7.74.0', @@ -305,6 +306,7 @@ export const translations = { singboxLink: 'SingBox Link', clashLink: 'Clash Link', surgeLink: 'Surge Link', + quanxLink: 'Quantumult X Link', copied: 'Copied!', shortening: 'Shortening...', alreadyShortened: 'Links are already shortened!', @@ -452,7 +454,7 @@ export const translations = { }, generalSettings: 'تنظیمات عمومی', groupByCountry: 'گروه‌بندی بر اساس کشور', - groupByCountryTip: 'فقط Clash/Surge/SingBox', + groupByCountryTip: 'فقط Clash/Surge/SingBox/QuanX', includeAutoSelect: 'شامل گروه انتخاب خودکار', UASettings: 'UserAgent سفارشی', UAtip: 'به طور پیش‌فرض از curl/7.74.0 استفاده می‌کند', @@ -461,6 +463,7 @@ export const translations = { singboxLink: 'لینک SingBox', clashLink: 'لینک Clash', surgeLink: 'لینک Surge', + quanxLink: 'لینک Quantumult X', copied: 'کپی شد!', shortening: 'در حال کوتاه کردن...', alreadyShortened: 'لینک‌ها از قبل کوتاه شده‌اند!', @@ -608,7 +611,7 @@ export const translations = { }, generalSettings: 'Общие настройки', groupByCountry: 'Группировать по странам', - groupByCountryTip: 'Только для Clash/Surge/SingBox', + groupByCountryTip: 'Только для Clash/Surge/SingBox/QuanX', includeAutoSelect: 'Включить группу автовыбора', UASettings: 'Пользовательский UserAgent', UAtip: 'По умолчанию используется curl/7.74.0', @@ -617,6 +620,7 @@ export const translations = { singboxLink: 'Ссылка SingBox', clashLink: 'Ссылка Clash', surgeLink: 'Ссылка Surge', + quanxLink: 'Ссылка Quantumult X', copied: 'Скопировано!', shortening: 'Сокращение...', alreadyShortened: 'Ссылки уже сокращены!', diff --git a/src/parsers/ProxyParser.js b/src/parsers/ProxyParser.js index 411d74987..a0e711e59 100644 --- a/src/parsers/ProxyParser.js +++ b/src/parsers/ProxyParser.js @@ -6,6 +6,7 @@ import { parseTrojan } from './protocols/trojanParser.js'; import { parseTuic } from './protocols/tuicParser.js'; import { parseAnytls } from './protocols/anytlsParser.js'; import { fetchSubscription } from './subscription/httpSubscriptionFetcher.js'; +import { stripInvisibleChars } from '../utils.js'; const protocolParsers = { ss: parseShadowsocks, @@ -26,7 +27,7 @@ export class ProxyParser { if (!url || typeof url !== 'string') { return undefined; } - const trimmed = url.trim(); + const trimmed = stripInvisibleChars(url).trim(); const type = trimmed.split('://')[0].toLowerCase(); const parser = protocolParsers[type]; if (!parser) { diff --git a/src/parsers/convertQuanxProxyToObject.js b/src/parsers/convertQuanxProxyToObject.js new file mode 100644 index 000000000..812dcfb2b --- /dev/null +++ b/src/parsers/convertQuanxProxyToObject.js @@ -0,0 +1,140 @@ +/** + * Parse a Quantumult X server line into the internal (Sing-Box style) proxy object. + * Reference: https://github.com/crossutility/Quantumult-X/blob/master/sample.conf + * + * shadowsocks=host:port, method=..., password=..., obfs=..., tag=... + * vmess=host:port, method=..., password=, obfs=ws|wss|over-tls|http, ... + * vless=host:port, method=none, password=, obfs=..., vless-flow=..., reality-... + * trojan=host:port, password=..., over-tls=true | obfs=wss, ... + * anytls=host:port, password=..., over-tls=true, ... + */ + +// host:port right after `type=` distinguishes QX lines from Surge's `Name = type, host, port` +export const QUANX_PROXY_LINE = /^(shadowsocks|vmess|vless|trojan|anytls|http|socks5)\s*=\s*(\[[^\]]+\]|[^\s,:\[\]]+):(\d+)\s*(,|$)/i; + +function parseParams(parts) { + const params = {}; + parts.forEach(part => { + const index = part.indexOf('='); + if (index > 0) params[part.slice(0, index).trim().toLowerCase()] = part.slice(index + 1).trim(); + }); + return params; +} + +function parseBoolParam(value) { + if (value === undefined) return undefined; + return String(value).toLowerCase() === 'true'; +} + +function buildTls(params, serverName) { + const tls = { + enabled: true, + server_name: serverName, + insecure: params['tls-verification'] !== undefined && !parseBoolParam(params['tls-verification']) + }; + if (params['reality-base64-pubkey']) { + tls.reality = { + enabled: true, + public_key: params['reality-base64-pubkey'], + short_id: params['reality-hex-shortid'] + }; + // Same default the vless URI parser applies: reality requires a uTLS fingerprint in sing-box + tls.utls = { enabled: true, fingerprint: 'chrome' }; + } + return tls; +} + +// vmess/vless/trojan encode transport and TLS together in `obfs` +function buildV2rayTransport(params) { + const obfs = (params.obfs || '').toLowerCase(); + const host = params['obfs-host']; + const path = params['obfs-uri'] || '/'; + if (obfs === 'ws' || obfs === 'wss') { + return { type: 'ws', path, ...(host ? { headers: { host } } : {}) }; + } + if (obfs === 'http' || obfs.endsWith('-http')) { + return { type: 'http', method: 'GET', path: [path], ...(host ? { headers: { host: [host] } } : {}) }; + } + return undefined; +} + +function v2rayTls(params) { + const obfs = (params.obfs || '').toLowerCase(); + if (obfs !== 'wss' && obfs !== 'over-tls') return undefined; + // Sub-Store style puts SNI in tls-host; the official sample uses obfs-host for over-tls + return buildTls(params, params['tls-host'] || params['obfs-host']); +} + +const CONVERTERS = { + shadowsocks(base, params) { + if (params['ssr-protocol']) return null; // SSR has no internal representation + const proxy = { ...base, type: 'shadowsocks', method: params.method, password: params.password }; + const obfs = (params.obfs || '').toLowerCase(); + if (obfs === 'http' || obfs === 'tls') { + proxy.plugin = 'obfs'; + proxy.plugin_opts = { mode: obfs, ...(params['obfs-host'] ? { host: params['obfs-host'] } : {}), ...(params['obfs-uri'] ? { path: params['obfs-uri'] } : {}) }; + } else if (obfs === 'ws' || obfs === 'wss') { + proxy.plugin = 'v2ray-plugin'; + proxy.plugin_opts = { mode: 'websocket', path: params['obfs-uri'] || '/', ...(params['obfs-host'] ? { host: params['obfs-host'] } : {}), ...(obfs === 'wss' ? { tls: true } : {}) }; + } else if (obfs) { + return null; // e.g. ss over-tls: no equivalent outside QX + } + return proxy; + }, + vmess(base, params) { + const method = (params.method || '').toLowerCase(); + return { + ...base, + type: 'vmess', + uuid: params.password, + alter_id: params.aead !== undefined && !parseBoolParam(params.aead) ? 1 : 0, + security: ['none', 'aes-128-gcm', 'chacha20-poly1305'].includes(method) ? method : 'auto', + transport: buildV2rayTransport(params), + tls: v2rayTls(params) + }; + }, + vless(base, params) { + return { + ...base, + type: 'vless', + uuid: params.password, + transport: buildV2rayTransport(params), + tls: v2rayTls(params) || { enabled: false }, + flow: params['vless-flow'] || undefined + }; + }, + trojan(base, params) { + const ws = (params.obfs || '').toLowerCase() === 'wss'; + return { + ...base, + type: 'trojan', + password: params.password, + transport: ws ? buildV2rayTransport(params) : undefined, + tls: buildTls(params, params['tls-host'] || params['obfs-host']) + }; + }, + anytls(base, params) { + return { ...base, type: 'anytls', password: params.password, tls: buildTls(params, params['tls-host']) }; + } +}; + +export function convertQuanxProxyToObject(line) { + const match = typeof line === 'string' ? line.trim().match(QUANX_PROXY_LINE) : null; + if (!match) return null; + const kind = match[1].toLowerCase(); + const converter = CONVERTERS[kind]; + if (!converter) return null; // http/socks5 proxies are not part of the internal model + + const server = match[2].replace(/^\[|\]$/g, ''); + const port = parseInt(match[3], 10); + const params = parseParams(line.trim().slice(line.trim().indexOf(',') + 1).split(',')); + const udp = parseBoolParam(params['udp-relay']); + const base = { + tag: params.tag || `${kind} ${server}:${port}`, + server, + server_port: port, + tcp_fast_open: parseBoolParam(params['fast-open']) ?? false, + ...(udp !== undefined ? { udp } : {}) + }; + return converter(base, params); +} diff --git a/src/parsers/convertYamlProxyToObject.js b/src/parsers/convertYamlProxyToObject.js index e4bfd9073..fbab2b504 100644 --- a/src/parsers/convertYamlProxyToObject.js +++ b/src/parsers/convertYamlProxyToObject.js @@ -124,7 +124,8 @@ export function convertYamlProxyToObject(p) { }; } case 'trojan': { - const tlsEnabled = !!p.tls; + // Clash/mihomo trojan has no tls key because TLS is mandatory; only an explicit false disables it + const tlsEnabled = p.tls !== false; const reality = p['reality-opts']; const tls = tlsEnabled ? { diff --git a/src/parsers/protocols/shadowsocksParser.js b/src/parsers/protocols/shadowsocksParser.js index 11a4eb364..b80859fad 100644 --- a/src/parsers/protocols/shadowsocksParser.js +++ b/src/parsers/protocols/shadowsocksParser.js @@ -14,7 +14,7 @@ function parseServer(serverPart) { * @param {string} pluginStr - The plugin parameter value (URL decoded) * @returns {{plugin: string, plugin_opts: object}|null} - Parsed plugin info or null */ -function parsePluginString(pluginStr) { +export function parsePluginString(pluginStr) { if (!pluginStr) return null; const parts = pluginStr.split(';'); diff --git a/src/parsers/subscription/subscriptionContentParser.js b/src/parsers/subscription/subscriptionContentParser.js index 365fee646..d64b53cc6 100644 --- a/src/parsers/subscription/subscriptionContentParser.js +++ b/src/parsers/subscription/subscriptionContentParser.js @@ -2,6 +2,7 @@ import yaml from 'js-yaml'; import { deepCopy } from '../../utils.js'; import { convertYamlProxyToObject } from '../convertYamlProxyToObject.js'; import { convertSurgeProxyToObject } from '../convertSurgeProxyToObject.js'; +import { convertQuanxProxyToObject, QUANX_PROXY_LINE } from '../convertQuanxProxyToObject.js'; import { convertSurgeIniToJson } from '../../utils/surgeConfigParser.js'; /** @@ -250,6 +251,21 @@ function parseSurgeProxyGroupLine(line) { * @param {string} content - The decoded subscription content * @returns {object|string[]} - Parsed config object or array of lines */ +/** + * Quantumult X node lists (e.g. Sub-Store / miaomiaowu `?t=qx` output) or a full QX profile + * @param {string} content + * @returns {object|null} - { type: 'quanxConfig', config: null, proxies } or null if not QX + */ +export function parseQuanxNodes(content) { + const lines = content.split(/\r?\n/).map(line => line.trim()).filter(line => QUANX_PROXY_LINE.test(line)); + if (lines.length === 0) return null; + return { + type: 'quanxConfig', + config: null, + proxies: lines.map(convertQuanxProxyToObject).filter(Boolean) + }; +} + export function parseSubscriptionContent(content) { if (!content || typeof content !== 'string') { return []; @@ -278,6 +294,11 @@ export function parseSubscriptionContent(content) { return surgeResult; } + const quanxResult = parseQuanxNodes(trimmed); + if (quanxResult) { + return quanxResult; + } + // Fallback: split by lines (for URI lists) return trimmed.split('\n').filter(line => line.trim() !== ''); } diff --git a/src/services/configStorageService.js b/src/services/configStorageService.js index 81048f058..1bf9c9de2 100644 --- a/src/services/configStorageService.js +++ b/src/services/configStorageService.js @@ -1,5 +1,6 @@ import yaml from 'js-yaml'; import { generateWebPath } from '../utils.js'; +import { normalizeQuanxConfig } from '../utils/quanxConfigParser.js'; import { InvalidPayloadError, MissingDependencyError } from './errors.js'; export class ConfigStorageService { @@ -53,6 +54,14 @@ export class ConfigStorageService { return typeof content === 'object' ? JSON.stringify(content) : content; } + if (type === 'quanx') { + const parsed = normalizeQuanxConfig(content); + if (!parsed) { + throw new InvalidPayloadError('Invalid Quantumult X config: expected INI content with [section] headers'); + } + return JSON.stringify(parsed); + } + if (typeof content === 'object') { return JSON.stringify(content); } diff --git a/src/utils.js b/src/utils.js index b00f84ece..9c2d7f614 100644 --- a/src/utils.js +++ b/src/utils.js @@ -92,6 +92,21 @@ export function base64ToBinary(base64String) { return binaryString; } +// Zero-width/format characters ride along when links are copied from phones or chat apps; +// String#trim keeps U+200B and U+2060, so `\u200bvless://` would silently match no parser. +const INVISIBLE_CHARS = /[\u200B-\u200D\u2060\uFEFF]/g; + +export function stripInvisibleChars(value) { + return typeof value === 'string' ? value.replace(INVISIBLE_CHARS, '') : value; +} + +// Short, escaped preview of user input for diagnostics, so hidden characters become visible +export function previewInput(value, max = 60) { + const str = String(value ?? '').trim(); + const clipped = str.length > max ? `${str.slice(0, max)}…` : str; + return clipped.replace(/[\p{Cf}\p{Cc}]/gu, ch => `\\u${ch.codePointAt(0).toString(16).padStart(4, '0')}`); +} + export function tryDecodeSubscriptionLines(input, { decodeUriComponent = false } = {}) { if (typeof input !== 'string') { return input; diff --git a/src/utils/quanxConfigParser.js b/src/utils/quanxConfigParser.js new file mode 100644 index 000000000..adfe69bb4 --- /dev/null +++ b/src/utils/quanxConfigParser.js @@ -0,0 +1,36 @@ +// QX sections mix key=value, flag-only (e.g. `no-ipv6`) and positional lines, +// so bodies are kept as raw lines instead of being parsed into key/value maps. +export function parseQuanxIni(content) { + // Null prototype: section names come from user input (e.g. [__proto__]) + const sections = Object.create(null); + let current = null; + for (const rawLine of String(content ?? '').split(/\r?\n/)) { + const line = rawLine.trim(); + if (!line || /^(#|;|\/\/)/.test(line)) continue; + const header = line.match(/^\[([^\]]+)\]\s*(?:[;#].*)?$/); + if (header) { + current = header[1].trim().toLowerCase(); + sections[current] = sections[current] || []; + continue; + } + if (current) sections[current].push(line); + } + return Object.keys(sections).length > 0 ? { sections } : null; +} + +export function isQuanxConfig(value) { + const sections = value?.sections; + return !!sections && typeof sections === 'object' && !Array.isArray(sections) + && Object.values(sections).every(lines => Array.isArray(lines) && lines.every(line => typeof line === 'string')); +} + +// Accepts INI text or an already-structured object and always returns parser output, +// so object payloads get the same name normalization and line splitting as INI text. +export function normalizeQuanxConfig(content) { + if (typeof content === 'string') return parseQuanxIni(content); + if (!isQuanxConfig(content)) return null; + const ini = Object.entries(content.sections) + .map(([name, lines]) => [`[${name}]`, ...lines].join('\n')) + .join('\n'); + return parseQuanxIni(ini); +} diff --git a/test/nameless-link.test.js b/test/nameless-link.test.js new file mode 100644 index 000000000..3d59bf246 --- /dev/null +++ b/test/nameless-link.test.js @@ -0,0 +1,29 @@ +import { describe, it, expect } from 'vitest'; +import { createApp } from '../src/app/createApp.jsx'; +import { MemoryKVAdapter } from '../src/adapters/kv/memoryKv.js'; + +// Shape of the query a 3x-ui share link produced (values anonymized): no `#name`, a `/` before `?` +const QUERY = 'config=vless%3A%2F%2F00000000-0000-4000-8000-000000000001%40203.0.113.10%3A20443%2F%3Fencryption%3Dnone%26fp%3Dchrome%26pbk%3DTESTPUBLICKEY0000000000000000000000000000000%26security%3Dreality%26sid%3D0123456789abcd%26sni%3Dvuejs.org%26spx%3D%252F0spiderx000000%26support-x25519mlkem768%3Dtrue%26type%3Dtcp&ua=&selectedRules=%5B%22Location%3ACN%22%2C%22Private%22%2C%22Non-China%22%2C%22Github%22%2C%22Google%22%2C%22Youtube%22%2C%22AI+Services%22%2C%22Telegram%22%5D&customRules=%5B%5D&include_auto_select=false'; + +const app = () => createApp({ kv: new MemoryKVAdapter(), assetFetcher: null, logger: console, config: {} }); + +describe('share links without a #name', () => { + it('are kept for QuanX with an endpoint-based name', async () => { + const res = await app().request(`http://localhost/quanx?${QUERY}`); + expect(res.status).toBe(200); + const text = await res.text(); + expect(text).toContain('vless=203.0.113.10:20443, method=none, password=00000000-0000-4000-8000-000000000001, obfs=over-tls, tls-host=vuejs.org, reality-base64-pubkey=TESTPUBLICKEY0000000000000000000000000000000, reality-hex-shortid=0123456789abcd, udp-relay=true, tag=vless 203.0.113.10:20443'); + expect(text).toContain('static=🚀 节点选择, vless 203.0.113.10:20443, direct, reject'); + }); + + it('emit Clash REALITY options that new Xray servers accept', async () => { + const text = await (await app().request(`http://localhost/clash?${QUERY}`)).text(); + expect(text).toContain('support-x25519mlkem768: true'); + expect(text).toContain('client-fingerprint: chrome'); + }); + + it('are kept for Clash too', async () => { + const text = await (await app().request(`http://localhost/clash?${QUERY}`)).text(); + expect(text).toContain('name: vless 203.0.113.10:20443'); + }); +}); diff --git a/test/quanx-builder.test.js b/test/quanx-builder.test.js new file mode 100644 index 000000000..6b05fbf4a --- /dev/null +++ b/test/quanx-builder.test.js @@ -0,0 +1,418 @@ +import { describe, it, expect } from 'vitest'; +import { QuanxConfigBuilder } from '../src/builders/QuanxConfigBuilder.js'; +import { createApp } from '../src/app/createApp.jsx'; +import { MemoryKVAdapter } from '../src/adapters/kv/memoryKv.js'; + +const UUID = '23ad6b10-8d1a-40f7-8ad0-e3e35cd32291'; + +const vmessWs = 'vmess://' + btoa(JSON.stringify({ + v: '2', ps: 'HK-vmess', add: 'hk.example.com', port: '443', id: UUID, aid: '0', + net: 'ws', type: 'none', host: 'hk.example.com', path: '/ws', tls: 'tls', sni: 'hk.example.com' +})); + +const INPUT = [ + 'ss://' + btoa('aes-256-gcm:pass') + '@1.2.3.4:8388#JP-SS', + vmessWs, + `vless://${UUID}@5.6.7.8:443?encryption=none&security=reality&type=tcp&sni=www.apple.com&fp=chrome&pbk=PUBKEY&sid=0123abcd&flow=xtls-rprx-vision#US-VLESS`, + 'trojan://pwd@tj.example.com:443?sni=tj.example.com#SG,Trojan', + 'anytls://pw@at.example.com:443?sni=at.example.com&insecure=1#JP-AnyTLS', + 'hysteria2://pw@hy.example.com:8443?sni=hy.example.com#US-HY2', + `vless://${UUID}@g.example.com:443?security=tls&type=grpc&serviceName=x#grpc-node` +].join('\n'); + +function section(config, name) { + const match = config.match(new RegExp(`\\[${name}\\]\\n([\\s\\S]*?)(?=\\n\\n\\[|\\n?$)`)); + return match ? match[1].split('\n').filter(Boolean) : []; +} + +async function build(input = INPUT, options = {}) { + const builder = new QuanxConfigBuilder( + input, + options.selectedRules ?? 'minimal', + options.customRules ?? [], + undefined, + 'en-US', + 'curl/7.74.0', + options.groupByCountry ?? false + ); + return builder.build(); +} + +describe('QuanxConfigBuilder', () => { + it('converts supported protocols to Quantumult X server lines', async () => { + const servers = section(await build(), 'server_local'); + + expect(servers).toContain('shadowsocks=1.2.3.4:8388, method=aes-256-gcm, password=pass, udp-relay=true, tag=JP-SS'); + expect(servers).toContain(`vmess=hk.example.com:443, method=chacha20-poly1305, password=${UUID}, obfs=wss, obfs-host=hk.example.com, obfs-uri=/ws, tls-host=hk.example.com, tls-verification=true, aead=true, udp-relay=true, tag=HK-vmess`); + expect(servers).toContain(`vless=5.6.7.8:443, method=none, password=${UUID}, obfs=over-tls, tls-host=www.apple.com, reality-base64-pubkey=PUBKEY, reality-hex-shortid=0123abcd, vless-flow=xtls-rprx-vision, udp-relay=true, tag=US-VLESS`); + expect(servers).toContain('trojan=tj.example.com:443, password=pwd, over-tls=true, tls-host=tj.example.com, tls-verification=true, udp-relay=true, tag=SG,Trojan'); + expect(servers).toContain('anytls=at.example.com:443, password=pw, over-tls=true, tls-host=at.example.com, tls-verification=false, udp-relay=true, tag=JP-AnyTLS'); + }); + + it('comments out unsupported proxies and keeps them out of policies', async () => { + const config = await build(); + const servers = section(config, 'server_local'); + const policies = section(config, 'policy'); + + expect(servers).toContain('# Unsupported by Quantumult X: US-HY2 - type hysteria2'); + expect(servers).toContain('# Unsupported by Quantumult X: grpc-node - transport grpc'); + expect(policies.join('\n')).not.toContain('US-HY2'); + expect(policies.join('\n')).not.toContain('grpc-node'); + }); + + it('refuses values with commas instead of emitting a broken line', async () => { + const good = 'ss://' + btoa('aes-256-gcm:pass') + '@1.2.3.4:8388#Good'; + const config = await build([good, 'ss://' + btoa('aes-256-gcm:pa,ss') + '@1.2.3.4:8388#Bad'].join('\n')); + const servers = section(config, 'server_local'); + expect(servers).toEqual([ + 'shadowsocks=1.2.3.4:8388, method=aes-256-gcm, password=pass, udp-relay=true, tag=Good', + '# Unsupported by Quantumult X: Bad - password contains a comma or newline' + ]); + }); + + it('emits valid policies referencing existing servers and builtin policies', async () => { + const config = await build(); + const policies = section(config, 'policy'); + const serverTags = section(config, 'server_local') + .filter(line => !line.startsWith('#')) + .map(line => line.split('tag=').pop()); + const policyNames = policies.map(line => line.split('=')[1].split(',')[0].trim()); + const known = new Set([...serverTags, ...policyNames, 'direct', 'reject']); + + expect(policies[0]).toMatch(/^url-latency-benchmark=⚡ Auto Select, .*check-interval=600/); + policies.forEach(line => { + expect(line).toMatch(/^(static|url-latency-benchmark)=/); + const members = line.split(',').slice(1).map(s => s.trim()).filter(s => !s.includes('=')); + members.forEach(member => expect(known.has(member)).toBe(true)); + }); + expect(policies.join('\n')).not.toMatch(/DIRECT|REJECT/); + }); + + it('routes rules through remote lists with the resource parser and ends with final', async () => { + const config = await build(INPUT, { + customRules: [{ name: 'MyRule', domain_suffix: 'foo.com', domain_keyword: 'bar', ip_cidr: '1.1.1.0/24,2001:db8::/32', src_ip_cidr: '10.0.0.1/32', site: 'github' }] + }); + const general = section(config, 'general'); + const remote = section(config, 'filter_remote'); + const local = section(config, 'filter_local'); + + expect(general.some(line => line.startsWith('resource_parser_url = https://'))).toBe(true); + expect(remote[0]).toMatch(/geosite\/github\.conf, tag=geosite:github - MyRule, force-policy=MyRule, update-interval=86400, opt-parser=true, enabled=true$/); + remote.forEach(line => expect(line).toContain('opt-parser=true')); + // geosite lists must precede geoip lists + const firstIp = remote.findIndex(line => line.includes('/geoip/')); + expect(firstIp).toBeGreaterThan(-1); + expect(remote.slice(firstIp).every(line => line.includes('/geoip/'))).toBe(true); + + expect(local).toEqual([ + 'host-suffix, foo.com, MyRule', + 'host-keyword, bar, MyRule', + 'ip-cidr, 1.1.1.0/24, MyRule', + 'ip6-cidr, 2001:db8::/32, MyRule', + '# source IP rules are not supported by Quantumult X, skipped: 10.0.0.1/32', + 'final, 🐟 Fall Back' + ]); + }); + + it('builds country groups and points Node Select at them', async () => { + const policies = section(await build(INPUT, { groupByCountry: true }), 'policy'); + expect(policies).toContain('url-latency-benchmark=🇯🇵 Japan, JP-SS, JP-AnyTLS, check-interval=600'); + const nodeSelect = policies.find(line => line.startsWith('static=🚀 Node Select')); + expect(nodeSelect).toContain('🇯🇵 Japan'); + expect(nodeSelect).not.toContain('JP-SS'); + }); + + it('deduplicates identical nodes and renames name collisions', async () => { + const ss = 'ss://' + btoa('aes-256-gcm:pass') + '@1.2.3.4:8388#Same'; + const ss2 = 'ss://' + btoa('aes-256-gcm:other') + '@1.2.3.4:8388#Same'; + const servers = section(await build([ss, ss, ss2].join('\n')), 'server_local'); + expect(servers.map(line => line.split('tag=').pop())).toEqual(['Same', 'Same 2']); + }); + + it('keeps wss nodes whose Host header differs from the TLS SNI via tls-host', async () => { + const vmess = 'vmess://' + btoa(JSON.stringify({ + v: '2', ps: 'Mismatch', add: 'a.example.com', port: '443', id: UUID, aid: '0', + net: 'ws', host: 'cdn.example.com', path: '/ws', tls: 'tls', sni: 'a.example.com' + })); + const trojan = 'trojan://pwd@t.example.com:443?sni=t.example.com&type=ws&host=cdn.example.com&path=%2Fws#TJ-Mismatch'; + const config = await build([vmess, trojan].join('\n')); + expect(section(config, 'server_local')).toEqual([ + `vmess=a.example.com:443, method=chacha20-poly1305, password=${UUID}, obfs=wss, obfs-host=cdn.example.com, obfs-uri=/ws, tls-host=a.example.com, tls-verification=true, aead=true, udp-relay=true, tag=Mismatch`, + 'trojan=t.example.com:443, password=pwd, obfs=wss, obfs-host=cdn.example.com, obfs-uri=/ws, tls-host=t.example.com, tls-verification=true, udp-relay=true, tag=TJ-Mismatch' + ]); + }); + + it('keeps untrusted multiline values from injecting config lines', async () => { + const input = JSON.stringify({ + outbounds: [ + { type: 'shadowsocks', tag: 'BadServer', server: 'a.com\n[mitm]', server_port: 1, method: 'aes-256-gcm', password: 'p' }, + { type: 'shadowsocks', tag: 'BadMethod', server: 'b.com', server_port: 1, method: 'x\n[mitm]\nhostname = *', password: 'p' }, + { type: 'shadowsocks', tag: 'Good', server: 'c.com', server_port: 1, method: 'aes-256-gcm', password: 'p' } + ] + }); + const config = await build(input); + expect(config.match(/^\[mitm\]$/gm)).toHaveLength(1); + expect(config).not.toMatch(/^hostname/m); + expect(section(config, 'server_local')).toEqual([ + 'shadowsocks=c.com:1, method=aes-256-gcm, password=p, udp-relay=true, tag=Good', + '# Unsupported by Quantumult X: BadServer - server contains a delimiter', + '# Unsupported by Quantumult X: BadMethod - cipher x [mitm] hostname = *' + ]); + }); + + it('reads Sing-Box string plugin_opts', async () => { + const input = JSON.stringify({ + outbounds: [ + { type: 'shadowsocks', tag: 'V2P', server: 'v.com', server_port: 443, method: 'aes-256-gcm', password: 'p', plugin: 'v2ray-plugin', plugin_opts: 'mode=websocket;tls;host=cdn.example.com;path=/ws' }, + { type: 'shadowsocks', tag: 'OBFS', server: 'o.com', server_port: 443, method: 'aes-256-gcm', password: 'p', plugin: 'obfs-local', plugin_opts: 'obfs=tls;obfs-host=bing.com' } + ] + }); + const servers = section(await build(input), 'server_local'); + expect(servers).toEqual([ + 'shadowsocks=v.com:443, method=aes-256-gcm, password=p, obfs=wss, obfs-host=cdn.example.com, obfs-uri=/ws, udp-relay=true, tag=V2P', + 'shadowsocks=o.com:443, method=aes-256-gcm, password=p, obfs=tls, obfs-host=bing.com, udp-relay=true, tag=OBFS' + ]); + }); + + it('treats Clash trojan without a tls key as TLS', async () => { + const yaml = 'proxies:\n - {name: CT, type: trojan, server: t.example.com, port: 443, password: p, sni: t.example.com}\n'; + expect(section(await build(yaml), 'server_local')).toEqual([ + 'trojan=t.example.com:443, password=p, over-tls=true, tls-host=t.example.com, tls-verification=true, udp-relay=true, tag=CT' + ]); + }); + + it('references custom rule policies by their literal name', async () => { + const config = await build(INPUT, { + customRules: [ + { name: 'Work.Proxy', domain_suffix: 'work.com', site: 'github' }, + { name: 'Google', domain_suffix: 'g.com' } + ] + }); + const policies = section(config, 'policy'); + expect(policies.some(line => line.startsWith('static=Work.Proxy, '))).toBe(true); + expect(section(config, 'filter_local')).toContain('host-suffix, work.com, Work.Proxy'); + expect(section(config, 'filter_local')).toContain('host-suffix, g.com, Google'); + expect(section(config, 'filter_remote')[0]).toContain('force-policy=Work.Proxy,'); + }); + + it('drops rules of a nameless custom rule instead of emitting a policy-less line', async () => { + const config = await build(INPUT, { customRules: [{ name: '', domain_suffix: 'x.com', site: 'github' }] }); + expect(section(config, 'filter_local')).not.toContain('host-suffix, x.com, '); + section(config, 'filter_local').forEach(line => expect(line).not.toMatch(/,\s*$/)); + expect(section(config, 'filter_remote').join('\n')).not.toContain('github.conf'); + }); + + it('downgrades latency groups with a single node to static', async () => { + const input = ['ss://' + btoa('aes-256-gcm:pass') + '@1.2.3.4:8388#JP-SS', 'hysteria2://pw@hy.example.com:8443#US-HY2'].join('\n'); + const policies = section(await build(input, { groupByCountry: true }), 'policy'); + expect(policies).toContain('static=⚡ Auto Select, JP-SS'); + expect(policies).toContain('static=🇯🇵 Japan, JP-SS'); + expect(policies.join('\n')).not.toContain('url-latency-benchmark'); + }); + + it('maps the 3x-ui vision-udp443 flow to plain vision', async () => { + const link = `vless://${UUID}@1.2.3.4:443?type=tcp&security=reality&pbk=PUBKEY&fp=chrome&sni=www.tesla.com&sid=a258&flow=xtls-rprx-vision-udp443#xui`; + expect(section(await build(link), 'server_local')).toEqual([ + `vless=1.2.3.4:443, method=none, password=${UUID}, obfs=over-tls, tls-host=www.tesla.com, reality-base64-pubkey=PUBKEY, reality-hex-shortid=a258, vless-flow=xtls-rprx-vision, udp-relay=true, tag=xui` + ]); + }); + + it('parses links carrying invisible characters from copy/paste', async () => { + const link = `\u200bvless://${UUID}@1.2.3.4:443?encryption=none&fp=chrome&pbk=PUBKEY&security=reality&sid=c9c6&sni=vuejs.org&spx=%2Fa1&support-x25519mlkem768=true&type=tcp#sub\u2060-1`; + expect(section(await build(link), 'server_local')).toEqual([ + `vless=1.2.3.4:443, method=none, password=${UUID}, obfs=over-tls, tls-host=vuejs.org, reality-base64-pubkey=PUBKEY, reality-hex-shortid=c9c6, udp-relay=true, tag=sub-1` + ]); + }); + + it('lists unparsed input lines when nothing could be read', async () => { + await expect(build('vmes://broken-link')).rejects.toThrow(/Not parsed:\n- unrecognized input: vmes:\/\/broken-link/); + }); + + it('refuses to build an all-direct profile when no node is QX compatible', async () => { + const xhttp = 'vless://0e1f2a3b-1111-2222-3333-444455556666@1.2.3.4:443?type=xhttp&path=%2F&security=reality&pbk=abc&sni=a.com#xui-xhttp'; + await expect(build(xhttp)).rejects.toThrow(/No Quantumult X compatible nodes[\s\S]*xui-xhttp - transport xhttp/); + }); +}); + +describe('/quanx route', () => { + const createTestApp = () => createApp({ + kv: new MemoryKVAdapter(), + assetFetcher: null, + logger: console, + config: { configTtlSeconds: 60, shortLinkTtlSeconds: null } + }); + + it('returns a Quantumult X profile', async () => { + const app = createTestApp(); + const res = await app.request(`http://localhost/quanx?config=${encodeURIComponent(INPUT)}`); + expect(res.status).toBe(200); + const text = await res.text(); + expect(text).toContain('[server_local]'); + expect(text).toContain('tag=JP-SS'); + }); + + it('serves bare node lines with list=true', async () => { + const res = await createTestApp().request(`http://localhost/quanx?list=true&config=${encodeURIComponent(INPUT)}`); + expect(res.status).toBe(200); + const lines = (await res.text()).trim().split('\n'); + expect(lines[0]).toBe('shadowsocks=1.2.3.4:8388, method=aes-256-gcm, password=pass, udp-relay=true, tag=JP-SS'); + expect(lines.every(line => /^(shadowsocks|vmess|vless|trojan|anytls)=|^# Unsupported/.test(line))).toBe(true); + }); + + it('answers 400 with reasons instead of an all-direct profile', async () => { + const grpc = 'vless://0e1f2a3b-1111-2222-3333-444455556666@1.2.3.4:443?type=grpc&serviceName=x&security=reality&pbk=abc&sni=a.com#xui-grpc'; + for (const extra of ['', '&list=true']) { + const res = await createTestApp().request(`http://localhost/quanx?config=${encodeURIComponent(grpc)}${extra}`); + expect(res.status).toBe(400); + expect(await res.text()).toContain('xui-grpc - transport grpc'); + } + }); + + it('fetches subscriptions with a Clash UA instead of curl or the QX app UA', async () => { + const seen = []; + const fetchMock = async (url, init) => { + seen.push(init?.headers?.get?.('User-Agent')); + return { ok: true, status: 200, text: async () => 'ss://' + btoa('aes-256-gcm:pass') + '@1.2.3.4:8388#JP-SS', headers: { get: () => null } }; + }; + const original = globalThis.fetch; + globalThis.fetch = fetchMock; + try { + const res = await createTestApp().request(`http://localhost/quanx?config=${encodeURIComponent('https://sub.example.com/s')}`, { + headers: { 'User-Agent': 'Quantumult%20X/1.5.5' } + }); + expect(res.status).toBe(200); + } finally { + globalThis.fetch = original; + } + expect(seen).toEqual(['clash.meta']); + }); + + it('requires the config parameter', async () => { + const res = await createTestApp().request('http://localhost/quanx'); + expect(res.status).toBe(400); + }); + + it('supports q/ short links', async () => { + const app = createTestApp(); + const query = `?config=${encodeURIComponent(INPUT)}`; + const code = await (await app.request(`http://localhost/shorten-v2?url=${encodeURIComponent('http://localhost/quanx' + query)}`)).text(); + + const redirect = await app.request(`http://localhost/q/${code}`); + expect(redirect.status).toBe(302); + expect(redirect.headers.get('location')).toBe(`http://localhost/quanx${query}`); + + const resolved = await app.request(`http://localhost/resolve?url=${encodeURIComponent(`http://localhost/q/${code}`)}`); + expect((await resolved.json()).originalUrl).toBe(`http://localhost/quanx${query}`); + }); +}); + +describe('Quantumult X base config', () => { + const createTestApp = () => createApp({ + kv: new MemoryKVAdapter(), + assetFetcher: null, + logger: console, + config: { configTtlSeconds: 60, shortLinkTtlSeconds: null } + }); + + const USER_PROFILE = `; my profile +[general] +server_check_url = http://cp.cloudflare.com/generate_204 +profile_img_url = http://example.com/a.png + +[dns] +server = 8.8.8.8 + +[policy] +static=Old, direct + +[filter_local] +host, evil.com, Old +final, Old + +[rewrite_remote] +https://example.com/rewrite.snippet, tag=MyRewrite, enabled=true + +[task_local] +0 9 * * * https://example.com/task.js, tag=Task, enabled=true + +[mitm] +hostname = *.example.com +`; + + it('saves an INI profile and applies it to /quanx via configId', async () => { + const app = createTestApp(); + const save = await app.request('http://localhost/config', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ type: 'quanx', content: USER_PROFILE }) + }); + expect(save.status).toBe(200); + const configId = await save.text(); + expect(configId).toMatch(/^quanx_/); + + const res = await app.request(`http://localhost/quanx?config=${encodeURIComponent(INPUT)}&configId=${configId}`); + expect(res.status).toBe(200); + const text = await res.text(); + const general = section(text, 'general'); + + // user keys win, defaults the user omitted are kept + expect(general).toContain('server_check_url = http://cp.cloudflare.com/generate_204'); + expect(general).not.toContain('server_check_url = http://www.gstatic.com/generate_204'); + expect(general).toContain('profile_img_url = http://example.com/a.png'); + expect(general.some(line => line.startsWith('resource_parser_url = '))).toBe(true); + + expect(section(text, 'dns')).toEqual(['server = 8.8.8.8']); + expect(section(text, 'rewrite_remote')).toEqual(['https://example.com/rewrite.snippet, tag=MyRewrite, enabled=true']); + expect(section(text, 'task_local')).toEqual(['0 9 * * * https://example.com/task.js, tag=Task, enabled=true']); + expect(section(text, 'mitm')).toEqual(['hostname = *.example.com']); + + // generated sections are never taken from the base config + expect(text).not.toContain('static=Old'); + expect(text).not.toContain('evil.com'); + expect(section(text, 'server_local').some(line => line.endsWith('tag=JP-SS'))).toBe(true); + expect(text.match(/^\[general\]$/gm)).toHaveLength(1); + }); + + it('rejects content without any [section]', async () => { + const res = await createTestApp().request('http://localhost/config', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ type: 'quanx', content: 'just some text' }) + }); + expect(res.status).toBe(400); + }); + + it('ignores configIds saved for other clients', async () => { + const app = createTestApp(); + const save = await app.request('http://localhost/config', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ type: 'clash', content: 'port: 7890' }) + }); + const configId = await save.text(); + const text = await (await app.request(`http://localhost/quanx?config=${encodeURIComponent(INPUT)}&configId=${configId}`)).text(); + expect(section(text, 'general').some(line => line.startsWith('resource_parser_url = '))).toBe(true); + expect(text).not.toContain('7890'); + }); +}); + +describe('Quantumult X base config parsing', () => { + it('normalizes object payloads like INI text', async () => { + const { normalizeQuanxConfig } = await import('../src/utils/quanxConfigParser.js'); + const parsed = normalizeQuanxConfig({ + sections: { ' Policy ': ['static=X, direct'], rewrite_local: ['a\n[filter_local]\nfinal, direct'] } + }); + expect(Object.keys(parsed.sections).sort()).toEqual(['filter_local', 'policy', 'rewrite_local']); + expect(parsed.sections.rewrite_local).toEqual(['a']); + }); + + it('recognizes headers with trailing comments and keeps __proto__ inert', async () => { + const { parseQuanxIni } = await import('../src/utils/quanxConfigParser.js'); + const parsed = parseQuanxIni('[mitm] ; certs\nhostname = a.com\n[__proto__]\nx'); + expect(parsed.sections.mitm).toEqual(['hostname = a.com']); + const builder = new QuanxConfigBuilder(INPUT, 'minimal', [], JSON.parse(JSON.stringify(parsed)), 'en-US', 'curl/7.74.0', false); + const config = await builder.build(); + expect(section(config, 'mitm')).toEqual(['hostname = a.com']); + expect(section(config, 'policy').length).toBeGreaterThan(0); + }); +}); diff --git a/test/quanx-input-parsing.test.js b/test/quanx-input-parsing.test.js new file mode 100644 index 000000000..3d21f325a --- /dev/null +++ b/test/quanx-input-parsing.test.js @@ -0,0 +1,63 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import yaml from 'js-yaml'; +import { ClashConfigBuilder } from '../src/builders/ClashConfigBuilder.js'; +import { QuanxConfigBuilder } from '../src/builders/QuanxConfigBuilder.js'; +import { convertQuanxProxyToObject } from '../src/parsers/convertQuanxProxyToObject.js'; + +const UUID = '00000000-a7d7-4154-b280-6e36d5941daa'; +// Shape of a Sub-Store / miaomiaowu `?t=qx` node list +const QX_LIST = [ + 'shadowsocks=115.0.0.1:18014,method=chacha20-ietf-poly1305,password=fake,udp-relay=true,tag=🇯🇵 nuro-家宽', + 'shadowsocks=hk.example.com:61870,method=2022-blake3-aes-256-gcm,password=AAAA=:BBBB=,udp-relay=true,tag=🇭🇰 vmiss·SS', + `vless=hk.example.com:61850,method=none,password=${UUID},obfs=over-tls,tls-host=www.tesla.com,vless-flow=xtls-rprx-vision,udp-relay=true,tag=🇭🇰 vmiss,reality-base64-pubkey=PUBKEY,reality-hex-shortid=a258`, + `vmess=v.example.com:443,method=chacha20-poly1305,password=${UUID},obfs=wss,obfs-host=cdn.example.com,obfs-uri=/ws,tls-host=v.example.com,aead=true,tag=VM`, + 'trojan=t.example.com:443,password=pwd,over-tls=true,tls-host=t.example.com,tls-verification=false,tag=TJ', + 'http=h.example.com:80,username=u,password=p,tag=HTTP-ignored' +].join('\n'); + +const servers = (config) => (config.match(/\[server_local\]\n([\s\S]*?)(?=\n\n\[|\n?$)/)?.[1] || '').split('\n').filter(Boolean); + +describe('Quantumult X node lines as input', () => { + afterEach(() => vi.unstubAllGlobals()); + + it('converts a QX node line into the internal object', () => { + expect(convertQuanxProxyToObject(QX_LIST.split('\n')[2])).toMatchObject({ + type: 'vless', tag: '🇭🇰 vmiss', server: 'hk.example.com', server_port: 61850, uuid: UUID, udp: true, + flow: 'xtls-rprx-vision', + tls: { enabled: true, server_name: 'www.tesla.com', reality: { enabled: true, public_key: 'PUBKEY', short_id: 'a258' } } + }); + expect(convertQuanxProxyToObject('Name = vmess, host, 443, username=x')).toBeNull(); + expect(convertQuanxProxyToObject('http=h.example.com:80,tag=x')).toBeNull(); + }); + + it('feeds QX node lists into the Clash builder', async () => { + const builder = new ClashConfigBuilder(QX_LIST, 'minimal', [], null, 'en-US', 'curl/7.74.0'); + const config = yaml.load(await builder.build()); + const byName = Object.fromEntries(config.proxies.map(p => [p.name, p])); + expect(Object.keys(byName)).toEqual(['🇯🇵 nuro-家宽', '🇭🇰 vmiss·SS', '🇭🇰 vmiss', 'VM', 'TJ']); + expect(byName['🇭🇰 vmiss']).toMatchObject({ type: 'vless', flow: 'xtls-rprx-vision', 'reality-opts': { 'public-key': 'PUBKEY', 'short-id': 'a258' } }); + expect(byName.VM).toMatchObject({ type: 'vmess', network: 'ws', tls: true, servername: 'v.example.com' }); + expect(byName.TJ).toMatchObject({ type: 'trojan', 'skip-cert-verify': true }); + }); + + it('round-trips QX node lists through the QuanX builder', async () => { + const builder = new QuanxConfigBuilder(QX_LIST, 'minimal', [], undefined, 'en-US', 'curl/7.74.0', false); + const lines = servers(await builder.build()); + expect(lines).toContain(`vless=hk.example.com:61850, method=none, password=${UUID}, obfs=over-tls, tls-host=www.tesla.com, reality-base64-pubkey=PUBKEY, reality-hex-shortid=a258, vless-flow=xtls-rprx-vision, udp-relay=true, tag=🇭🇰 vmiss`); + expect(lines).toContain('shadowsocks=hk.example.com:61870, method=2022-blake3-aes-256-gcm, password=AAAA=:BBBB=, udp-relay=true, tag=🇭🇰 vmiss·SS'); + expect(lines.length).toBe(5); + }); + + it('parses a fetched QX subscription', async () => { + vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, text: async () => QX_LIST, headers: { get: () => null } }))); + const builder = new ClashConfigBuilder('https://sub.example.com/api?t=qx', 'minimal', [], null, 'en-US', 'curl/7.74.0'); + const config = yaml.load(await builder.build()); + expect(config.proxies).toHaveLength(5); + }); + + it('explains a fetched subscription that yields no nodes', async () => { + vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, text: async () => 'login', headers: { get: () => null } }))); + const builder = new QuanxConfigBuilder('https://sub.example.com/sub', 'minimal', [], undefined, 'en-US', 'curl/7.74.0', false); + await expect(builder.build()).rejects.toThrow(/subscription returned no usable nodes: https:\/\/sub\.example\.com\/sub \(content starts with: login<\/html>\)/); + }); +});