From 8ffb62f2d725baac761826203b44f841d2959e65 Mon Sep 17 00:00:00 2001 From: xream Date: Sun, 19 Apr 2026 08:19:01 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=8C=E5=96=84=20VLESS=20URI=20?= =?UTF-8?q?=E8=BD=AC=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/package.json | 2 +- backend/src/core/proxy-utils/index.js | 41 + backend/src/core/proxy-utils/parsers/index.js | 826 ++++++++++-- .../src/core/proxy-utils/processors/index.js | 10 +- .../core/proxy-utils/producers/clashmeta.js | 9 + backend/src/core/proxy-utils/producers/uri.js | 484 ++++--- backend/src/core/proxy-utils/xhttp-utils.js | 108 +- .../proxy-parsers/v2ray-and-platforms.spec.js | 548 +++++++- .../test/proxy-producers/structured.spec.js | 32 + backend/src/test/proxy-producers/text.spec.js | 1114 +++++++++++++++-- scripts/demo.js | 2 +- 11 files changed, 2807 insertions(+), 369 deletions(-) diff --git a/backend/package.json b/backend/package.json index 4a733feb..537e462c 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.22.1", + "version": "2.22.2", "description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.", "main": "src/main.js", "scripts": { diff --git a/backend/src/core/proxy-utils/index.js b/backend/src/core/proxy-utils/index.js index 75c68003..8d9936c5 100644 --- a/backend/src/core/proxy-utils/index.js +++ b/backend/src/core/proxy-utils/index.js @@ -283,6 +283,47 @@ function produce(proxies, targetPlatform, type, opts = {}) { if (!isProxyUUIDValid) $.info(`UUID may be invalid: ${proxy.name} ${proxy.uuid}`); // return isProxyUUIDValid; + const isVlessType = proxy.type === 'vless'; + const realityChecks = isVlessType + ? [ + ['reality-opts', proxy['reality-opts']], + [ + 'xhttp download-settings reality-opts', + proxy['xhttp-opts']?.['download-settings']?.[ + 'reality-opts' + ], + ], + ] + : []; + for (const [realityLabel, realityOpts] of realityChecks) { + if (realityOpts && !isNotBlank(realityOpts['public-key'])) { + // Intentional: a VLESS Reality node without public-key is + // not a valid Mihomo export or regenerated share link. We + // keep the marker while parsing so callers can inspect the + // broken config, then stop export here instead of silently + // emitting invalid Reality output. + $.error( + `Skipping VLESS Reality proxy ${proxy.name}: empty ${realityLabel}.public-key`, + ); + return false; + } + } + + const xhttpOpts = proxy['xhttp-opts']; + if ( + isVlessType && + proxy.network === 'xhttp' && + xhttpOpts?.mode === 'stream-one' && + xhttpOpts['download-settings'] + ) { + // Match Mihomo's outbound validation: xhttp download-settings + // require split transports, so stream-one is rejected instead + // of emitting a config/share link that Mihomo will not accept. + $.error( + `Skipping VLESS xhttp proxy ${proxy.name}: mode "stream-one" cannot be used with download-settings`, + ); + return false; + } } return true; diff --git a/backend/src/core/proxy-utils/parsers/index.js b/backend/src/core/proxy-utils/parsers/index.js index 5ffc5034..1b2783e6 100644 --- a/backend/src/core/proxy-utils/parsers/index.js +++ b/backend/src/core/proxy-utils/parsers/index.js @@ -18,7 +18,12 @@ import YAML from '@/utils/yaml'; import _ from 'lodash'; import { Base64 } from 'js-base64'; -import { normalizeXhttpScalarUpperBound } from '../xhttp-utils'; +import { + normalizeXhttpIntegerValue, + normalizeXhttpNonNegativeRange, + normalizeXhttpPositiveRange, + normalizeXhttpScalarUpperBound, +} from '../xhttp-utils'; function surge_port_hopping(raw) { const [parts, port_hopping] = @@ -37,8 +42,7 @@ function splitURIFragment(raw) { const [__, content, fragment] = /^(.*?)(?:#(.*?))?$/.exec(raw); return { content, - fragment: - fragment != null ? decodeURIComponent(fragment) : undefined, + fragment: fragment != null ? decodeURIComponent(fragment) : undefined, }; } @@ -56,7 +60,11 @@ function parseWireGuardURIAddressValue(value) { return parsed; }; if (isIPv4(host)) { - return { family: 'ipv4', address: host, cidr: normalizeCIDR(cidrRaw, 32) }; + return { + family: 'ipv4', + address: host, + cidr: normalizeCIDR(cidrRaw, 32), + }; } if (isIPv6(host)) { return { @@ -752,46 +760,676 @@ function URI_VLESS() { }; for (const [sourceKey, targetKey] of Object.entries(xmuxFieldMap)) { - const value = xmux[sourceKey]; - if (typeof value === 'string' && value !== '') { - reuseSettings[targetKey] = value; - } else if ( - typeof value === 'number' && - Number.isFinite(value) - ) { - reuseSettings[targetKey] = `${value}`; + const normalizedValue = normalizeXhttpNonNegativeRange( + xmux[sourceKey], + ); + if (normalizedValue != null) { + reuseSettings[targetKey] = + typeof normalizedValue === 'number' + ? `${normalizedValue}` + : normalizedValue; } } + const hKeepAlivePeriod = normalizeXhttpIntegerValue( + xmux.hKeepAlivePeriod, + ); + if (hKeepAlivePeriod != null) { + reuseSettings['h-keep-alive-period'] = hKeepAlivePeriod; + } + return Object.keys(reuseSettings).length > 0 ? reuseSettings : undefined; }; + const toStringHeaderMap = (headers) => { + if (!isPlainObject(headers)) { + return undefined; + } + + const parsedHeaders = {}; + for (const [key, value] of Object.entries(headers)) { + if (typeof value === 'string' && value !== '') { + parsedHeaders[key] = value; + } + } + + return Object.keys(parsedHeaders).length > 0 + ? parsedHeaders + : undefined; + }; + + const cloneUnsupportedXhttpValue = (value) => { + if (Array.isArray(value)) { + return value.map(cloneUnsupportedXhttpValue); + } + + if (isPlainObject(value)) { + const clonedValue = {}; + for (const [key, entryValue] of Object.entries(value)) { + clonedValue[key] = cloneUnsupportedXhttpValue(entryValue); + } + return clonedValue; + } + + return value; + }; + + const compactUnsupportedXhttpValue = (value) => { + if (Array.isArray(value)) { + return value + .map(compactUnsupportedXhttpValue) + .filter((entryValue) => entryValue !== undefined); + } + + if (!isPlainObject(value)) { + return value; + } + + const compactedValue = {}; + for (const [key, entryValue] of Object.entries(value)) { + const compactedEntryValue = + compactUnsupportedXhttpValue(entryValue); + if (compactedEntryValue !== undefined) { + compactedValue[key] = compactedEntryValue; + } + } + + return Object.keys(compactedValue).length > 0 + ? compactedValue + : undefined; + }; + + const setUnsupportedXhttpField = (target, key, value) => { + const normalizedValue = compactUnsupportedXhttpValue( + cloneUnsupportedXhttpValue(value), + ); + if (normalizedValue !== undefined) { + target[key] = normalizedValue; + } + }; + + const collectUnsupportedXhttpHeaders = (headers) => { + if (headers == null) { + return undefined; + } + + if (!isPlainObject(headers)) { + return cloneUnsupportedXhttpValue(headers); + } + + const unsupportedHeaders = {}; + for (const [key, value] of Object.entries(headers)) { + if (typeof value === 'string' && value !== '') { + continue; + } + + setUnsupportedXhttpField(unsupportedHeaders, key, value); + } + + return compactUnsupportedXhttpValue(unsupportedHeaders); + }; + + const isSupportedXmuxFieldValue = (key, value) => { + if ( + [ + 'maxConnections', + 'maxConcurrency', + 'cMaxReuseTimes', + 'hMaxRequestTimes', + 'hMaxReusableSecs', + ].includes(key) + ) { + return normalizeXhttpNonNegativeRange(value) != null; + } + + if (key === 'hKeepAlivePeriod') { + return normalizeXhttpIntegerValue(value) != null; + } + + return false; + }; + + const collectUnsupportedXmux = (xmux) => { + if (xmux == null) { + return undefined; + } + + if (!isPlainObject(xmux)) { + return cloneUnsupportedXhttpValue(xmux); + } + + const unsupportedXmux = {}; + for (const [key, value] of Object.entries(xmux)) { + if (isSupportedXmuxFieldValue(key, value)) { + continue; + } + + setUnsupportedXhttpField(unsupportedXmux, key, value); + } + + return compactUnsupportedXhttpValue(unsupportedXmux); + }; + + const collectUnsupportedXhttpExtra = (extra) => { + if (extra == null) { + return undefined; + } + + if (!isPlainObject(extra)) { + return cloneUnsupportedXhttpValue(extra); + } + + const unsupportedExtra = {}; + for (const [key, value] of Object.entries(extra)) { + switch (key) { + case 'headers': { + const unsupportedHeaders = + collectUnsupportedXhttpHeaders(value); + if (unsupportedHeaders !== undefined) { + unsupportedExtra.headers = unsupportedHeaders; + } + break; + } + case 'noGRPCHeader': + case 'xPaddingObfsMode': + if (value !== true) { + setUnsupportedXhttpField( + unsupportedExtra, + key, + value, + ); + } + break; + case 'xPaddingBytes': + case 'xPaddingKey': + case 'xPaddingHeader': + case 'xPaddingPlacement': + case 'xPaddingMethod': + case 'uplinkHTTPMethod': + case 'sessionPlacement': + case 'sessionKey': + case 'seqPlacement': + case 'seqKey': + case 'uplinkDataPlacement': + case 'uplinkDataKey': + if (!isNotBlank(value)) { + setUnsupportedXhttpField( + unsupportedExtra, + key, + value, + ); + } + break; + case 'uplinkChunkSize': + if (normalizeXhttpNonNegativeRange(value) == null) { + setUnsupportedXhttpField( + unsupportedExtra, + key, + value, + ); + } + break; + case 'scMaxEachPostBytes': + if (normalizeXhttpScalarUpperBound(value) == null) { + setUnsupportedXhttpField( + unsupportedExtra, + key, + value, + ); + } + break; + case 'scMinPostsIntervalMs': + if (normalizeXhttpPositiveRange(value) == null) { + setUnsupportedXhttpField( + unsupportedExtra, + key, + value, + ); + } + break; + case 'xmux': { + const unsupportedXmux = collectUnsupportedXmux(value); + if (unsupportedXmux !== undefined) { + unsupportedExtra.xmux = unsupportedXmux; + } + break; + } + default: + setUnsupportedXhttpField(unsupportedExtra, key, value); + break; + } + } + + return compactUnsupportedXhttpValue(unsupportedExtra); + }; + + const collectUnsupportedNestedXhttpSettings = (xhttpSettings) => { + if (xhttpSettings == null) { + return undefined; + } + + if (!isPlainObject(xhttpSettings)) { + return cloneUnsupportedXhttpValue(xhttpSettings); + } + + const unsupportedXhttpSettings = {}; + if ( + Object.prototype.hasOwnProperty.call(xhttpSettings, 'path') && + !isNotBlank(xhttpSettings.path) + ) { + setUnsupportedXhttpField( + unsupportedXhttpSettings, + 'path', + xhttpSettings.path, + ); + } + if ( + Object.prototype.hasOwnProperty.call(xhttpSettings, 'host') && + !isNotBlank(xhttpSettings.host) + ) { + setUnsupportedXhttpField( + unsupportedXhttpSettings, + 'host', + xhttpSettings.host, + ); + } + + const inlineExtra = {}; + for (const [key, value] of Object.entries(xhttpSettings)) { + if (['path', 'host', 'extra'].includes(key)) { + continue; + } + inlineExtra[key] = value; + } + + const unsupportedInlineExtra = + collectUnsupportedXhttpExtra(inlineExtra); + if (isPlainObject(unsupportedInlineExtra)) { + Object.assign(unsupportedXhttpSettings, unsupportedInlineExtra); + } + + if (Object.prototype.hasOwnProperty.call(xhttpSettings, 'extra')) { + const unsupportedExtra = collectUnsupportedXhttpExtra( + xhttpSettings.extra, + ); + if (unsupportedExtra !== undefined) { + unsupportedXhttpSettings.extra = unsupportedExtra; + } + } + + return compactUnsupportedXhttpValue(unsupportedXhttpSettings); + }; + + const collectUnsupportedDownloadSettings = (downloadSettings) => { + if (downloadSettings == null) { + return undefined; + } + + if (!isPlainObject(downloadSettings)) { + return cloneUnsupportedXhttpValue(downloadSettings); + } + + const unsupportedDownloadSettings = {}; + for (const [key, value] of Object.entries(downloadSettings)) { + switch (key) { + case 'address': + if (!isNotBlank(value)) { + setUnsupportedXhttpField( + unsupportedDownloadSettings, + key, + value, + ); + } + break; + case 'port': + if ( + normalizeXhttpIntegerValue(value, { + allowNegative: false, + }) == null + ) { + setUnsupportedXhttpField( + unsupportedDownloadSettings, + key, + value, + ); + } + break; + case 'security': { + const normalizedSecurity = + typeof value === 'string' ? value.toLowerCase() : ''; + if (!['tls', 'reality'].includes(normalizedSecurity)) { + setUnsupportedXhttpField( + unsupportedDownloadSettings, + key, + value, + ); + } + break; + } + case 'tlsSettings': { + if (!isPlainObject(value)) { + setUnsupportedXhttpField( + unsupportedDownloadSettings, + key, + value, + ); + break; + } + + const unsupportedTlsSettings = {}; + for (const [tlsKey, tlsValue] of Object.entries(value)) { + switch (tlsKey) { + case 'serverName': + case 'fingerprint': + case 'echConfigList': + if (!isNotBlank(tlsValue)) { + setUnsupportedXhttpField( + unsupportedTlsSettings, + tlsKey, + tlsValue, + ); + } + break; + case 'alpn': + if ( + !( + Array.isArray(tlsValue) && + tlsValue.length > 0 && + tlsValue.every( + (item) => + typeof item === 'string' && + item !== '', + ) + ) + ) { + setUnsupportedXhttpField( + unsupportedTlsSettings, + tlsKey, + tlsValue, + ); + } + break; + case 'allowInsecure': + if (tlsValue !== true) { + setUnsupportedXhttpField( + unsupportedTlsSettings, + tlsKey, + tlsValue, + ); + } + break; + default: + setUnsupportedXhttpField( + unsupportedTlsSettings, + tlsKey, + tlsValue, + ); + break; + } + } + + const compactedTlsSettings = + compactUnsupportedXhttpValue( + unsupportedTlsSettings, + ); + if (compactedTlsSettings !== undefined) { + unsupportedDownloadSettings.tlsSettings = + compactedTlsSettings; + } + break; + } + case 'realitySettings': { + if (!isPlainObject(value)) { + setUnsupportedXhttpField( + unsupportedDownloadSettings, + key, + value, + ); + break; + } + + const unsupportedRealitySettings = {}; + for (const [realityKey, realityValue] of Object.entries( + value, + )) { + switch (realityKey) { + case 'publicKey': + case 'shortId': + case 'serverName': + case 'fingerprint': + if (!isNotBlank(realityValue)) { + setUnsupportedXhttpField( + unsupportedRealitySettings, + realityKey, + realityValue, + ); + } + break; + default: + setUnsupportedXhttpField( + unsupportedRealitySettings, + realityKey, + realityValue, + ); + break; + } + } + + const compactedRealitySettings = + compactUnsupportedXhttpValue( + unsupportedRealitySettings, + ); + if (compactedRealitySettings !== undefined) { + unsupportedDownloadSettings.realitySettings = + compactedRealitySettings; + } + break; + } + case 'xhttpSettings': { + const unsupportedXhttpSettings = + collectUnsupportedNestedXhttpSettings(value); + if (unsupportedXhttpSettings !== undefined) { + unsupportedDownloadSettings.xhttpSettings = + unsupportedXhttpSettings; + } + break; + } + case 'network': { + const normalizedNetwork = + typeof value === 'string' ? value.toLowerCase() : ''; + if ( + normalizedNetwork !== 'xhttp' && + normalizedNetwork !== 'splithttp' + ) { + setUnsupportedXhttpField( + unsupportedDownloadSettings, + key, + value, + ); + } + break; + } + default: + setUnsupportedXhttpField( + unsupportedDownloadSettings, + key, + value, + ); + break; + } + } + + return compactUnsupportedXhttpValue(unsupportedDownloadSettings); + }; + + const collectUnsupportedRootXhttpExtra = ( + extra, + { parsedDownloadSettings } = {}, + ) => { + if (!isPlainObject(extra)) { + return undefined; + } + + const { + downloadSettings: rawDownloadSettings, + ...rootInlineExtra + } = extra; + + const unsupportedExtra = + collectUnsupportedXhttpExtra(rootInlineExtra) || {}; + + if ( + Object.prototype.hasOwnProperty.call(extra, 'downloadSettings') + ) { + const unsupportedDownloadSettings = + collectUnsupportedDownloadSettings(rawDownloadSettings); + if (unsupportedDownloadSettings !== undefined) { + unsupportedExtra.downloadSettings = + unsupportedDownloadSettings; + } + } + + return compactUnsupportedXhttpValue(unsupportedExtra); + }; + + const applyXhttpExtraFields = (target, extra) => { + if (!isPlainObject(target) || !isPlainObject(extra)) { + return; + } + + const parsedHeaders = toStringHeaderMap(extra.headers); + if (parsedHeaders) { + const headers = { ...(target.headers || {}) }; + for (const [key, value] of Object.entries(parsedHeaders)) { + if (/^host$/i.test(key)) { + if ( + !Object.prototype.hasOwnProperty.call( + headers, + 'Host', + ) && + !Object.prototype.hasOwnProperty.call( + headers, + 'host', + ) + ) { + headers.Host = value; + } + continue; + } + headers[key] = value; + } + if (Object.keys(headers).length > 0) { + target.headers = headers; + } + } + + if (extra.noGRPCHeader === true) { + target['no-grpc-header'] = true; + } + if (isNotBlank(extra.xPaddingBytes)) { + target['x-padding-bytes'] = extra.xPaddingBytes; + } + if (extra.xPaddingObfsMode === true) { + target['x-padding-obfs-mode'] = true; + } + if (isNotBlank(extra.xPaddingKey)) { + target['x-padding-key'] = extra.xPaddingKey; + } + if (isNotBlank(extra.xPaddingHeader)) { + target['x-padding-header'] = extra.xPaddingHeader; + } + if (isNotBlank(extra.xPaddingPlacement)) { + target['x-padding-placement'] = extra.xPaddingPlacement; + } + if (isNotBlank(extra.xPaddingMethod)) { + target['x-padding-method'] = extra.xPaddingMethod; + } + if (isNotBlank(extra.uplinkHTTPMethod)) { + target['uplink-http-method'] = extra.uplinkHTTPMethod; + } + if (isNotBlank(extra.sessionPlacement)) { + target['session-placement'] = extra.sessionPlacement; + } + if (isNotBlank(extra.sessionKey)) { + target['session-key'] = extra.sessionKey; + } + if (isNotBlank(extra.seqPlacement)) { + target['seq-placement'] = extra.seqPlacement; + } + if (isNotBlank(extra.seqKey)) { + target['seq-key'] = extra.seqKey; + } + if (isNotBlank(extra.uplinkDataPlacement)) { + target['uplink-data-placement'] = extra.uplinkDataPlacement; + } + if (isNotBlank(extra.uplinkDataKey)) { + target['uplink-data-key'] = extra.uplinkDataKey; + } + + const uplinkChunkSize = normalizeXhttpNonNegativeRange( + extra.uplinkChunkSize, + ); + if (uplinkChunkSize != null) { + target['uplink-chunk-size'] = uplinkChunkSize; + } + + const scMaxEachPostBytes = normalizeXhttpScalarUpperBound( + extra.scMaxEachPostBytes, + ); + if (scMaxEachPostBytes != null) { + target['sc-max-each-post-bytes'] = scMaxEachPostBytes; + } + + const scMinPostsIntervalMs = normalizeXhttpPositiveRange( + extra.scMinPostsIntervalMs, + ); + if (scMinPostsIntervalMs != null) { + target['sc-min-posts-interval-ms'] = scMinPostsIntervalMs; + } + + const reuseSettings = mapXmuxToReuseSettings(extra.xmux); + if (reuseSettings) { + target['reuse-settings'] = reuseSettings; + } + }; + const parseDownloadSettings = (downloadSettings) => { if (!isPlainObject(downloadSettings)) { return undefined; } const parsedDownloadSettings = {}; + const downloadNetwork = + typeof downloadSettings.network === 'string' + ? downloadSettings.network.toLowerCase() + : ''; + if ( + downloadNetwork === 'xhttp' || + downloadNetwork === 'splithttp' + ) { + parsedDownloadSettings.network = 'xhttp'; + } if (isNotBlank(downloadSettings.address)) { parsedDownloadSettings.server = downloadSettings.address; } - if ( - typeof downloadSettings.port === 'number' && - Number.isFinite(downloadSettings.port) - ) { - parsedDownloadSettings.port = parseInt( - `${downloadSettings.port}`, - 10, - ); + const parsedPort = normalizeXhttpIntegerValue( + downloadSettings.port, + { + allowNegative: false, + }, + ); + if (parsedPort != null) { + parsedDownloadSettings.port = parsedPort; } - if ( - typeof downloadSettings.security === 'string' && - downloadSettings.security.toLowerCase() === 'tls' - ) { + const downloadSecurity = + typeof downloadSettings.security === 'string' + ? downloadSettings.security.toLowerCase() + : ''; + if (downloadSecurity === 'tls' || downloadSecurity === 'reality') { parsedDownloadSettings.tls = true; } @@ -804,14 +1442,54 @@ function URI_VLESS() { parsedDownloadSettings['client-fingerprint'] = downloadSettings.tlsSettings.fingerprint; } - if (Array.isArray(downloadSettings.tlsSettings.alpn)) { - const alpn = downloadSettings.tlsSettings.alpn.filter( + if ( + Array.isArray(downloadSettings.tlsSettings.alpn) && + downloadSettings.tlsSettings.alpn.length > 0 && + downloadSettings.tlsSettings.alpn.every( (item) => typeof item === 'string' && item !== '', - ); - if (alpn.length > 0) { - parsedDownloadSettings.alpn = alpn; - } + ) + ) { + parsedDownloadSettings.alpn = + downloadSettings.tlsSettings.alpn; } + if (downloadSettings.tlsSettings.allowInsecure === true) { + parsedDownloadSettings['skip-cert-verify'] = true; + } + if (isNotBlank(downloadSettings.tlsSettings.echConfigList)) { + parsedDownloadSettings['ech-opts'] = { + enable: true, + config: downloadSettings.tlsSettings.echConfigList, + }; + } + } + + let realityOpts; + if (isPlainObject(downloadSettings.realitySettings)) { + realityOpts = {}; + if (isNotBlank(downloadSettings.realitySettings.publicKey)) { + realityOpts['public-key'] = + downloadSettings.realitySettings.publicKey; + } + if (isNotBlank(downloadSettings.realitySettings.shortId)) { + realityOpts['short-id'] = + downloadSettings.realitySettings.shortId; + } + if (isNotBlank(downloadSettings.realitySettings.serverName)) { + parsedDownloadSettings.servername = + downloadSettings.realitySettings.serverName; + } + if (isNotBlank(downloadSettings.realitySettings.fingerprint)) { + parsedDownloadSettings['client-fingerprint'] = + downloadSettings.realitySettings.fingerprint; + } + } + if (downloadSecurity === 'reality') { + // Keep an explicit empty reality marker so the producer can + // route invalid nested Reality configs through the shared + // "missing public-key" export rejection path. + parsedDownloadSettings['reality-opts'] = realityOpts || {}; + } else if (realityOpts && Object.keys(realityOpts).length > 0) { + parsedDownloadSettings['reality-opts'] = realityOpts; } if (isPlainObject(downloadSettings.xhttpSettings)) { @@ -823,35 +1501,15 @@ function URI_VLESS() { parsedDownloadSettings.host = downloadSettings.xhttpSettings.host; } - if (downloadSettings.xhttpSettings.noGRPCHeader === true) { - parsedDownloadSettings['no-grpc-header'] = true; - } - if (isNotBlank(downloadSettings.xhttpSettings.xPaddingBytes)) { - parsedDownloadSettings['x-padding-bytes'] = - downloadSettings.xhttpSettings.xPaddingBytes; - } - const scMaxEachPostBytes = - normalizeXhttpScalarUpperBound( - downloadSettings.xhttpSettings.scMaxEachPostBytes, - ); - if (scMaxEachPostBytes != null) { - parsedDownloadSettings['sc-max-each-post-bytes'] = - scMaxEachPostBytes; - } - const scMinPostsIntervalMs = - normalizeXhttpScalarUpperBound( - downloadSettings.xhttpSettings.scMinPostsIntervalMs, - ); - if (scMinPostsIntervalMs != null) { - parsedDownloadSettings['sc-min-posts-interval-ms'] = - scMinPostsIntervalMs; - } - - const reuseSettings = mapXmuxToReuseSettings( - downloadSettings.xhttpSettings.extra?.xmux, + applyXhttpExtraFields( + parsedDownloadSettings, + downloadSettings.xhttpSettings, ); - if (reuseSettings) { - parsedDownloadSettings['reuse-settings'] = reuseSettings; + if (isPlainObject(downloadSettings.xhttpSettings.extra)) { + applyXhttpExtraFields( + parsedDownloadSettings, + downloadSettings.xhttpSettings.extra, + ); } } @@ -1054,17 +1712,19 @@ function URI_VLESS() { // mKCP 的伪装头部类型。当前可选值有 none / srtp / utp / wechat-video / dtls / wireguard。省略时默认值为 none,即不使用伪装头部,但不可以为空字符串。 proxy.headerType = params.headerType || 'none'; } - if (params.extra) { + if (params.extra && !['xhttp'].includes(proxy.network)) { proxy._extra = params.extra; } if (['xhttp'].includes(proxy.network)) { let extra = {}; + let invalidRawExtra; try { - extra = proxy._extra ? JSON.parse(proxy._extra) : {}; + extra = params.extra ? JSON.parse(params.extra) : {}; } catch (e) { $.error( - `Failed to parse extra field as JSON: ${proxy._extra}`, + `Failed to parse extra field as JSON: ${params.extra}`, ); + invalidRawExtra = params.extra; } const xhttpOpts = { ...(proxy[`${proxy.network}-opts`] || {}), @@ -1072,32 +1732,7 @@ function URI_VLESS() { if (params.mode) { xhttpOpts.mode = params.mode; } - if (extra?.['noGRPCHeader'] === true) { - xhttpOpts['no-grpc-header'] = true; - } - if (isNotBlank(extra?.['xPaddingBytes'])) { - xhttpOpts['x-padding-bytes'] = extra['xPaddingBytes']; - } - const scMaxEachPostBytes = - normalizeXhttpScalarUpperBound(extra?.['scMaxEachPostBytes']); - if (scMaxEachPostBytes != null) { - xhttpOpts['sc-max-each-post-bytes'] = - scMaxEachPostBytes; - } - const scMinPostsIntervalMs = - normalizeXhttpScalarUpperBound( - extra?.['scMinPostsIntervalMs'], - ); - if (scMinPostsIntervalMs != null) { - xhttpOpts['sc-min-posts-interval-ms'] = - scMinPostsIntervalMs; - } - if (isPlainObject(extra?.xmux)) { - const reuseSettings = mapXmuxToReuseSettings(extra.xmux); - if (reuseSettings) { - xhttpOpts['reuse-settings'] = reuseSettings; - } - } + applyXhttpExtraFields(xhttpOpts, extra); const downloadSettings = parseDownloadSettings( extra?.downloadSettings, ); @@ -1107,6 +1742,23 @@ function URI_VLESS() { if (Object.keys(xhttpOpts).length > 0) { proxy[`${proxy.network}-opts`] = xhttpOpts; } + if (invalidRawExtra != null) { + // Keep the raw invalid extra string so URI exports can + // round-trip it verbatim even though Mihomo cannot model it. + proxy._extra = invalidRawExtra; + } + + // IMPORTANT: for VLESS xhttp we only keep URI extra fields that + // Mihomo does not model structurally in `_extra_unsupported`. + // Supported fields must round-trip through the structured node + // so later edits are reflected on export, while unsupported + // fields still survive VLESS URI -> node -> VLESS URI flows. + const unsupportedExtra = collectUnsupportedRootXhttpExtra(extra, { + parsedDownloadSettings: downloadSettings, + }); + if (unsupportedExtra) { + proxy._extra_unsupported = unsupportedExtra; + } } else if (params.mode) { proxy._mode = params.mode; } diff --git a/backend/src/core/proxy-utils/processors/index.js b/backend/src/core/proxy-utils/processors/index.js index 4c386655..be74ff7b 100644 --- a/backend/src/core/proxy-utils/processors/index.js +++ b/backend/src/core/proxy-utils/processors/index.js @@ -1,6 +1,6 @@ import resourceCache from '@/utils/resource-cache'; import scriptResourceCache from '@/utils/script-resource-cache'; -import { isIPv4, isIPv6, ipAddress } from '@/utils'; +import { isIPv4, isIPv6, ipAddress, isPlainObject } from '@/utils'; import { FULL } from '@/utils/logical'; import { getFlag, removeFlag } from '@/utils/geo'; import { doh } from '@/utils/dns'; @@ -23,9 +23,6 @@ import { normalizeFlowHeader, } from '@/utils/flow'; -function isObject(item) { - return item && typeof item === 'object' && !Array.isArray(item); -} function trimWrap(str) { if (str.startsWith('<') && str.endsWith('>')) { return str.slice(1, -1); @@ -35,7 +32,10 @@ function trimWrap(str) { function deepMerge(target, _other) { const other = typeof _other === 'string' ? JSON.parse(_other) : _other; for (const key in other) { - if (isObject(other[key])) { + // Only recurse into JSON-like patch objects. YAML can surface non-plain + // objects (for example timestamps), and those should be assigned as + // values instead of being treated as nested config maps. + if (isPlainObject(other[key])) { if (key.endsWith('!')) { const k = trimWrap(key.slice(0, -1)); target[k] = other[key]; diff --git a/backend/src/core/proxy-utils/producers/clashmeta.js b/backend/src/core/proxy-utils/producers/clashmeta.js index da643f74..451a8f84 100644 --- a/backend/src/core/proxy-utils/producers/clashmeta.js +++ b/backend/src/core/proxy-utils/producers/clashmeta.js @@ -173,6 +173,15 @@ export default function ClashMeta_Producer() { proxy.servername = proxy.sni; delete proxy.sni; } + // Mihomo 的运行时校验(`adapter/outbound/vless.go`) + // 会先把 flow 截断到 16 个字符,并且只接受 + // `xtls-rprx-vision`。`xtls-rprx-direct`、 + // `xtls-rprx-unknown` 等值在 Mihomo 加载时会报错。 + // + // 另外,xhttp 使用 `alpn: [h3]` 时必须启用 TLS, + // 且不能启用 Reality;这条限制同时作用于根 xhttp + // 配置,以及继承根配置默认值后的嵌套 + // `download-settings`。 } else if (proxy.type === 'ss') { if ( isPresent(proxy, 'shadow-tls-password') && diff --git a/backend/src/core/proxy-utils/producers/uri.js b/backend/src/core/proxy-utils/producers/uri.js index 2e4e5621..65817b7a 100644 --- a/backend/src/core/proxy-utils/producers/uri.js +++ b/backend/src/core/proxy-utils/producers/uri.js @@ -1,11 +1,39 @@ /* eslint-disable no-case-declarations */ import { Base64 } from 'js-base64'; -import { isIPv6 } from '@/utils'; +import { isIPv6, isPlainObject } from '@/utils'; import { getWireGuardAddressWithCIDR, normalizePluginMuxValue } from './utils'; -import { normalizeXhttpScalarUpperBound } from '../xhttp-utils'; +import { + normalizeXhttpIntegerValue, + normalizeXhttpNonNegativeRange, + normalizeXhttpPositiveRange, + normalizeXhttpScalarUpperBound, +} from '../xhttp-utils'; -function isObject(value) { - return value != null && typeof value === 'object' && !Array.isArray(value); +function toStringHeaderMap(headers, { excludeHost = false } = {}) { + if (!isPlainObject(headers)) { + return undefined; + } + + const parsedHeaders = {}; + for (const [key, value] of Object.entries(headers)) { + if (typeof value !== 'string' || value === '') { + continue; + } + if (excludeHost && /^host$/i.test(key)) { + continue; + } + parsedHeaders[key] = value; + } + + return Object.keys(parsedHeaders).length > 0 ? parsedHeaders : undefined; +} + +function parseIntegerLikeValue(value) { + return normalizeXhttpIntegerValue(value); +} + +function getSerializableXhttpRangeValue(value) { + return normalizeXhttpNonNegativeRange(value); } function getTransportHost(network, transportOpts = {}) { @@ -31,7 +59,7 @@ function getTransportHost(network, transportOpts = {}) { } function mapReuseSettingsToXmux(reuseSettings) { - if (!isObject(reuseSettings)) { + if (!isPlainObject(reuseSettings)) { return undefined; } @@ -45,33 +73,155 @@ function mapReuseSettingsToXmux(reuseSettings) { }; for (const [sourceKey, targetKey] of Object.entries(reuseFieldMap)) { - const value = reuseSettings[sourceKey]; - if (typeof value === 'string' && value !== '') { - xmux[targetKey] = value; - } else if (typeof value === 'number' && Number.isFinite(value)) { - xmux[targetKey] = `${value}`; + const normalizedValue = normalizeXhttpNonNegativeRange( + reuseSettings[sourceKey], + ); + if (normalizedValue != null) { + xmux[targetKey] = + typeof normalizedValue === 'number' + ? `${normalizedValue}` + : normalizedValue; } } + const hKeepAlivePeriod = parseIntegerLikeValue( + reuseSettings['h-keep-alive-period'], + ); + if (hKeepAlivePeriod != null) { + xmux.hKeepAlivePeriod = hKeepAlivePeriod; + } + return Object.keys(xmux).length > 0 ? xmux : undefined; } +function applyStructuredXhttpExtraFields( + target, + xhttpOpts, + { excludeHostHeader = true, xmuxTarget = 'root' } = {}, +) { + if (!isPlainObject(target) || !isPlainObject(xhttpOpts)) { + return; + } + + const headers = toStringHeaderMap(xhttpOpts.headers, { + excludeHost: excludeHostHeader, + }); + if (headers) { + target.headers = headers; + } + + if (xhttpOpts['no-grpc-header'] === true) { + target.noGRPCHeader = true; + } + if (xhttpOpts['x-padding-bytes']) { + target.xPaddingBytes = xhttpOpts['x-padding-bytes']; + } + if (xhttpOpts['x-padding-obfs-mode'] === true) { + target.xPaddingObfsMode = true; + } + if (xhttpOpts['x-padding-key']) { + target.xPaddingKey = xhttpOpts['x-padding-key']; + } + if (xhttpOpts['x-padding-header']) { + target.xPaddingHeader = xhttpOpts['x-padding-header']; + } + if (xhttpOpts['x-padding-placement']) { + target.xPaddingPlacement = xhttpOpts['x-padding-placement']; + } + if (xhttpOpts['x-padding-method']) { + target.xPaddingMethod = xhttpOpts['x-padding-method']; + } + if (xhttpOpts['uplink-http-method']) { + target.uplinkHTTPMethod = xhttpOpts['uplink-http-method']; + } + if (xhttpOpts['session-placement']) { + target.sessionPlacement = xhttpOpts['session-placement']; + } + if (xhttpOpts['session-key']) { + target.sessionKey = xhttpOpts['session-key']; + } + if (xhttpOpts['seq-placement']) { + target.seqPlacement = xhttpOpts['seq-placement']; + } + if (xhttpOpts['seq-key']) { + target.seqKey = xhttpOpts['seq-key']; + } + if (xhttpOpts['uplink-data-placement']) { + target.uplinkDataPlacement = xhttpOpts['uplink-data-placement']; + } + if (xhttpOpts['uplink-data-key']) { + target.uplinkDataKey = xhttpOpts['uplink-data-key']; + } + + const uplinkChunkSize = getSerializableXhttpRangeValue( + xhttpOpts['uplink-chunk-size'], + ); + if (uplinkChunkSize != null) { + target.uplinkChunkSize = uplinkChunkSize; + } + + if (xhttpOpts['sc-max-each-post-bytes'] != null) { + const scMaxEachPostBytes = normalizeXhttpScalarUpperBound( + xhttpOpts['sc-max-each-post-bytes'], + ); + if (scMaxEachPostBytes != null) { + target.scMaxEachPostBytes = scMaxEachPostBytes; + } + } + + if (xhttpOpts['sc-min-posts-interval-ms'] != null) { + const scMinPostsIntervalMs = normalizeXhttpPositiveRange( + xhttpOpts['sc-min-posts-interval-ms'], + ); + if (scMinPostsIntervalMs != null) { + target.scMinPostsIntervalMs = scMinPostsIntervalMs; + } + } + + const xmux = mapReuseSettingsToXmux(xhttpOpts['reuse-settings']); + if (xmux) { + if (xmuxTarget === 'extra') { + target.extra = { + ...(isPlainObject(target.extra) ? target.extra : {}), + xmux, + }; + } else { + target.xmux = xmux; + } + } +} + function buildXhttpDownloadSettings(downloadSettings) { - if (!isObject(downloadSettings)) { + if (!isPlainObject(downloadSettings)) { return undefined; } + const explicitNetwork = + typeof downloadSettings.network === 'string' + ? downloadSettings.network.toLowerCase() + : ''; + const normalizedNetwork = + explicitNetwork === 'xhttp' || explicitNetwork === 'splithttp' + ? 'xhttp' + : undefined; + const result = {}; if (downloadSettings.server) { result.address = downloadSettings.server; } - if ( - downloadSettings.port != null && - !Number.isNaN(parseInt(`${downloadSettings.port}`, 10)) - ) { - result.port = parseInt(`${downloadSettings.port}`, 10); + const parsedPort = normalizeXhttpIntegerValue(downloadSettings.port, { + allowNegative: false, + }); + if (parsedPort != null) { + result.port = parsedPort; } - if (downloadSettings.tls) { + + const realityOpts = isPlainObject(downloadSettings['reality-opts']) + ? downloadSettings['reality-opts'] + : undefined; + if (realityOpts) { + result.security = 'reality'; + } else if (downloadSettings.tls) { result.security = 'tls'; } @@ -82,87 +232,87 @@ function buildXhttpDownloadSettings(downloadSettings) { if (downloadSettings['client-fingerprint']) { tlsSettings.fingerprint = downloadSettings['client-fingerprint']; } + if (downloadSettings['skip-cert-verify']) { + tlsSettings.allowInsecure = true; + } if (downloadSettings.alpn) { tlsSettings.alpn = Array.isArray(downloadSettings.alpn) ? downloadSettings.alpn : [downloadSettings.alpn]; } + if ( + isPlainObject(downloadSettings['ech-opts']) && + downloadSettings['ech-opts'].config + ) { + tlsSettings.echConfigList = downloadSettings['ech-opts'].config; + } if (Object.keys(tlsSettings).length > 0) { result.tlsSettings = tlsSettings; } + if (realityOpts) { + const realitySettings = {}; + if (downloadSettings.servername) { + realitySettings.serverName = downloadSettings.servername; + } + if (downloadSettings['client-fingerprint']) { + realitySettings.fingerprint = + downloadSettings['client-fingerprint']; + } + if (realityOpts['public-key']) { + realitySettings.publicKey = realityOpts['public-key']; + } + if (realityOpts['short-id']) { + realitySettings.shortId = realityOpts['short-id']; + } + if (Object.keys(realitySettings).length > 0) { + result.realitySettings = realitySettings; + } + } + const xhttpSettings = {}; if (downloadSettings.path) { xhttpSettings.path = downloadSettings.path; } - if (downloadSettings.host) { - xhttpSettings.host = downloadSettings.host; - } - if (downloadSettings['no-grpc-header']) { - xhttpSettings.noGRPCHeader = true; - } - if (downloadSettings['x-padding-bytes']) { - xhttpSettings.xPaddingBytes = downloadSettings['x-padding-bytes']; - } - if (downloadSettings['sc-max-each-post-bytes'] != null) { - const scMaxEachPostBytes = normalizeXhttpScalarUpperBound( - downloadSettings['sc-max-each-post-bytes'], - ); - if (scMaxEachPostBytes != null) { - xhttpSettings.scMaxEachPostBytes = scMaxEachPostBytes; - } - } - if (downloadSettings['sc-min-posts-interval-ms'] != null) { - const scMinPostsIntervalMs = normalizeXhttpScalarUpperBound( - downloadSettings['sc-min-posts-interval-ms'], - ); - if (scMinPostsIntervalMs != null) { - xhttpSettings.scMinPostsIntervalMs = scMinPostsIntervalMs; - } - } - - const xmux = mapReuseSettingsToXmux(downloadSettings['reuse-settings']); - if (xmux) { - xhttpSettings.extra = { xmux }; + const downloadHost = getTransportHost('xhttp', downloadSettings); + if (downloadHost) { + xhttpSettings.host = downloadHost; } + applyStructuredXhttpExtraFields(xhttpSettings, downloadSettings, { + excludeHostHeader: true, + xmuxTarget: 'extra', + }); if (Object.keys(xhttpSettings).length > 0) { result.xhttpSettings = xhttpSettings; } - return Object.keys(result).length > 0 ? result : undefined; + if (Object.keys(result).length === 0 && normalizedNetwork == null) { + return undefined; + } + + // Treat nested downloadSettings.network as a supported structured field. + // Fresh structured exports still default to xhttp so Xray sees a nested + // StreamConfig instead of falling back to tcp. + return { + ...(result.address != null ? { address: result.address } : {}), + network: normalizedNetwork || 'xhttp', + ...(result.port != null ? { port: result.port } : {}), + ...(result.security != null ? { security: result.security } : {}), + ...(result.tlsSettings != null ? { tlsSettings: result.tlsSettings } : {}), + ...(result.realitySettings != null + ? { realitySettings: result.realitySettings } + : {}), + ...(result.xhttpSettings != null ? { xhttpSettings: result.xhttpSettings } : {}), + }; } -function buildStructuredVlessExtra(proxy) { +function buildStructuredVlessExtraObject(proxy) { const xhttpOpts = proxy['xhttp-opts'] || {}; const extra = {}; - - if (xhttpOpts['no-grpc-header'] === true) { - extra.noGRPCHeader = true; - } - if (xhttpOpts['x-padding-bytes']) { - extra.xPaddingBytes = xhttpOpts['x-padding-bytes']; - } - if (xhttpOpts['sc-max-each-post-bytes'] != null) { - const scMaxEachPostBytes = normalizeXhttpScalarUpperBound( - xhttpOpts['sc-max-each-post-bytes'], - ); - if (scMaxEachPostBytes != null) { - extra.scMaxEachPostBytes = scMaxEachPostBytes; - } - } - if (xhttpOpts['sc-min-posts-interval-ms'] != null) { - const scMinPostsIntervalMs = normalizeXhttpScalarUpperBound( - xhttpOpts['sc-min-posts-interval-ms'], - ); - if (scMinPostsIntervalMs != null) { - extra.scMinPostsIntervalMs = scMinPostsIntervalMs; - } - } - - const xmux = mapReuseSettingsToXmux(xhttpOpts['reuse-settings']); - if (xmux) { - extra.xmux = xmux; - } + applyStructuredXhttpExtraFields(extra, xhttpOpts, { + excludeHostHeader: true, + xmuxTarget: 'root', + }); const downloadSettings = buildXhttpDownloadSettings( xhttpOpts['download-settings'], @@ -171,130 +321,112 @@ function buildStructuredVlessExtra(proxy) { extra.downloadSettings = downloadSettings; } - return Object.keys(extra).length > 0 ? JSON.stringify(extra) : ''; + return Object.keys(extra).length > 0 ? extra : undefined; } -function applyNormalizedXhttpScalar(target, rawKey, value) { - if (!isObject(target)) { - return false; +function cloneXhttpExtraValue(value) { + if (Array.isArray(value)) { + return value.map(cloneXhttpExtraValue); } - const normalizedValue = normalizeXhttpScalarUpperBound(value); - if (normalizedValue != null) { - if (target[rawKey] === normalizedValue) { - return false; + if (isPlainObject(value)) { + const clonedValue = {}; + for (const [key, entryValue] of Object.entries(value)) { + clonedValue[key] = cloneXhttpExtraValue(entryValue); } - target[rawKey] = normalizedValue; - return true; + return clonedValue; } - if (Object.prototype.hasOwnProperty.call(target, rawKey)) { - delete target[rawKey]; - return true; - } - - return false; + return value; } -function normalizeRawXhttpExtra(proxy) { - if (!proxy._extra) { - return ''; +function mergeUnsupportedXhttpExtraValue(baseValue, unsupportedValue) { + if (baseValue == null) { + return cloneXhttpExtraValue(unsupportedValue); } - let rawExtra; - try { - rawExtra = JSON.parse(proxy._extra); - } catch (e) { + if (Array.isArray(baseValue) || Array.isArray(unsupportedValue)) { + return cloneXhttpExtraValue(baseValue); + } + + if (isPlainObject(baseValue) && isPlainObject(unsupportedValue)) { + return mergeUnsupportedXhttpExtraObject(baseValue, unsupportedValue); + } + + return cloneXhttpExtraValue(baseValue); +} + +function mergeUnsupportedXhttpExtraObject(baseObject, unsupportedObject) { + const mergedExtra = isPlainObject(baseObject) + ? cloneXhttpExtraValue(baseObject) + : {}; + if (!isPlainObject(unsupportedObject)) { + return mergedExtra; + } + + for (const [key, value] of Object.entries(unsupportedObject)) { + if (!Object.prototype.hasOwnProperty.call(mergedExtra, key)) { + mergedExtra[key] = cloneXhttpExtraValue(value); + continue; + } + + mergedExtra[key] = mergeUnsupportedXhttpExtraValue( + mergedExtra[key], + value, + ); + } + + return mergedExtra; +} + +function getExplicitExtraOverride(proxy) { + if (typeof proxy._extra === 'string') { return proxy._extra; } - if (!isObject(rawExtra) || !isObject(proxy['xhttp-opts'])) { - return proxy._extra; + // `_extra` only accepts JSON-like plain objects here. Broader object checks + // would accidentally stringify instances such as Date/Map/class values. + if (isPlainObject(proxy._extra)) { + return JSON.stringify(proxy._extra); } - let didChange = false; - const xhttpOpts = proxy['xhttp-opts']; - - if (xhttpOpts['sc-max-each-post-bytes'] != null) { - didChange = - applyNormalizedXhttpScalar( - rawExtra, - 'scMaxEachPostBytes', - xhttpOpts['sc-max-each-post-bytes'], - ) || didChange; - } - if (xhttpOpts['sc-min-posts-interval-ms'] != null) { - didChange = - applyNormalizedXhttpScalar( - rawExtra, - 'scMinPostsIntervalMs', - xhttpOpts['sc-min-posts-interval-ms'], - ) || didChange; - } - - const downloadSettings = xhttpOpts['download-settings']; - if (isObject(downloadSettings)) { - const rawDownloadSettings = isObject(rawExtra.downloadSettings) - ? rawExtra.downloadSettings - : undefined; - - let rawXhttpSettings = isObject(rawDownloadSettings?.xhttpSettings) - ? rawDownloadSettings.xhttpSettings - : undefined; - if ( - !rawXhttpSettings && - (downloadSettings['sc-max-each-post-bytes'] != null || - downloadSettings['sc-min-posts-interval-ms'] != null) - ) { - rawExtra.downloadSettings = isObject(rawExtra.downloadSettings) - ? rawExtra.downloadSettings - : {}; - rawExtra.downloadSettings.xhttpSettings = {}; - rawXhttpSettings = rawExtra.downloadSettings.xhttpSettings; - didChange = true; - } - - if (rawXhttpSettings) { - if (downloadSettings['sc-max-each-post-bytes'] != null) { - didChange = - applyNormalizedXhttpScalar( - rawXhttpSettings, - 'scMaxEachPostBytes', - downloadSettings['sc-max-each-post-bytes'], - ) || didChange; - } - if (downloadSettings['sc-min-posts-interval-ms'] != null) { - didChange = - applyNormalizedXhttpScalar( - rawXhttpSettings, - 'scMinPostsIntervalMs', - downloadSettings['sc-min-posts-interval-ms'], - ) || didChange; - } - - if (Object.keys(rawXhttpSettings).length === 0) { - delete rawExtra.downloadSettings.xhttpSettings; - didChange = true; - if (Object.keys(rawExtra.downloadSettings).length === 0) { - delete rawExtra.downloadSettings; - } - } - } - } - - return didChange ? JSON.stringify(rawExtra) : proxy._extra; + return undefined; } function buildVlessExtra(proxy) { + const explicitExtraOverride = getExplicitExtraOverride(proxy); + if (explicitExtraOverride != null) { + // `_extra` is an explicit user override for the final URI extra. When + // present as a string or plain object, we bypass the structured xhttp + // rebuild entirely so users can hand-author extra without needing to + // keep other structured fields in sync. + return explicitExtraOverride; + } + if (proxy.network !== 'xhttp') { return proxy._extra || ''; } - if (proxy._extra) { - return normalizeRawXhttpExtra(proxy); - } + const structuredExtra = buildStructuredVlessExtraObject(proxy); - return buildStructuredVlessExtra(proxy); + // IMPORTANT: `_extra_unsupported` is only the sidecar for URI extra fields + // that Mihomo does not model structurally yet, and it only participates + // when the user did not explicitly set `_extra`. Without an explicit + // override, supported xhttp fields must still be emitted from the current + // structured Mihomo node so later edits are reflected on export, while + // `_extra_unsupported` fills the holes needed for VLESS URI -> node -> + // VLESS URI lossless round-trips. That also means supported-field format + // conflicts are resolved by the structured emitters here, e.g. + // sc-max-each-post-bytes still emits the compatibility upper bound while + // sc-min-posts-interval-ms keeps range. + const mergedExtra = mergeUnsupportedXhttpExtraObject( + structuredExtra, + proxy._extra_unsupported, + ); + + return Object.keys(mergedExtra).length > 0 + ? JSON.stringify(mergedExtra) + : ''; } function vless(proxy) { diff --git a/backend/src/core/proxy-utils/xhttp-utils.js b/backend/src/core/proxy-utils/xhttp-utils.js index 733f203b..23f714b2 100644 --- a/backend/src/core/proxy-utils/xhttp-utils.js +++ b/backend/src/core/proxy-utils/xhttp-utils.js @@ -1,11 +1,15 @@ -export function normalizeXhttpScalarUpperBound(value) { +function parseNormalizedXhttpRangeBounds( + value, + { allowZeroUpperBound = true } = {}, +) { if (typeof value !== 'string' && typeof value !== 'number') { return undefined; } - // Mirror Mihomo's ParseRange/GetNormalizedSc* behavior: accept explicit - // positive signs, leading zeros, and ascending ranges, but reject - // zero-valued finals because sc-* values must resolve to > 0. + // Mirror Mihomo's ParseRange behavior: accept explicit positive signs, + // leading zeros, and ascending ranges. We also compact whitespace so the + // emitted value stays compatible with Xray's Int32Range string parser, + // which does not trim around the internal `-`. const parseUnsignedIntegerToken = (token) => { const normalizedToken = token.trim(); if (!/^\+?\d+$/.test(normalizedToken)) { @@ -20,7 +24,13 @@ export function normalizeXhttpScalarUpperBound(value) { const rangeParts = normalizedValue.split('-'); if (rangeParts.length === 1) { const normalizedInteger = parseUnsignedIntegerToken(rangeParts[0]); - return normalizedInteger > 0 ? normalizedInteger : undefined; + const minimumAllowedValue = allowZeroUpperBound ? 0 : 1; + return normalizedInteger >= minimumAllowedValue + ? { + lowerBound: normalizedInteger, + upperBound: normalizedInteger, + } + : undefined; } if (rangeParts.length !== 2) { @@ -33,5 +43,91 @@ export function normalizeXhttpScalarUpperBound(value) { return undefined; } - return upperBound > 0 && upperBound >= lowerBound ? upperBound : undefined; + const minimumAllowedUpperBound = allowZeroUpperBound ? 0 : 1; + return upperBound >= minimumAllowedUpperBound && upperBound >= lowerBound + ? { + lowerBound, + upperBound, + } + : undefined; +} + +function parseNormalizedXhttpPositiveRangeBounds(value) { + return parseNormalizedXhttpRangeBounds(value, { + allowZeroUpperBound: false, + }); +} + +export function normalizeXhttpScalarUpperBound(value) { + // IMPORTANT: the legacy-client compatibility reason for collapsing ranges + // to an upper bound specifically applies to sc-max-each-post-bytes. + // Mihomo first shipped sc-max-each-post-bytes as an int-only field, then + // only later added true range support, so emitting `lower-upper` here can + // still break older clients that predate that change. Once the new + // official Mihomo stable release with ranged sc-max-each-post-bytes is + // broadly deployed, switch that field back to preserving full ranges and + // remove the upper-bound compatibility logic tied to it. + const normalizedBounds = parseNormalizedXhttpPositiveRangeBounds(value); + return normalizedBounds?.upperBound; +} + +export function normalizeXhttpPositiveRange(value) { + // IMPORTANT: unlike sc-max-each-post-bytes, sc-min-posts-interval-ms does + // not need an old-client compatibility shim. Mihomo introduced + // sc-min-posts-interval-ms with range semantics from day one, so we should + // keep exporting its full normalized range form instead of collapsing it. + const normalizedBounds = parseNormalizedXhttpPositiveRangeBounds(value); + if (!normalizedBounds) { + return undefined; + } + + const { lowerBound, upperBound } = normalizedBounds; + return lowerBound === upperBound ? upperBound : `${lowerBound}-${upperBound}`; +} + +export function normalizeXhttpNonNegativeRange(value) { + const normalizedBounds = parseNormalizedXhttpRangeBounds(value); + if (!normalizedBounds) { + return undefined; + } + + const { lowerBound, upperBound } = normalizedBounds; + return lowerBound === upperBound ? upperBound : `${lowerBound}-${upperBound}`; +} + +export function normalizeXhttpIntegerValue( + value, + { allowNegative = true } = {}, +) { + if ( + typeof value === 'number' && + Number.isFinite(value) && + Number.isSafeInteger(value) + ) { + if (!allowNegative && value < 0) { + return undefined; + } + return value; + } + + if (typeof value !== 'string') { + return undefined; + } + + const normalizedValue = value.trim(); + const integerPattern = allowNegative ? /^[+-]?\d+$/ : /^\+?\d+$/; + if (!integerPattern.test(normalizedValue)) { + return undefined; + } + + const parsedInteger = parseInt(normalizedValue, 10); + if (!Number.isSafeInteger(parsedInteger)) { + return undefined; + } + + if (!allowNegative && parsedInteger < 0) { + return undefined; + } + + return parsedInteger; } diff --git a/backend/src/test/proxy-parsers/v2ray-and-platforms.spec.js b/backend/src/test/proxy-parsers/v2ray-and-platforms.spec.js index d1f33b0f..c1b4972a 100644 --- a/backend/src/test/proxy-parsers/v2ray-and-platforms.spec.js +++ b/backend/src/test/proxy-parsers/v2ray-and-platforms.spec.js @@ -87,7 +87,9 @@ describe('VMess and VLESS parser coverage', function () { fp: 'chrome', }), ); - const proxy = parseOne(`vmess://${share}#Outer%20Fragment%20Remark`); + const proxy = parseOne( + `vmess://${share}#Outer%20Fragment%20Remark`, + ); expectSubset(proxy, { type: 'vmess', @@ -652,7 +654,6 @@ describe('VMess and VLESS parser coverage', function () { uuid: UUID, tls: true, network: 'xhttp', - _extra: extra, 'xhttp-opts': { mode: 'stream-up', path: '/xhttp', @@ -672,6 +673,8 @@ describe('VMess and VLESS parser coverage', function () { }, }, }); + expect(proxy).to.not.have.property('_extra'); + expect(proxy).to.not.have.property('_extra_unsupported'); }); it('parses xhttp VLESS shares with downloadSettings extra', function () { @@ -715,7 +718,6 @@ describe('VMess and VLESS parser coverage', function () { uuid: UUID, tls: true, network: 'xhttp', - _extra: extra, 'xhttp-opts': { mode: 'stream-up', path: '/xhttp', @@ -734,7 +736,7 @@ describe('VMess and VLESS parser coverage', function () { 'no-grpc-header': true, 'x-padding-bytes': '32-64', 'sc-max-each-post-bytes': 1000000, - 'sc-min-posts-interval-ms': 300, + 'sc-min-posts-interval-ms': '0-300', 'reuse-settings': { 'max-connections': '8', 'h-max-reusable-secs': '900', @@ -742,6 +744,10 @@ describe('VMess and VLESS parser coverage', function () { }, }, }); + expect( + proxy['xhttp-opts']?.['download-settings'], + ).to.not.have.property('network'); + expect(proxy).to.not.have.property('_extra_unsupported'); }); it('parses xhttp VLESS shares with downloadSettings extra without mode', function () { @@ -769,7 +775,6 @@ describe('VMess and VLESS parser coverage', function () { uuid: UUID, tls: true, network: 'xhttp', - _extra: extra, 'xhttp-opts': { path: '/xhttp', headers: { @@ -786,6 +791,166 @@ describe('VMess and VLESS parser coverage', function () { expect(proxy['xhttp-opts']).to.not.have.property('mode'); }); + it('parses xhttp network into structured downloadSettings while keeping unsupported nested fields in the sidecar', function () { + const extra = JSON.stringify({ + downloadSettings: { + network: 'xhttp', + sockopt: { + mark: 255, + }, + }, + }); + const proxy = parseOne( + `vless://${UUID}@vless-xhttp.example.com:443?type=xhttp&security=tls&host=cdn.example.com&path=%2Fxhttp&mode=stream-up&extra=${encodeURIComponent( + extra, + )}#VLESS%20XHTTP%20Download%20Unsupported%20Only`, + ); + + expectSubset(proxy, { + type: 'vless', + name: 'VLESS XHTTP Download Unsupported Only', + server: 'vless-xhttp.example.com', + port: 443, + uuid: UUID, + tls: true, + network: 'xhttp', + 'xhttp-opts': { + mode: 'stream-up', + path: '/xhttp', + headers: { + Host: 'cdn.example.com', + }, + 'download-settings': { + network: 'xhttp', + }, + }, + }); + expect(proxy._extra_unsupported).to.deep.equal({ + downloadSettings: { + sockopt: { + mark: 255, + }, + }, + }); + }); + + it('normalizes splithttp downloadSettings network without keeping the raw network in the sidecar', function () { + const extra = JSON.stringify({ + downloadSettings: { + network: 'splithttp', + sockopt: { + mark: 255, + }, + }, + }); + const proxy = parseOne( + `vless://${UUID}@vless-xhttp.example.com:443?type=xhttp&security=tls&host=cdn.example.com&path=%2Fxhttp&mode=stream-up&extra=${encodeURIComponent( + extra, + )}#VLESS%20XHTTP%20Download%20SplitHTTP`, + ); + + expectSubset(proxy, { + type: 'vless', + name: 'VLESS XHTTP Download SplitHTTP', + server: 'vless-xhttp.example.com', + port: 443, + uuid: UUID, + tls: true, + network: 'xhttp', + 'xhttp-opts': { + mode: 'stream-up', + path: '/xhttp', + headers: { + Host: 'cdn.example.com', + }, + 'download-settings': { + network: 'xhttp', + }, + }, + }); + expect(proxy._extra_unsupported).to.deep.equal({ + downloadSettings: { + sockopt: { + mark: 255, + }, + }, + }); + }); + + it('keeps malformed reality downloadSettings as an empty reality marker', function () { + const extra = JSON.stringify({ + downloadSettings: { + address: 'download.example.com', + network: 'xhttp', + port: 8443, + security: 'reality', + xhttpSettings: { + path: '/download', + }, + }, + }); + const proxy = parseOne( + `vless://${UUID}@vless-xhttp.example.com:443?type=xhttp&security=tls&host=cdn.example.com&path=%2Fxhttp&mode=stream-up&extra=${encodeURIComponent( + extra, + )}#VLESS%20XHTTP%20Download%20Reality%20Marker`, + ); + + expectSubset(proxy, { + type: 'vless', + name: 'VLESS XHTTP Download Reality Marker', + server: 'vless-xhttp.example.com', + port: 443, + uuid: UUID, + tls: true, + network: 'xhttp', + 'xhttp-opts': { + mode: 'stream-up', + path: '/xhttp', + headers: { + Host: 'cdn.example.com', + }, + 'download-settings': { + network: 'xhttp', + server: 'download.example.com', + port: 8443, + tls: true, + path: '/download', + }, + }, + }); + expect( + proxy['xhttp-opts']?.['download-settings']?.['reality-opts'], + ).to.deep.equal({}); + expect(proxy).to.not.have.property('_extra_unsupported'); + }); + + it('keeps invalid xhttp extra as raw _extra for URI round-trips', function () { + const proxy = parseOne( + `vless://${UUID}@vless-xhttp.example.com:443?type=xhttp&security=tls&host=cdn.example.com&path=%2Fxhttp&mode=stream-up&extra=${encodeURIComponent( + '{bad', + )}#VLESS%20XHTTP%20Invalid%20Extra`, + ); + + expectSubset(proxy, { + type: 'vless', + name: 'VLESS XHTTP Invalid Extra', + server: 'vless-xhttp.example.com', + port: 443, + uuid: UUID, + tls: true, + network: 'xhttp', + _extra: '{bad', + 'xhttp-opts': { + mode: 'stream-up', + path: '/xhttp', + headers: { + Host: 'cdn.example.com', + }, + }, + }); + expect(proxy).to.not.have.property('_extra_unsupported'); + }); + it('parses xhttp VLESS shares with range-form scMinPostsIntervalMs', function () { const extra = JSON.stringify({ noGRPCHeader: true, @@ -813,7 +978,6 @@ describe('VMess and VLESS parser coverage', function () { uuid: UUID, tls: true, network: 'xhttp', - _extra: extra, 'xhttp-opts': { mode: 'stream-up', path: '/xhttp', @@ -822,7 +986,7 @@ describe('VMess and VLESS parser coverage', function () { }, 'no-grpc-header': true, 'x-padding-bytes': '64-128', - 'sc-min-posts-interval-ms': 300, + 'sc-min-posts-interval-ms': '100-300', 'reuse-settings': { 'max-connections': '0', 'max-concurrency': '16-32', @@ -861,7 +1025,6 @@ describe('VMess and VLESS parser coverage', function () { uuid: UUID, tls: true, network: 'xhttp', - _extra: extra, 'xhttp-opts': { mode: 'stream-up', path: '/xhttp', @@ -909,7 +1072,6 @@ describe('VMess and VLESS parser coverage', function () { uuid: UUID, tls: true, network: 'xhttp', - _extra: extra, 'xhttp-opts': { mode: 'stream-up', path: '/xhttp', @@ -918,7 +1080,7 @@ describe('VMess and VLESS parser coverage', function () { }, 'no-grpc-header': true, 'x-padding-bytes': '64-128', - 'sc-min-posts-interval-ms': 300, + 'sc-min-posts-interval-ms': '0-300', 'reuse-settings': { 'max-connections': '0', 'max-concurrency': '16-32', @@ -962,7 +1124,6 @@ describe('VMess and VLESS parser coverage', function () { uuid: UUID, tls: true, network: 'xhttp', - _extra: extra, 'xhttp-opts': { mode: 'stream-up', path: '/xhttp', @@ -980,7 +1141,7 @@ describe('VMess and VLESS parser coverage', function () { path: '/download', host: 'download-host.example.com', 'sc-max-each-post-bytes': 1000000, - 'sc-min-posts-interval-ms': 300, + 'sc-min-posts-interval-ms': '0-300', }, }, }); @@ -1018,7 +1179,6 @@ describe('VMess and VLESS parser coverage', function () { uuid: UUID, tls: true, network: 'xhttp', - _extra: extra, 'xhttp-opts': { mode: 'stream-up', path: '/xhttp', @@ -1036,7 +1196,7 @@ describe('VMess and VLESS parser coverage', function () { path: '/download', host: 'download-host.example.com', 'sc-max-each-post-bytes': 1000000, - 'sc-min-posts-interval-ms': 300, + 'sc-min-posts-interval-ms': '0-300', }, }, }); @@ -1081,7 +1241,6 @@ describe('VMess and VLESS parser coverage', function () { uuid: UUID, tls: true, network: 'xhttp', - _extra: extra, 'xhttp-opts': { mode: 'stream-up', path: '/xhttp', @@ -1102,6 +1261,9 @@ describe('VMess and VLESS parser coverage', function () { expect(proxy['xhttp-opts']).to.not.have.property( 'sc-min-posts-interval-ms', ); + expect(proxy._extra_unsupported).to.deep.equal({ + scMinPostsIntervalMs: value, + }); } }); @@ -1136,7 +1298,6 @@ describe('VMess and VLESS parser coverage', function () { uuid: UUID, tls: true, network: 'xhttp', - _extra: extra, 'xhttp-opts': { mode: 'stream-up', path: '/xhttp', @@ -1158,6 +1319,354 @@ describe('VMess and VLESS parser coverage', function () { expect( proxy['xhttp-opts']?.['download-settings'], ).to.not.have.property('sc-min-posts-interval-ms'); + expect(proxy._extra_unsupported).to.deep.equal({ + downloadSettings: { + xhttpSettings: { + scMinPostsIntervalMs: '0-0', + }, + }, + }); + }); + + it('parses extended xhttp VLESS extra fields and keeps unsupported fields in _extra_unsupported', function () { + const extra = JSON.stringify({ + headers: { + 'X-Test': 'demo', + }, + noGRPCHeader: true, + xPaddingBytes: '64-128', + xPaddingObfsMode: true, + xPaddingKey: 'x_padding', + xPaddingHeader: 'Referer', + xPaddingPlacement: 'header', + xPaddingMethod: 'tokenish', + uplinkHTTPMethod: 'PUT', + sessionPlacement: 'query', + sessionKey: 'x_session_id', + seqPlacement: 'header', + seqKey: 'X-Seq', + uplinkDataPlacement: 'header', + uplinkDataKey: 'X-Data', + uplinkChunkSize: '64-128', + xmux: { + maxConcurrency: '16-32', + hKeepAlivePeriod: 15, + }, + noSSEHeader: true, + downloadSettings: { + address: 'download.example.com', + port: 8443, + security: 'tls', + tlsSettings: { + serverName: 'download-sni.example.com', + fingerprint: 'chrome', + allowInsecure: true, + alpn: ['h2'], + echConfigList: 'ECHCONFIG', + }, + xhttpSettings: { + path: '/download', + host: 'download-host.example.com', + headers: { + 'X-Download': '1', + }, + noGRPCHeader: true, + xPaddingBytes: '16-32', + xPaddingObfsMode: true, + xPaddingKey: 'x_padding_dl', + xPaddingHeader: 'Cookie', + xPaddingPlacement: 'query', + xPaddingMethod: 'repeat-x', + uplinkHTTPMethod: 'PATCH', + sessionPlacement: 'header', + sessionKey: 'X-Session', + seqPlacement: 'query', + seqKey: 'x_seq', + uplinkDataPlacement: 'cookie', + uplinkDataKey: 'x_data', + uplinkChunkSize: 48, + extra: { + xmux: { + maxConcurrency: '8-16', + hKeepAlivePeriod: -1, + }, + }, + }, + sockopt: { + mark: 255, + }, + }, + }); + const proxy = parseOne( + `vless://${UUID}@vless-xhttp.example.com:443?type=xhttp&security=tls&host=cdn.example.com&path=%2Fxhttp&mode=stream-up&extra=${encodeURIComponent( + extra, + )}#VLESS%20XHTTP%20Extended%20Extra`, + ); + + expectSubset(proxy, { + type: 'vless', + name: 'VLESS XHTTP Extended Extra', + server: 'vless-xhttp.example.com', + port: 443, + uuid: UUID, + tls: true, + network: 'xhttp', + 'xhttp-opts': { + mode: 'stream-up', + path: '/xhttp', + headers: { + Host: 'cdn.example.com', + 'X-Test': 'demo', + }, + 'no-grpc-header': true, + 'x-padding-bytes': '64-128', + 'x-padding-obfs-mode': true, + 'x-padding-key': 'x_padding', + 'x-padding-header': 'Referer', + 'x-padding-placement': 'header', + 'x-padding-method': 'tokenish', + 'uplink-http-method': 'PUT', + 'session-placement': 'query', + 'session-key': 'x_session_id', + 'seq-placement': 'header', + 'seq-key': 'X-Seq', + 'uplink-data-placement': 'header', + 'uplink-data-key': 'X-Data', + 'uplink-chunk-size': '64-128', + 'reuse-settings': { + 'max-concurrency': '16-32', + 'h-keep-alive-period': 15, + }, + 'download-settings': { + server: 'download.example.com', + port: 8443, + tls: true, + servername: 'download-sni.example.com', + 'client-fingerprint': 'chrome', + 'skip-cert-verify': true, + alpn: ['h2'], + 'ech-opts': { + enable: true, + config: 'ECHCONFIG', + }, + path: '/download', + host: 'download-host.example.com', + headers: { + 'X-Download': '1', + }, + 'no-grpc-header': true, + 'x-padding-bytes': '16-32', + 'x-padding-obfs-mode': true, + 'x-padding-key': 'x_padding_dl', + 'x-padding-header': 'Cookie', + 'x-padding-placement': 'query', + 'x-padding-method': 'repeat-x', + 'uplink-http-method': 'PATCH', + 'session-placement': 'header', + 'session-key': 'X-Session', + 'seq-placement': 'query', + 'seq-key': 'x_seq', + 'uplink-data-placement': 'cookie', + 'uplink-data-key': 'x_data', + 'uplink-chunk-size': 48, + 'reuse-settings': { + 'max-concurrency': '8-16', + 'h-keep-alive-period': -1, + }, + }, + }, + }); + + expect(proxy).to.not.have.property('_extra'); + expect(proxy._extra_unsupported).to.deep.equal({ + noSSEHeader: true, + downloadSettings: { + sockopt: { + mark: 255, + }, + }, + }); + expect(proxy['xhttp-opts']).to.not.have.property('no-sse-header'); + expect( + proxy['xhttp-opts']?.['download-settings'], + ).to.not.have.property('sockopt'); + }); + + it('parses xhttp VLESS xmux ranges canonically and keeps unsupported keep-alive values in _extra_unsupported', function () { + const extra = JSON.stringify({ + xmux: { + maxConnections: '+0008', + maxConcurrency: '0008-0016', + hKeepAlivePeriod: '9007199254740993', + }, + }); + const proxy = parseOne( + `vless://${UUID}@vless-xhttp.example.com:443?type=xhttp&security=tls&host=cdn.example.com&path=%2Fxhttp&mode=stream-up&extra=${encodeURIComponent( + extra, + )}#VLESS%20XHTTP%20XMUX%20Canonical`, + ); + + expectSubset(proxy, { + type: 'vless', + network: 'xhttp', + 'xhttp-opts': { + mode: 'stream-up', + path: '/xhttp', + headers: { + Host: 'cdn.example.com', + }, + 'reuse-settings': { + 'max-connections': '8', + 'max-concurrency': '8-16', + }, + }, + }); + expect(proxy['xhttp-opts']?.['reuse-settings']).to.not.have.property( + 'h-keep-alive-period', + ); + expect(proxy._extra_unsupported).to.deep.equal({ + xmux: { + hKeepAlivePeriod: '9007199254740993', + }, + }); + }); + + it('parses xhttp VLESS shares with string downloadSettings ports as structured values', function () { + const extra = JSON.stringify({ + downloadSettings: { + address: 'download.example.com', + port: '8443', + security: 'tls', + xhttpSettings: { + path: '/download', + }, + }, + }); + const proxy = parseOne( + `vless://${UUID}@vless-xhttp.example.com:443?type=xhttp&security=tls&host=cdn.example.com&path=%2Fxhttp&mode=stream-up&extra=${encodeURIComponent( + extra, + )}#VLESS%20XHTTP%20String%20Download%20Port`, + ); + + expectSubset(proxy, { + type: 'vless', + network: 'xhttp', + 'xhttp-opts': { + mode: 'stream-up', + path: '/xhttp', + headers: { + Host: 'cdn.example.com', + }, + 'download-settings': { + server: 'download.example.com', + port: 8443, + tls: true, + path: '/download', + }, + }, + }); + expect(proxy).to.not.have.property('_extra_unsupported'); + }); + + it('keeps malformed xhttp VLESS uplinkChunkSize values in _extra_unsupported', function () { + const extra = JSON.stringify({ + uplinkChunkSize: 'fast', + downloadSettings: { + address: 'download.example.com', + port: 8443, + security: 'tls', + xhttpSettings: { + path: '/download', + uplinkChunkSize: 'faster', + }, + }, + }); + const proxy = parseOne( + `vless://${UUID}@vless-xhttp.example.com:443?type=xhttp&security=tls&host=cdn.example.com&path=%2Fxhttp&mode=stream-up&extra=${encodeURIComponent( + extra, + )}#VLESS%20XHTTP%20Malformed%20Uplink%20Chunk`, + ); + + expectSubset(proxy, { + type: 'vless', + network: 'xhttp', + 'xhttp-opts': { + mode: 'stream-up', + path: '/xhttp', + headers: { + Host: 'cdn.example.com', + }, + 'download-settings': { + server: 'download.example.com', + port: 8443, + tls: true, + path: '/download', + }, + }, + }); + expect(proxy['xhttp-opts']).to.not.have.property( + 'uplink-chunk-size', + ); + expect( + proxy['xhttp-opts']?.['download-settings'], + ).to.not.have.property('uplink-chunk-size'); + expect(proxy._extra_unsupported).to.deep.equal({ + uplinkChunkSize: 'fast', + downloadSettings: { + xhttpSettings: { + uplinkChunkSize: 'faster', + }, + }, + }); + }); + + it('keeps mixed downloadSettings tlsSettings.alpn arrays in _extra_unsupported', function () { + const extra = JSON.stringify({ + downloadSettings: { + address: 'download.example.com', + port: 8443, + security: 'tls', + tlsSettings: { + alpn: ['h2', { foo: 1 }], + }, + xhttpSettings: { + path: '/download', + }, + }, + }); + const proxy = parseOne( + `vless://${UUID}@vless-xhttp.example.com:443?type=xhttp&security=tls&host=cdn.example.com&path=%2Fxhttp&mode=stream-up&extra=${encodeURIComponent( + extra, + )}#VLESS%20XHTTP%20Mixed%20ALPN`, + ); + + expectSubset(proxy, { + type: 'vless', + network: 'xhttp', + 'xhttp-opts': { + mode: 'stream-up', + path: '/xhttp', + headers: { + Host: 'cdn.example.com', + }, + 'download-settings': { + server: 'download.example.com', + port: 8443, + tls: true, + path: '/download', + }, + }, + }); + expect( + proxy['xhttp-opts']?.['download-settings'], + ).to.not.have.property('alpn'); + expect(proxy._extra_unsupported).to.deep.equal({ + downloadSettings: { + tlsSettings: { + alpn: ['h2', { foo: 1 }], + }, + }, + }); }); it('parses xhttp VLESS shares with range-form scMaxEachPostBytes', function () { @@ -1187,7 +1696,6 @@ describe('VMess and VLESS parser coverage', function () { uuid: UUID, tls: true, network: 'xhttp', - _extra: extra, 'xhttp-opts': { mode: 'stream-up', path: '/xhttp', @@ -1235,7 +1743,6 @@ describe('VMess and VLESS parser coverage', function () { uuid: UUID, tls: true, network: 'xhttp', - _extra: extra, 'xhttp-opts': { mode: 'stream-up', path: '/xhttp', @@ -1283,7 +1790,6 @@ describe('VMess and VLESS parser coverage', function () { uuid: UUID, tls: true, network: 'xhttp', - _extra: extra, 'xhttp-opts': { mode: 'stream-up', path: '/xhttp', @@ -1342,7 +1848,6 @@ describe('VMess and VLESS parser coverage', function () { uuid: UUID, tls: true, network: 'xhttp', - _extra: extra, 'xhttp-opts': { mode: 'stream-up', path: '/xhttp', @@ -1363,6 +1868,9 @@ describe('VMess and VLESS parser coverage', function () { expect(proxy['xhttp-opts']).to.not.have.property( 'sc-max-each-post-bytes', ); + expect(proxy._extra_unsupported).to.deep.equal({ + scMaxEachPostBytes: value, + }); } }); diff --git a/backend/src/test/proxy-producers/structured.spec.js b/backend/src/test/proxy-producers/structured.spec.js index 98d17857..e54708e2 100644 --- a/backend/src/test/proxy-producers/structured.spec.js +++ b/backend/src/test/proxy-producers/structured.spec.js @@ -363,6 +363,38 @@ describe('Proxy structured producers', function () { }); }); + it('skips Mihomo VLESS xhttp stream-one proxies when download-settings are present', function () { + const proxy = { + type: 'vless', + name: 'XHTTP Stream One Download', + server: 'vless-xhttp.example.com', + port: 443, + uuid: UUID, + tls: true, + sni: 'sni.example.com', + network: 'xhttp', + 'xhttp-opts': { + path: '/xhttp', + headers: { + Host: 'cdn.example.com', + }, + mode: 'stream-one', + 'download-settings': { + server: 'download.example.com', + port: 8443, + tls: true, + path: '/download', + }, + }, + }; + + const internal = produceInternal('Mihomo', proxy); + const external = ProxyUtils.produce([proxy], 'Mihomo', 'external'); + + expect(internal).to.have.length(0); + expect(external.trim()).to.equal('proxies:'); + }); + it('normalizes Stash TUIC defaults and external yaml wrapper', function () { const proxy = { type: 'tuic', diff --git a/backend/src/test/proxy-producers/text.spec.js b/backend/src/test/proxy-producers/text.spec.js index e17beef9..e44c13e4 100644 --- a/backend/src/test/proxy-producers/text.spec.js +++ b/backend/src/test/proxy-producers/text.spec.js @@ -316,8 +316,7 @@ describe('Proxy text producers', function () { sni: 'apple.com', udp: true, 'reality-opts': { - 'public-key': - 'k4Uxez0sjl8bKaZH2Vgi8-WDFshML51QkxKFLWFIONk', + 'public-key': 'k4Uxez0sjl8bKaZH2Vgi8-WDFshML51QkxKFLWFIONk', 'short-id': '0123456789abcdef', }, }); @@ -662,9 +661,7 @@ describe('Proxy text producers', function () { ]); const [explicit, defaults] = output.split('\n'); - expect(explicit).to.include( - 'address=10.0.0.2%2F24%2Cfd00%3A%3A2%2F64', - ); + expect(explicit).to.include('address=10.0.0.2%2F24%2Cfd00%3A%3A2%2F64'); expect(defaults).to.include( 'address=10.0.0.3%2F32%2Cfd00%3A%3A3%2F128', ); @@ -1019,13 +1016,14 @@ describe('Proxy text producers', function () { tls: true, sni: 'sni.example.com', network: 'xhttp', - _extra: extra, 'xhttp-opts': { path: '/xhttp', headers: { Host: 'cdn.example.com', }, mode: 'stream-up', + 'no-grpc-header': true, + 'x-padding-bytes': '64-128', }, }); @@ -1036,24 +1034,25 @@ describe('Proxy text producers', function () { ); }); - it('prefers raw _extra over structured xhttp fields when producing URI VLESS links', function () { - const extra = JSON.stringify({ - customField: 'keep-me', - downloadSettings: { - address: 'old.example.com', - port: 443, - }, - }); + it('preserves _extra_unsupported without letting it override structured xhttp fields when producing URI VLESS links', function () { const output = produceExternal('URI', { type: 'vless', - name: 'URI XHTTP Raw Extra', + name: 'URI XHTTP Unsupported Extra', server: 'vless-xhttp.example.com', port: 443, uuid: UUID, tls: true, sni: 'sni.example.com', network: 'xhttp', - _extra: extra, + _extra_unsupported: { + customField: 'keep-me', + downloadSettings: { + sockopt: { + mark: 255, + }, + address: 'old.example.com', + }, + }, 'xhttp-opts': { path: '/xhttp', mode: 'stream-up', @@ -1065,35 +1064,55 @@ describe('Proxy text producers', function () { server: 'download.example.com', port: 8443, tls: true, + path: '/download', + host: 'download-host.example.com', }, }, }); - expect(output).to.equal( - `vless://${UUID}@vless-xhttp.example.com:443?security=tls&type=xhttp&path=%2Fxhttp&host=cdn.example.com&sni=sni.example.com&mode=stream-up&extra=${encodeURIComponent( - extra, - )}#URI%20XHTTP%20Raw%20Extra`, + const [, encodedExtra] = output.match(/[?&]extra=([^#]+)/); + const extra = JSON.parse(decodeURIComponent(encodedExtra)); + expect(extra.customField).to.equal('keep-me'); + expect(extra.noGRPCHeader).to.equal(true); + expect(extra.downloadSettings?.address).to.equal( + 'download.example.com', + ); + expect(extra.downloadSettings?.port).to.equal(8443); + expect(extra.downloadSettings?.network).to.equal('xhttp'); + expect(extra.downloadSettings?.security).to.equal('tls'); + expect(extra.downloadSettings?.sockopt).to.deep.equal({ + mark: 255, + }); + expect(extra.downloadSettings?.xhttpSettings?.path).to.equal( + '/download', + ); + expect(extra.downloadSettings?.xhttpSettings?.host).to.equal( + 'download-host.example.com', ); - }); - it('normalizes raw xhttp sc scalars from _extra when structured xhttp fields exist', function () { - const rawExtra = JSON.stringify({ + const reparsed = ProxyUtils.parse(output); + expect(reparsed, output).to.have.length(1); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.server, + ).to.equal('download.example.com'); + expect(reparsed[0]._extra_unsupported).to.deep.equal({ customField: 'keep-me', - scMaxEachPostBytes: '000-1000000', - scMinPostsIntervalMs: '0300', downloadSettings: { - address: 'download.example.com', - port: 8443, - security: 'tls', - xhttpSettings: { - scMaxEachPostBytes: '000-1000000', - scMinPostsIntervalMs: '000-300', + sockopt: { + mark: 255, }, }, }); + }); + + it('uses string _extra as the final xhttp URI extra without rebuilding it', function () { + const rawExtra = JSON.stringify({ + customField: 'keep-me', + scMinPostsIntervalMs: '0-300', + }); const output = produceExternal('URI', { type: 'vless', - name: 'URI XHTTP Raw Extra Scalars', + name: 'URI XHTTP Raw Extra String', server: 'vless-xhttp.example.com', port: 443, uuid: UUID, @@ -1101,6 +1120,137 @@ describe('Proxy text producers', function () { sni: 'sni.example.com', network: 'xhttp', _extra: rawExtra, + 'xhttp-opts': { + path: '/xhttp', + mode: 'stream-up', + headers: { + Host: 'cdn.example.com', + }, + 'sc-min-posts-interval-ms': 300, + }, + }); + + const [, encodedExtra] = output.match(/[?&]extra=([^#]+)/); + expect(decodeURIComponent(encodedExtra)).to.equal(rawExtra); + + const reparsed = ProxyUtils.parse(output); + expect(reparsed, output).to.have.length(1); + expect( + reparsed[0]['xhttp-opts']?.['sc-min-posts-interval-ms'], + ).to.equal('0-300'); + }); + + it('stringifies plain-object _extra before using it as the final xhttp URI extra', function () { + const rawExtra = { + customField: 'keep-me', + scMinPostsIntervalMs: '0-300', + }; + const output = produceExternal('URI', { + type: 'vless', + name: 'URI XHTTP Raw Extra Object', + server: 'vless-xhttp.example.com', + port: 443, + uuid: UUID, + tls: true, + sni: 'sni.example.com', + network: 'xhttp', + _extra: rawExtra, + 'xhttp-opts': { + path: '/xhttp', + mode: 'stream-up', + headers: { + Host: 'cdn.example.com', + }, + 'sc-min-posts-interval-ms': 300, + }, + }); + + const [, encodedExtra] = output.match(/[?&]extra=([^#]+)/); + expect(JSON.parse(decodeURIComponent(encodedExtra))).to.deep.equal( + rawExtra, + ); + + const reparsed = ProxyUtils.parse(output); + expect(reparsed, output).to.have.length(1); + expect( + reparsed[0]['xhttp-opts']?.['sc-min-posts-interval-ms'], + ).to.equal('0-300'); + }); + + it('prefers explicit _extra over _extra_unsupported when both are present', function () { + const rawExtra = JSON.stringify({ + customField: 'raw-wins', + scMinPostsIntervalMs: '0-300', + }); + const output = produceExternal('URI', { + type: 'vless', + name: 'URI XHTTP Raw Extra Wins', + server: 'vless-xhttp.example.com', + port: 443, + uuid: UUID, + tls: true, + sni: 'sni.example.com', + network: 'xhttp', + _extra: rawExtra, + _extra_unsupported: { + customField: 'stale-sidecar', + downloadSettings: { + sockopt: { + mark: 255, + }, + }, + }, + 'xhttp-opts': { + path: '/xhttp', + mode: 'stream-up', + headers: { + Host: 'cdn.example.com', + }, + 'sc-min-posts-interval-ms': 300, + 'download-settings': { + server: 'download.example.com', + port: 8443, + tls: true, + }, + }, + }); + + const [, encodedExtra] = output.match(/[?&]extra=([^#]+)/); + expect(decodeURIComponent(encodedExtra)).to.equal(rawExtra); + + const reparsed = ProxyUtils.parse(output); + expect(reparsed, output).to.have.length(1); + expect( + reparsed[0]['xhttp-opts']?.['sc-min-posts-interval-ms'], + ).to.equal('0-300'); + expect(reparsed[0]._extra_unsupported).to.deep.equal({ + customField: 'raw-wins', + }); + }); + + it('keeps structured xhttp scalar normalization even if _extra_unsupported carries conflicting raw fields', function () { + const output = produceExternal('URI', { + type: 'vless', + name: 'URI XHTTP Unsupported Extra Scalars', + server: 'vless-xhttp.example.com', + port: 443, + uuid: UUID, + tls: true, + sni: 'sni.example.com', + network: 'xhttp', + _extra_unsupported: { + customField: 'keep-me', + scMaxEachPostBytes: '000-1000000', + scMinPostsIntervalMs: '0300', + uplinkChunkSize: '00064 - 00128', + downloadSettings: { + xhttpSettings: { + scMaxEachPostBytes: '000-1000000', + scMinPostsIntervalMs: '000-300', + uplinkChunkSize: '00048', + }, + }, + }, 'xhttp-opts': { path: '/xhttp', mode: 'stream-up', @@ -1109,12 +1259,14 @@ describe('Proxy text producers', function () { }, 'sc-max-each-post-bytes': 1000000, 'sc-min-posts-interval-ms': 300, + 'uplink-chunk-size': '00064 - 00128', 'download-settings': { server: 'download.example.com', port: 8443, tls: true, 'sc-max-each-post-bytes': 1000000, 'sc-min-posts-interval-ms': 300, + 'uplink-chunk-size': '00048', }, }, }); @@ -1124,21 +1276,277 @@ describe('Proxy text producers', function () { expect(extra.customField).to.equal('keep-me'); expect(extra.scMaxEachPostBytes).to.equal(1000000); expect(extra.scMinPostsIntervalMs).to.equal(300); - expect(extra.downloadSettings?.xhttpSettings?.scMaxEachPostBytes).to.equal( - 1000000, - ); + expect(extra.uplinkChunkSize).to.equal('64-128'); + expect( + extra.downloadSettings?.xhttpSettings?.scMaxEachPostBytes, + ).to.equal(1000000); expect( extra.downloadSettings?.xhttpSettings?.scMinPostsIntervalMs, ).to.equal(300); + expect(extra.downloadSettings?.xhttpSettings?.uplinkChunkSize).to.equal( + 48, + ); const reparsed = ProxyUtils.parse(output); expect(reparsed, output).to.have.length(1); expect(reparsed[0]['xhttp-opts']?.['sc-max-each-post-bytes']).to.equal( 1000000, ); - expect(reparsed[0]['xhttp-opts']?.['sc-min-posts-interval-ms']).to.equal( - 300, + expect( + reparsed[0]['xhttp-opts']?.['sc-min-posts-interval-ms'], + ).to.equal(300); + expect(reparsed[0]['xhttp-opts']?.['uplink-chunk-size']).to.equal( + '64-128', ); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.[ + 'uplink-chunk-size' + ], + ).to.equal(48); + expect(reparsed[0]._extra_unsupported).to.deep.equal({ + customField: 'keep-me', + }); + }); + + it('round-trips unsupported xhttp extra sidecar values without dropping them', function () { + const rawExtra = JSON.stringify({ + uplinkChunkSize: 'fast', + xmux: { + hKeepAlivePeriod: '9007199254740993', + }, + downloadSettings: { + address: 'download.example.com', + port: 8443, + security: 'tls', + tlsSettings: { + alpn: ['h2', { foo: 1 }], + }, + xhttpSettings: { + path: '/download', + }, + }, + }); + const [parsed] = ProxyUtils.parse( + `vless://${UUID}@vless-xhttp.example.com:443?security=tls&type=xhttp&path=%2Fxhttp&host=cdn.example.com&sni=sni.example.com&mode=stream-up&extra=${encodeURIComponent( + rawExtra, + )}#URI%20XHTTP%20Unsupported%20Roundtrip`, + ); + const output = produceExternal('URI', parsed); + + const [, encodedExtra] = output.match(/[?&]extra=([^#]+)/); + const extra = JSON.parse(decodeURIComponent(encodedExtra)); + expect(extra.uplinkChunkSize).to.equal('fast'); + expect(extra.xmux).to.deep.equal({ + hKeepAlivePeriod: '9007199254740993', + }); + expect(extra.downloadSettings?.address).to.equal('download.example.com'); + expect(extra.downloadSettings?.port).to.equal(8443); + expect(extra.downloadSettings?.network).to.equal('xhttp'); + expect(extra.downloadSettings?.security).to.equal('tls'); + expect(extra.downloadSettings?.tlsSettings?.alpn).to.deep.equal([ + 'h2', + { foo: 1 }, + ]); + expect(extra.downloadSettings?.xhttpSettings?.path).to.equal( + '/download', + ); + + const reparsed = ProxyUtils.parse(output); + expect(reparsed, output).to.have.length(1); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.network, + ).to.equal('xhttp'); + expect(reparsed[0]).to.have.property('_extra_unsupported'); + expect(reparsed[0]._extra_unsupported).to.deep.equal({ + uplinkChunkSize: 'fast', + xmux: { + hKeepAlivePeriod: '9007199254740993', + }, + downloadSettings: { + tlsSettings: { + alpn: ['h2', { foo: 1 }], + }, + }, + }); + }); + + it('round-trips unsupported-only nested download settings with structured xhttp network', function () { + const rawExtra = JSON.stringify({ + downloadSettings: { + network: 'xhttp', + sockopt: { + mark: 255, + }, + }, + }); + const [parsed] = ProxyUtils.parse( + `vless://${UUID}@vless-xhttp.example.com:443?security=tls&type=xhttp&path=%2Fxhttp&host=cdn.example.com&sni=sni.example.com&mode=stream-up&extra=${encodeURIComponent( + rawExtra, + )}#URI%20XHTTP%20Download%20Unsupported%20Only`, + ); + expect(parsed['xhttp-opts']?.['download-settings']).to.deep.equal({ + network: 'xhttp', + }); + expect(parsed._extra_unsupported).to.deep.equal({ + downloadSettings: { + sockopt: { + mark: 255, + }, + }, + }); + + const output = produceExternal('URI', parsed); + const [, encodedExtra] = output.match(/[?&]extra=([^#]+)/); + const extra = JSON.parse(decodeURIComponent(encodedExtra)); + expect(extra.downloadSettings).to.deep.equal({ + network: 'xhttp', + sockopt: { + mark: 255, + }, + }); + + const reparsed = ProxyUtils.parse(output); + expect(reparsed, output).to.have.length(1); + expect(reparsed[0]['xhttp-opts']?.['download-settings']).to.deep.equal( + { + network: 'xhttp', + }, + ); + expect(reparsed[0]._extra_unsupported).to.deep.equal({ + downloadSettings: { + sockopt: { + mark: 255, + }, + }, + }); + }); + + it('keeps structured nested xhttp network out of mixed download settings sidecars', function () { + const rawExtra = JSON.stringify({ + downloadSettings: { + address: 'download.example.com', + network: 'xhttp', + port: 8443, + security: 'tls', + xhttpSettings: { + path: '/download', + }, + sockopt: { + mark: 255, + }, + }, + }); + const [parsed] = ProxyUtils.parse( + `vless://${UUID}@vless-xhttp.example.com:443?security=tls&type=xhttp&path=%2Fxhttp&host=cdn.example.com&sni=sni.example.com&mode=stream-up&extra=${encodeURIComponent( + rawExtra, + )}#URI%20XHTTP%20Download%20Mixed%20Sidecar`, + ); + + expect(parsed['xhttp-opts']?.['download-settings']).to.deep.equal({ + network: 'xhttp', + server: 'download.example.com', + port: 8443, + tls: true, + path: '/download', + }); + expect(parsed._extra_unsupported).to.deep.equal({ + downloadSettings: { + sockopt: { + mark: 255, + }, + }, + }); + + delete parsed['xhttp-opts']['download-settings']; + + const output = produceExternal('URI', parsed); + const [, encodedExtra] = output.match(/[?&]extra=([^#]+)/); + const extra = JSON.parse(decodeURIComponent(encodedExtra)); + expect(extra.downloadSettings).to.deep.equal({ + sockopt: { + mark: 255, + }, + }); + }); + + it('round-trips invalid xhttp extra strings through _extra', function () { + const rawExtra = '{bad'; + const [parsed] = ProxyUtils.parse( + `vless://${UUID}@vless-xhttp.example.com:443?security=tls&type=xhttp&path=%2Fxhttp&host=cdn.example.com&sni=sni.example.com&mode=stream-up&extra=${encodeURIComponent( + rawExtra, + )}#URI%20XHTTP%20Invalid%20Extra`, + ); + + expect(parsed._extra).to.equal(rawExtra); + + const output = produceExternal('URI', parsed); + const [, encodedExtra] = output.match(/[?&]extra=([^#]+)/); + expect(decodeURIComponent(encodedExtra)).to.equal(rawExtra); + }); + + it('normalizes structured xhttp xmux values when producing URI VLESS links', function () { + const output = produceExternal('URI', { + type: 'vless', + name: 'URI XHTTP XMUX', + server: 'vless-xhttp.example.com', + port: 443, + uuid: UUID, + tls: true, + sni: 'sni.example.com', + network: 'xhttp', + 'xhttp-opts': { + path: '/xhttp', + mode: 'stream-up', + headers: { + Host: 'cdn.example.com', + }, + 'reuse-settings': { + 'max-connections': '+0008', + 'max-concurrency': '0008-0016', + 'h-keep-alive-period': '+15', + }, + 'download-settings': { + server: 'download.example.com', + port: 8443, + tls: true, + path: '/download', + 'reuse-settings': { + 'h-max-request-times': '+0004-0008', + 'h-keep-alive-period': -1, + }, + }, + }, + }); + + const [, encodedExtra] = output.match(/[?&]extra=([^#]+)/); + const extra = JSON.parse(decodeURIComponent(encodedExtra)); + expect(extra.xmux).to.deep.equal({ + maxConnections: '8', + maxConcurrency: '8-16', + hKeepAlivePeriod: 15, + }); + expect(extra.downloadSettings?.xhttpSettings?.extra?.xmux).to.deep.equal( + { + hMaxRequestTimes: '4-8', + hKeepAlivePeriod: -1, + }, + ); + + const reparsed = ProxyUtils.parse(output); + expect(reparsed, output).to.have.length(1); + expect(reparsed[0]['xhttp-opts']?.['reuse-settings']).to.deep.equal({ + 'max-connections': '8', + 'max-concurrency': '8-16', + 'h-keep-alive-period': 15, + }); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.[ + 'reuse-settings' + ], + ).to.deep.equal({ + 'h-max-request-times': '4-8', + 'h-keep-alive-period': -1, + }); }); it('produces URI VLESS xhttp links with structured scMinPostsIntervalMs', function () { @@ -1184,9 +1592,181 @@ describe('Proxy text producers', function () { const reparsed = ProxyUtils.parse(output); expect(reparsed, output).to.have.length(1); - expect(reparsed[0]['xhttp-opts']?.['sc-min-posts-interval-ms']).to.equal( - 300, + expect( + reparsed[0]['xhttp-opts']?.['sc-min-posts-interval-ms'], + ).to.equal(300); + }); + + it('produces URI VLESS xhttp links with extended structured extra fields', function () { + const extra = JSON.stringify({ + headers: { + 'X-Test': 'demo', + }, + noGRPCHeader: true, + xPaddingBytes: '64-128', + xPaddingObfsMode: true, + xPaddingKey: 'x_padding', + xPaddingHeader: 'Referer', + xPaddingPlacement: 'header', + xPaddingMethod: 'tokenish', + uplinkHTTPMethod: 'PUT', + sessionPlacement: 'query', + sessionKey: 'x_session_id', + seqPlacement: 'header', + seqKey: 'X-Seq', + uplinkDataPlacement: 'header', + uplinkDataKey: 'X-Data', + uplinkChunkSize: '64-128', + xmux: { + maxConcurrency: '16-32', + hKeepAlivePeriod: 15, + }, + downloadSettings: { + address: 'download.example.com', + network: 'xhttp', + port: 8443, + security: 'tls', + tlsSettings: { + serverName: 'download-sni.example.com', + fingerprint: 'chrome', + allowInsecure: true, + alpn: ['h2'], + echConfigList: 'ECHCONFIG', + }, + xhttpSettings: { + path: '/download', + host: 'download-host.example.com', + headers: { + 'X-Download': '1', + }, + noGRPCHeader: true, + xPaddingBytes: '16-32', + xPaddingObfsMode: true, + xPaddingKey: 'x_padding_dl', + xPaddingHeader: 'Cookie', + xPaddingPlacement: 'query', + xPaddingMethod: 'repeat-x', + uplinkHTTPMethod: 'PATCH', + sessionPlacement: 'header', + sessionKey: 'X-Session', + seqPlacement: 'query', + seqKey: 'x_seq', + uplinkDataPlacement: 'cookie', + uplinkDataKey: 'x_data', + uplinkChunkSize: 48, + extra: { + xmux: { + maxConcurrency: '8-16', + hKeepAlivePeriod: -1, + }, + }, + }, + }, + }); + const output = produceExternal('URI', { + type: 'vless', + name: 'URI XHTTP Extended', + server: 'vless-xhttp.example.com', + port: 443, + uuid: UUID, + tls: true, + sni: 'sni.example.com', + network: 'xhttp', + 'xhttp-opts': { + path: '/xhttp', + mode: 'stream-up', + headers: { + Host: 'cdn.example.com', + 'X-Test': 'demo', + }, + 'no-grpc-header': true, + 'x-padding-bytes': '64-128', + 'x-padding-obfs-mode': true, + 'x-padding-key': 'x_padding', + 'x-padding-header': 'Referer', + 'x-padding-placement': 'header', + 'x-padding-method': 'tokenish', + 'uplink-http-method': 'PUT', + 'session-placement': 'query', + 'session-key': 'x_session_id', + 'seq-placement': 'header', + 'seq-key': 'X-Seq', + 'uplink-data-placement': 'header', + 'uplink-data-key': 'X-Data', + 'uplink-chunk-size': '64-128', + 'reuse-settings': { + 'max-concurrency': '16-32', + 'h-keep-alive-period': 15, + }, + 'download-settings': { + server: 'download.example.com', + port: 8443, + tls: true, + servername: 'download-sni.example.com', + 'client-fingerprint': 'chrome', + 'skip-cert-verify': true, + alpn: ['h2'], + 'ech-opts': { + enable: true, + config: 'ECHCONFIG', + }, + path: '/download', + host: 'download-host.example.com', + headers: { + 'X-Download': '1', + }, + 'no-grpc-header': true, + 'x-padding-bytes': '16-32', + 'x-padding-obfs-mode': true, + 'x-padding-key': 'x_padding_dl', + 'x-padding-header': 'Cookie', + 'x-padding-placement': 'query', + 'x-padding-method': 'repeat-x', + 'uplink-http-method': 'PATCH', + 'session-placement': 'header', + 'session-key': 'X-Session', + 'seq-placement': 'query', + 'seq-key': 'x_seq', + 'uplink-data-placement': 'cookie', + 'uplink-data-key': 'x_data', + 'uplink-chunk-size': 48, + 'reuse-settings': { + 'max-concurrency': '8-16', + 'h-keep-alive-period': -1, + }, + }, + }, + }); + + expect(output).to.equal( + `vless://${UUID}@vless-xhttp.example.com:443?security=tls&type=xhttp&path=%2Fxhttp&host=cdn.example.com&sni=sni.example.com&mode=stream-up&extra=${encodeURIComponent( + extra, + )}#URI%20XHTTP%20Extended`, ); + + const reparsed = ProxyUtils.parse(output); + expect(reparsed, output).to.have.length(1); + expect(reparsed[0]['xhttp-opts']?.headers?.['X-Test']).to.equal('demo'); + expect( + reparsed[0]['xhttp-opts']?.['reuse-settings']?.[ + 'h-keep-alive-period' + ], + ).to.equal(15); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.headers?.[ + 'X-Download' + ], + ).to.equal('1'); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.[ + 'uplink-chunk-size' + ], + ).to.equal(48); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.[ + 'reuse-settings' + ]?.['h-keep-alive-period'], + ).to.equal(-1); }); it('normalizes Mihomo leading-zero structured xhttp scalars when producing URI VLESS links', function () { @@ -1195,13 +1775,14 @@ describe('Proxy text producers', function () { scMinPostsIntervalMs: 300, downloadSettings: { address: 'download.example.com', + network: 'xhttp', port: 8443, security: 'tls', xhttpSettings: { path: '/download', host: 'download-host.example.com', scMaxEachPostBytes: 1000000, - scMinPostsIntervalMs: 300, + scMinPostsIntervalMs: '0-300', }, }, }); @@ -1242,12 +1823,12 @@ describe('Proxy text producers', function () { const reparsed = ProxyUtils.parse(output); expect(reparsed, output).to.have.length(1); - expect( - reparsed[0]['xhttp-opts']?.['sc-max-each-post-bytes'], - ).to.equal(1000000); - expect(reparsed[0]['xhttp-opts']?.['sc-min-posts-interval-ms']).to.equal( - 300, + expect(reparsed[0]['xhttp-opts']?.['sc-max-each-post-bytes']).to.equal( + 1000000, ); + expect( + reparsed[0]['xhttp-opts']?.['sc-min-posts-interval-ms'], + ).to.equal(300); expect( reparsed[0]['xhttp-opts']?.['download-settings']?.[ 'sc-max-each-post-bytes' @@ -1257,7 +1838,7 @@ describe('Proxy text producers', function () { reparsed[0]['xhttp-opts']?.['download-settings']?.[ 'sc-min-posts-interval-ms' ], - ).to.equal(300); + ).to.equal('0-300'); }); it('normalizes Mihomo explicit-plus structured xhttp scalars when producing URI VLESS links', function () { @@ -1266,13 +1847,14 @@ describe('Proxy text producers', function () { scMinPostsIntervalMs: 300, downloadSettings: { address: 'download.example.com', + network: 'xhttp', port: 8443, security: 'tls', xhttpSettings: { path: '/download', host: 'download-host.example.com', scMaxEachPostBytes: 1000000, - scMinPostsIntervalMs: 300, + scMinPostsIntervalMs: '0-300', }, }, }); @@ -1313,12 +1895,12 @@ describe('Proxy text producers', function () { const reparsed = ProxyUtils.parse(output); expect(reparsed, output).to.have.length(1); - expect( - reparsed[0]['xhttp-opts']?.['sc-max-each-post-bytes'], - ).to.equal(1000000); - expect(reparsed[0]['xhttp-opts']?.['sc-min-posts-interval-ms']).to.equal( - 300, + expect(reparsed[0]['xhttp-opts']?.['sc-max-each-post-bytes']).to.equal( + 1000000, ); + expect( + reparsed[0]['xhttp-opts']?.['sc-min-posts-interval-ms'], + ).to.equal(300); expect( reparsed[0]['xhttp-opts']?.['download-settings']?.[ 'sc-max-each-post-bytes' @@ -1328,7 +1910,7 @@ describe('Proxy text producers', function () { reparsed[0]['xhttp-opts']?.['download-settings']?.[ 'sc-min-posts-interval-ms' ], - ).to.equal(300); + ).to.equal('0-300'); }); it('produces URI VLESS xhttp links from structured download settings', function () { @@ -1340,6 +1922,7 @@ describe('Proxy text producers', function () { }, downloadSettings: { address: 'download.example.com', + network: 'xhttp', port: 8443, security: 'tls', tlsSettings: { @@ -1422,24 +2005,347 @@ describe('Proxy text producers', function () { ).to.equal(300); }); + it('normalizes structured xhttp uplinkChunkSize values when producing URI VLESS links', function () { + const output = produceExternal('URI', { + type: 'vless', + name: 'URI XHTTP Uplink Chunk Size', + server: 'vless-xhttp.example.com', + port: 443, + uuid: UUID, + tls: true, + sni: 'sni.example.com', + network: 'xhttp', + 'xhttp-opts': { + path: '/xhttp', + mode: 'stream-up', + headers: { + Host: 'cdn.example.com', + }, + 'uplink-chunk-size': '00064 - 00128', + 'download-settings': { + server: 'download.example.com', + port: 8443, + tls: true, + path: '/download', + host: 'download-host.example.com', + 'uplink-chunk-size': '00048', + }, + }, + }); + + const [, encodedExtra] = output.match(/[?&]extra=([^#]+)/); + const extra = JSON.parse(decodeURIComponent(encodedExtra)); + expect(extra.uplinkChunkSize).to.equal('64-128'); + expect(extra.downloadSettings?.xhttpSettings?.uplinkChunkSize).to.equal( + 48, + ); + + const reparsed = ProxyUtils.parse(output); + expect(reparsed, output).to.have.length(1); + expect(reparsed[0]['xhttp-opts']?.['uplink-chunk-size']).to.equal( + '64-128', + ); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.[ + 'uplink-chunk-size' + ], + ).to.equal(48); + }); + + it('preserves reality download settings TLS extras when producing URI VLESS links', function () { + const output = produceExternal('URI', { + type: 'vless', + name: 'URI XHTTP Reality Download', + server: 'vless-xhttp.example.com', + port: 443, + uuid: UUID, + tls: true, + sni: 'sni.example.com', + network: 'xhttp', + 'xhttp-opts': { + path: '/xhttp', + mode: 'stream-up', + headers: { + Host: 'cdn.example.com', + }, + 'download-settings': { + server: 'download.example.com', + port: 8443, + tls: true, + servername: 'download-sni.example.com', + 'client-fingerprint': 'chrome', + 'skip-cert-verify': true, + alpn: ['h2', 'http/1.1'], + 'ech-opts': { + enable: true, + config: 'ECHCONFIG', + }, + 'reality-opts': { + 'public-key': 'pubkey', + 'short-id': '08', + }, + path: '/download', + host: 'download-host.example.com', + }, + }, + }); + + const [, encodedExtra] = output.match(/[?&]extra=([^#]+)/); + const extra = JSON.parse(decodeURIComponent(encodedExtra)); + expect(extra.downloadSettings?.network).to.equal('xhttp'); + expect(extra.downloadSettings?.security).to.equal('reality'); + expect(extra.downloadSettings?.tlsSettings).to.deep.equal({ + serverName: 'download-sni.example.com', + fingerprint: 'chrome', + allowInsecure: true, + alpn: ['h2', 'http/1.1'], + echConfigList: 'ECHCONFIG', + }); + expect(extra.downloadSettings?.realitySettings).to.deep.equal({ + serverName: 'download-sni.example.com', + fingerprint: 'chrome', + publicKey: 'pubkey', + shortId: '08', + }); + + const reparsed = ProxyUtils.parse(output); + expect(reparsed, output).to.have.length(1); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.servername, + ).to.equal('download-sni.example.com'); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.[ + 'client-fingerprint' + ], + ).to.equal('chrome'); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.[ + 'skip-cert-verify' + ], + ).to.equal(true); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.alpn, + ).to.deep.equal(['h2', 'http/1.1']); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.['ech-opts'] + ?.config, + ).to.equal('ECHCONFIG'); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.['reality-opts'], + ).to.deep.equal({ + 'public-key': 'pubkey', + 'short-id': '08', + }); + }); + + it('skips URI VLESS exports when nested reality download settings are missing public keys', function () { + const rawExtra = JSON.stringify({ + downloadSettings: { + address: 'download.example.com', + network: 'xhttp', + port: 8443, + security: 'reality', + xhttpSettings: { + path: '/download', + }, + }, + }); + const parsed = ProxyUtils.parse( + `vless://${UUID}@vless-xhttp.example.com:443?security=tls&type=xhttp&path=%2Fxhttp&host=cdn.example.com&sni=sni.example.com&mode=stream-up&extra=${encodeURIComponent( + rawExtra, + )}#URI%20XHTTP%20Invalid%20Reality%20Download`, + ); + + expect(parsed).to.have.length(1); + expect( + parsed[0]['xhttp-opts']?.['download-settings']?.['reality-opts'], + ).to.deep.equal({}); + + const output = ProxyUtils.produce(parsed, 'URI', 'external'); + expect(output).to.equal(''); + }); + + it('skips URI VLESS exports when outer reality is valid but nested download reality is missing public keys', function () { + const rawExtra = JSON.stringify({ + downloadSettings: { + address: 'download.example.com', + network: 'xhttp', + port: 8443, + security: 'reality', + xhttpSettings: { + path: '/download', + }, + }, + }); + const parsed = ProxyUtils.parse( + `vless://${UUID}@vless-xhttp.example.com:443?security=reality&pbk=outer-pub&sid=01&type=xhttp&path=%2Fxhttp&host=cdn.example.com&sni=sni.example.com&mode=stream-up&extra=${encodeURIComponent( + rawExtra, + )}#URI%20XHTTP%20Mixed%20Reality`, + ); + + expect(parsed).to.have.length(1); + expect(parsed[0]['reality-opts']).to.deep.equal({ + 'public-key': 'outer-pub', + 'short-id': '01', + }); + expect( + parsed[0]['xhttp-opts']?.['download-settings']?.['reality-opts'], + ).to.deep.equal({}); + + const output = ProxyUtils.produce(parsed, 'URI', 'external'); + expect(output).to.equal(''); + }); + + it('skips URI VLESS exports when xhttp stream-one is combined with download-settings', function () { + const rawExtra = JSON.stringify({ + downloadSettings: { + address: 'download.example.com', + network: 'xhttp', + port: 8443, + security: 'tls', + xhttpSettings: { + path: '/download', + }, + }, + }); + const parsed = ProxyUtils.parse( + `vless://${UUID}@vless-xhttp.example.com:443?security=tls&type=xhttp&path=%2Fxhttp&host=cdn.example.com&sni=sni.example.com&mode=stream-one&extra=${encodeURIComponent( + rawExtra, + )}#URI%20XHTTP%20Stream%20One%20Download`, + ); + + expect(parsed).to.have.length(1); + expect(parsed[0]['xhttp-opts']?.mode).to.equal('stream-one'); + expect(parsed[0]['xhttp-opts']?.['download-settings']).to.deep.include({ + server: 'download.example.com', + port: 8443, + tls: true, + }); + + const output = ProxyUtils.produce(parsed, 'URI', 'external'); + expect(output).to.equal(''); + }); + + it('uses nested download Host header when producing URI VLESS links', function () { + const output = produceExternal('URI', { + type: 'vless', + name: 'URI XHTTP Download Host Header', + server: 'vless-xhttp.example.com', + port: 443, + uuid: UUID, + tls: true, + sni: 'sni.example.com', + network: 'xhttp', + 'xhttp-opts': { + path: '/xhttp', + mode: 'stream-up', + headers: { + Host: 'cdn.example.com', + }, + 'download-settings': { + server: 'download.example.com', + port: 8443, + tls: true, + path: '/download', + headers: { + Host: 'download-host.example.com', + 'X-Download': '1', + }, + }, + }, + }); + + const [, encodedExtra] = output.match(/[?&]extra=([^#]+)/); + const extra = JSON.parse(decodeURIComponent(encodedExtra)); + expect(extra.downloadSettings?.xhttpSettings?.host).to.equal( + 'download-host.example.com', + ); + expect(extra.downloadSettings?.xhttpSettings?.headers).to.deep.equal({ + 'X-Download': '1', + }); + + const reparsed = ProxyUtils.parse(output); + expect(reparsed, output).to.have.length(1); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.host, + ).to.equal('download-host.example.com'); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.headers, + ).to.deep.equal({ + 'X-Download': '1', + }); + }); + + it('prefers explicit nested download host over nested download Host header when producing URI VLESS links', function () { + const output = produceExternal('URI', { + type: 'vless', + name: 'URI XHTTP Download Host Precedence', + server: 'vless-xhttp.example.com', + port: 443, + uuid: UUID, + tls: true, + sni: 'sni.example.com', + network: 'xhttp', + 'xhttp-opts': { + path: '/xhttp', + mode: 'stream-up', + headers: { + Host: 'cdn.example.com', + }, + 'download-settings': { + server: 'download.example.com', + port: 8443, + tls: true, + path: '/download', + host: 'download-host.example.com', + headers: { + Host: 'ignored-header.example.com', + 'X-Download': '1', + }, + }, + }, + }); + + const [, encodedExtra] = output.match(/[?&]extra=([^#]+)/); + const extra = JSON.parse(decodeURIComponent(encodedExtra)); + expect(extra.downloadSettings?.xhttpSettings?.host).to.equal( + 'download-host.example.com', + ); + expect(extra.downloadSettings?.xhttpSettings?.headers).to.deep.equal({ + 'X-Download': '1', + }); + + const reparsed = ProxyUtils.parse(output); + expect(reparsed, output).to.have.length(1); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.host, + ).to.equal('download-host.example.com'); + expect( + reparsed[0]['xhttp-opts']?.['download-settings']?.headers, + ).to.deep.equal({ + 'X-Download': '1', + }); + }); + it('normalizes structured xhttp range-form scalars when producing URI VLESS links', function () { const extra = JSON.stringify({ noGRPCHeader: true, xPaddingBytes: '64-128', scMaxEachPostBytes: 1000000, - scMinPostsIntervalMs: 300, + scMinPostsIntervalMs: '0-300', xmux: { maxConnections: '8', }, downloadSettings: { address: 'download.example.com', + network: 'xhttp', port: 8443, security: 'tls', xhttpSettings: { path: '/download', host: 'download-host.example.com', scMaxEachPostBytes: 1000000, - scMinPostsIntervalMs: 300, + scMinPostsIntervalMs: '0-300', extra: { xmux: { maxConcurrency: '16-32', @@ -1493,12 +2399,12 @@ describe('Proxy text producers', function () { const reparsed = ProxyUtils.parse(output); expect(reparsed, output).to.have.length(1); - expect( - reparsed[0]['xhttp-opts']?.['sc-max-each-post-bytes'], - ).to.equal(1000000); - expect(reparsed[0]['xhttp-opts']?.['sc-min-posts-interval-ms']).to.equal( - 300, + expect(reparsed[0]['xhttp-opts']?.['sc-max-each-post-bytes']).to.equal( + 1000000, ); + expect( + reparsed[0]['xhttp-opts']?.['sc-min-posts-interval-ms'], + ).to.equal('0-300'); expect( reparsed[0]['xhttp-opts']?.['download-settings']?.[ 'sc-max-each-post-bytes' @@ -1508,7 +2414,57 @@ describe('Proxy text producers', function () { reparsed[0]['xhttp-opts']?.['download-settings']?.[ 'sc-min-posts-interval-ms' ], - ).to.equal(300); + ).to.equal('0-300'); + }); + + it('does not truncate malformed nested download port strings when producing URI VLESS links', function () { + const output = produceExternal('URI', { + type: 'vless', + name: 'URI XHTTP Invalid Download Port', + server: 'vless-xhttp.example.com', + port: 443, + uuid: UUID, + tls: true, + sni: 'sni.example.com', + network: 'xhttp', + 'xhttp-opts': { + path: '/xhttp', + mode: 'stream-up', + headers: { + Host: 'cdn.example.com', + }, + 'download-settings': { + server: 'download.example.com', + port: '8443foo', + tls: true, + path: '/download', + }, + }, + }); + + const [, encodedExtra] = output.match(/[?&]extra=([^#]+)/); + const extra = JSON.parse(decodeURIComponent(encodedExtra)); + expect(extra.downloadSettings).to.not.have.property('port'); + expect(extra.downloadSettings).to.deep.equal({ + address: 'download.example.com', + network: 'xhttp', + security: 'tls', + xhttpSettings: { + path: '/download', + }, + }); + + const reparsed = ProxyUtils.parse(output); + expect(reparsed, output).to.have.length(1); + expect( + reparsed[0]['xhttp-opts']?.['download-settings'], + ).to.not.have.property('port'); + expect(reparsed[0]['xhttp-opts']?.['download-settings']).to.deep.equal({ + server: 'download.example.com', + network: 'xhttp', + tls: true, + path: '/download', + }); }); it('drops invalid structured xhttp scalars when producing URI VLESS links', function () { @@ -1520,6 +2476,7 @@ describe('Proxy text producers', function () { }, downloadSettings: { address: 'download.example.com', + network: 'xhttp', port: 8443, security: 'tls', xhttpSettings: { @@ -1554,6 +2511,7 @@ describe('Proxy text producers', function () { 'x-padding-bytes': '64-128', 'sc-max-each-post-bytes': '9007199254740993', 'sc-min-posts-interval-ms': 0, + 'uplink-chunk-size': '64-fast', 'reuse-settings': { 'max-connections': '8', }, @@ -1567,6 +2525,7 @@ describe('Proxy text producers', function () { 'x-padding-bytes': '32-64', 'sc-max-each-post-bytes': '1-9007199254740993', 'sc-min-posts-interval-ms': 'fast', + 'uplink-chunk-size': 'fast', 'reuse-settings': { 'max-concurrency': '16-32', }, @@ -1588,12 +2547,18 @@ describe('Proxy text producers', function () { expect(reparsed[0]['xhttp-opts']).to.not.have.property( 'sc-min-posts-interval-ms', ); + expect(reparsed[0]['xhttp-opts']).to.not.have.property( + 'uplink-chunk-size', + ); expect( reparsed[0]['xhttp-opts']?.['download-settings'], ).to.not.have.property('sc-max-each-post-bytes'); expect( reparsed[0]['xhttp-opts']?.['download-settings'], ).to.not.have.property('sc-min-posts-interval-ms'); + expect( + reparsed[0]['xhttp-opts']?.['download-settings'], + ).to.not.have.property('uplink-chunk-size'); }); it('omits top-level URI xhttp extra when only invalid structured scalars remain', function () { @@ -1614,6 +2579,7 @@ describe('Proxy text producers', function () { }, 'sc-max-each-post-bytes': '9007199254740993', 'sc-min-posts-interval-ms': 0, + 'uplink-chunk-size': 'fast', }, }); @@ -1627,6 +2593,7 @@ describe('Proxy text producers', function () { const extra = JSON.stringify({ downloadSettings: { address: 'download.example.com', + network: 'xhttp', port: 8443, security: 'tls', }, @@ -1652,6 +2619,7 @@ describe('Proxy text producers', function () { tls: true, 'sc-max-each-post-bytes': '1-9007199254740993', 'sc-min-posts-interval-ms': 'fast', + 'uplink-chunk-size': 'fast', }, }, }); @@ -1664,18 +2632,18 @@ describe('Proxy text producers', function () { const reparsed = ProxyUtils.parse(output); expect(reparsed, output).to.have.length(1); - expect(reparsed[0]['xhttp-opts']?.['download-settings']).to.not.have.property( - 'sc-max-each-post-bytes', - ); - expect(reparsed[0]['xhttp-opts']?.['download-settings']).to.not.have.property( - 'sc-min-posts-interval-ms', - ); - expect(reparsed[0]['xhttp-opts']?.['download-settings']).to.not.have.property( - 'path', - ); - expect(reparsed[0]['xhttp-opts']?.['download-settings']).to.not.have.property( - 'host', - ); + expect( + reparsed[0]['xhttp-opts']?.['download-settings'], + ).to.not.have.property('sc-max-each-post-bytes'); + expect( + reparsed[0]['xhttp-opts']?.['download-settings'], + ).to.not.have.property('sc-min-posts-interval-ms'); + expect( + reparsed[0]['xhttp-opts']?.['download-settings'], + ).to.not.have.property('path'); + expect( + reparsed[0]['xhttp-opts']?.['download-settings'], + ).to.not.have.property('host'); }); it('produces URI Trojan websocket links with pcs from tls fingerprint', function () { diff --git a/scripts/demo.js b/scripts/demo.js index ee426a4c..92bf34e9 100644 --- a/scripts/demo.js +++ b/scripts/demo.js @@ -36,7 +36,7 @@ function operator(proxies = [], targetPlatform, context) { // 22. `sing-box` 支持使用完整的 `_curve_preferences` 结构设置 `tls` 的 `curve_preferences` // 23. `interface-name` 指定流量出站接口 只给 Surge 用的话, `interface` 也可以 // 24. Surge for macOS 可手动指定链接参数 target=SurgeMac 或在 同步配置 中指定 SurgeMac 来启用 mihomo 支援 Surge 本身不支持的协议. 设置节点字段 `_mihomoExternal` 为 `true` 可强制指定使用 mihomo External Proxy Program 输出该节点 - // 25. VLESS URI extra 字段复杂且其他客户端不一定跟进, 所以输出 URI 时, 若存在原始的 `_extra` 字段, 则直接使用该字段的值输出到 URI 的 extra 部分, 而不进行解析和重组 + // 25. VLESS xhttp URI 的 extra 默认会拆成两部分处理: mihomo 已支持的字段会解析到节点的结构化字段并在输出 URI 时重新组装; extra 里 mihomo 还不支持的字段只会保存在 `_extra_unsupported` 对象里. 输出 URI 时会用“当前结构化字段 + _extra_unsupported”一起构造 extra, 这样既不会让旧 raw extra 覆盖后来修改过的 mihomo 字段, 也能避免 VLESS URI -> VLESS URI 的流程里把暂不支持的 extra 字段丢掉. 但如果节点上显式设置了 `_extra`, 且它是字符串或普通对象, 那么输出 URI 时 extra 会直接使用 `_extra` (对象会自动转成 JSON 字符串), 不再重组结构化字段. 这是为了方便手动自定义 extra, 不用再一个个同步那些本来会影响 extra 的其它字段 // 26. `_qx_obfs_http` 为 QX 的 http obfs 原始值, 例如 `http`, `vmess-http`, `vemss-http`, `shadowsocks-http`, 用于 QX 输入输出时保留原始写法. `vemss-http` 应该是 huaqian 的 typo, 没测过, 反正也支持, 报错就自己改成 `vmess-http` 吧 // 27. WireGuard 支持 `ip-cidr`(IPv4 前缀长度) 和 `ipv6-cidr`(IPv6 前缀长度) 字段: 内部会保存前缀长度, 若未设置则默认分别为 `32` 和 `128`. 输出到 `mihomo`/`Shadowrocket`/`sing-box`/`URI` 时会带上该后缀