diff --git a/backend/package.json b/backend/package.json index 621f21f1..08214f08 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.44.11", + "version": "2.44.12", "description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.", "main": "src/main.js", "packageManager": "pnpm@11.0.9", diff --git a/backend/src/core/proxy-utils/parsers/index.js b/backend/src/core/proxy-utils/parsers/index.js index 4887e197..af844efe 100644 --- a/backend/src/core/proxy-utils/parsers/index.js +++ b/backend/src/core/proxy-utils/parsers/index.js @@ -1884,7 +1884,11 @@ function URI_VLESS() { } proxy['client-fingerprint'] = params.fp; proxy.alpn = params.alpn ? params.alpn.split(',') : undefined; - proxy['skip-cert-verify'] = /(TRUE)|1/i.test(params.allowInsecure); + proxy['skip-cert-verify'] = + /(TRUE)|1/i.test(params.allowInsecure) || + (protocol === 'vless' && + params.allowInsecure == null && + params.insecure === '1'); proxy._echConfigList = getIfPresent(params.ech); const echOpts = buildMihomoEchOptsFromXrayFields({ echConfigList: params.ech, @@ -1950,6 +1954,8 @@ function URI_VLESS() { } if (['websocket'].includes(proxy.network)) { proxy.network = 'ws'; + } else if (protocol === 'vless' && proxy.network === 'splithttp') { + proxy.network = 'xhttp'; } if (proxy.network && !['tcp', 'none'].includes(proxy.network)) { @@ -1987,7 +1993,7 @@ function URI_VLESS() { if (params.serviceName) { opts[`${proxy.network}-service-name`] = params.serviceName; } else if (isShadowrocket && params.path) { - if (!['ws', 'http', 'h2'].includes(proxy.network)) { + if (!['ws', 'http', 'h2', 'xhttp'].includes(proxy.network)) { opts[`${proxy.network}-service-name`] = params.path; delete params.path; } diff --git a/backend/src/core/proxy-utils/parsers/peggy/surge.js b/backend/src/core/proxy-utils/parsers/peggy/surge.js index 9b7e93a4..9409b301 100644 --- a/backend/src/core/proxy-utils/parsers/peggy/surge.js +++ b/backend/src/core/proxy-utils/parsers/peggy/surge.js @@ -1,4 +1,6 @@ import peggy from 'peggy'; +import { setSurgeXhttpOption } from '../../surge-xhttp'; + const grammars = String.raw` // global initializer {{ @@ -398,7 +400,7 @@ vmess = tag equals "vmess" address (vmess_uuid/vmess_aead/ws/ws_path/ws_headers/ handleWebsocket(); handleShadowTLS(); } -vless = tag equals "vless" address (vless_username/vless_option/reality_option/ws/ws_path/ws_headers/grpc/grpc_service_name/grpc_mode/grpc_authority/xhttp/xhttp_option/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls/sni/cert_verify_name/alpn/tls_fingerprint/tls_verification/client_cert/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* { +vless = tag equals "vless" address (vless_username/vless_option/reality_option/ws/ws_path/ws_headers/grpc/grpc_service_name/grpc_mode/grpc_authority/xhttp/xhttp_headers/xhttp_option/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls/sni/cert_verify_name/alpn/tls_fingerprint/tls_verification/client_cert/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* { proxy.type = "vless"; proxy["packet-encoding"] = "xudp"; if (proxy["reality-opts"] && proxy["reality-opts"]["public-key"]) proxy.tls = true; @@ -587,21 +589,30 @@ vmess_method = comma "encrypt-method" equals cipher:$[^,]+ { cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"bf-cfb"/"camellia-128-cfb"/"camellia-192-cfb"/"camellia-256-cfb"/"cast5-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"des-cfb"/"idea-cfb"/"none"/"rc2-cfb"/"rc4-md5"/"rc4"/"salsa20"/"seed-cfb"/"xchacha20-ietf-poly1305"/"2022-blake3-aes-128-gcm"/"2022-blake3-aes-256-gcm"); ws = comma "ws" equals flag:bool { if (flag) obfs.type = "ws"; } -ws_headers = comma "ws-headers" equals & { +ws_headers = comma "ws-headers" equals value:pipe_headers { obfs["ws-headers"] = value; } +pipe_headers = & { const start = peg$currPos; const index = readHeadersEnd(input, start, "|"); $.headers = input.substring(start, index); peg$currPos = index; return $.headers.trim().length > 0; -} { obfs["ws-headers"] = parseHeaders($.headers, "|"); } +} { return parseHeaders($.headers, "|"); } ws_path = comma "ws-path" equals path:uri { obfs.path = path.trim().replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); } grpc = comma "grpc" equals flag:bool { if (flag) proxy.network = "grpc"; } grpc_service_name = comma "grpc-service-name" equals value:quoted_value { $set(proxy, "grpc-opts.grpc-service-name", value.trim()); } grpc_mode = comma "grpc-mode" equals value:quoted_value { $set(proxy, "grpc-opts._grpc-type", value.trim()); } grpc_authority = comma "grpc-authority" equals value:quoted_value { $set(proxy, "grpc-opts._grpc-authority", value.trim()); } xhttp = comma "xhttp" equals flag:bool { xhttpEnabled = flag; } -xhttp_option = comma "xhttp-" key:("path"/"host"/"mode") equals value:quoted_value { xhttpOpts[key] = value.trim(); } +xhttp_headers = comma "xhttp-headers" equals value:pipe_headers { + for (const key of Object.keys(value)) { + if (/^host$/i.test(key)) delete value[key]; + } + xhttpOpts.headers = value; +} +xhttp_option = comma "xhttp-" key:$[a-z0-9-]+ equals value:quoted_value { + options.setSurgeXhttpOption(xhttpOpts, key, value.trim()); +} headers = comma "headers" equals & { const start = peg$currPos; const index = readHeadersEnd(input, start, ";"); @@ -664,7 +675,10 @@ others = comma [^=,]+ equals [^=,]+ let parser; export default function getParser() { if (!parser) { - parser = peggy.generate(grammars); + const generated = peggy.generate(grammars); + parser = { + parse: (input) => generated.parse(input, { setSurgeXhttpOption }), + }; } return parser; } diff --git a/backend/src/core/proxy-utils/producers/surge.js b/backend/src/core/proxy-utils/producers/surge.js index 539e6ea3..4cb6a9cc 100644 --- a/backend/src/core/proxy-utils/producers/surge.js +++ b/backend/src/core/proxy-utils/producers/surge.js @@ -1,6 +1,8 @@ +import _ from 'lodash'; import { Result, isPresent } from './utils'; -import { isNotBlank, getIfNotBlank } from '@/utils'; +import { isNotBlank, getIfNotBlank, isPlainObject } from '@/utils'; import $ from '@/core/app'; +import { SURGE_XHTTP_FIELDS } from '../surge-xhttp'; import { formatSurgeVmessEncryptMethod } from '../vmess-security'; const targetPlatform = 'Surge'; @@ -699,16 +701,21 @@ function appendVlessParams(result, proxy) { const network = proxy.network ?? 'tcp'; const reality = proxy['reality-opts']; const tls = proxy.tls || reality; + const encrypted = + isNotBlank(proxy.encryption) && proxy.encryption.trim() !== 'none'; if (!['tcp', 'raw', 'none', 'ws', 'grpc', 'xhttp'].includes(network)) { throw unsupported(`VLESS network ${network} is unsupported`); } if (proxy.encryption && /[,\r\n"']/.test(proxy.encryption)) { throw unsupported('VLESS encryption contains unsupported characters'); } + const supportsVision = + network !== 'grpc' && + (encrypted || (tls && network !== 'ws' && network !== 'xhttp')); if ( (network === 'ws' && reality) || (network === 'grpc' && !tls) || - (proxy.flow && (!tls || network === 'ws' || network === 'grpc')) + (proxy.flow && !supportsVision) ) { throw unsupported( 'Unsupported VLESS transport, TLS or flow combination', @@ -728,26 +735,7 @@ function appendVlessParams(result, proxy) { if (value) result.append(`,${key}=${value}`); } } else if (network === 'xhttp') { - result.append(',xhttp=true'); - // shortcut: export path, host and mode, extend when more XHTTP fields have a Surge mapping. - const xhttp = proxy['xhttp-opts']; - for (const [key, field] of [ - ['path', xhttp?.path], - ['host', xhttp?.host ?? xhttp?.headers?.Host ?? xhttp?.headers?.host], - ['mode', xhttp?.mode], - ]) { - const value = stripSurgeQuotes(String(field ?? '')); - if (!value) continue; - if (/[\r\n"]/.test(value)) { - throw unsupported( - `VLESS xhttp-${key} contains unsupported characters`, - ); - } - const parameter = value.includes(',') - ? quoteSurgeValue(value) - : value; - result.append(`,xhttp-${key}=${parameter}`); - } + appendXhttpParams(result, proxy); } if (proxy.flow) result.append(`,flow=${proxy.flow}`); @@ -765,6 +753,48 @@ function appendVlessParams(result, proxy) { } } +function appendXhttpParams(result, proxy) { + const xhttp = proxy['xhttp-opts']; + // A single Surge policy cannot represent a separate XHTTP download transport. + if (xhttp?.['download-settings']) { + throw unsupported('VLESS XHTTP download-settings are unsupported'); + } + + result.append(',xhttp=true'); + const headers = isPlainObject(xhttp?.headers) + ? Object.entries(xhttp.headers) + : []; + const host = + xhttp?.host ?? headers.find(([key]) => /^host$/i.test(key))?.[1]; + for (const [key, field] of Object.entries(SURGE_XHTTP_FIELDS)) { + const rawValue = key === 'host' ? host : _.get(xhttp, field); + if (rawValue == null) continue; + const rawText = String(rawValue); + const value = stripSurgeQuotes(rawText); + if (!value && key !== 'session-table') continue; + if (/[\r\n]/.test(rawText) || value.includes('"')) { + throw unsupported( + `VLESS xhttp-${key} contains unsupported characters`, + ); + } + const parameter = + !value || /[,'\s]/.test(value) ? quoteSurgeValue(value) : value; + result.append(`,xhttp-${key}=${parameter}`); + } + + const extraHeaders = headers.filter(([key]) => !/^host$/i.test(key)); + if ( + extraHeaders.some( + ([key, value]) => + /[,="':|\r\n]/.test(key) || /[\r\n]/.test(String(value)), + ) + ) { + throw unsupported('VLESS xhttp-headers contain unsupported characters'); + } + const value = formatHeaderMap(Object.fromEntries(extraHeaders), '|'); + if (value) result.append(`,xhttp-headers=${quoteSurgeValue(value)}`); +} + function ssh(proxy) { const result = new Result(proxy); result.append(`${proxy.name}=ssh,${proxy.server},${proxy.port}`); diff --git a/backend/src/core/proxy-utils/surge-xhttp.js b/backend/src/core/proxy-utils/surge-xhttp.js new file mode 100644 index 00000000..2875694e --- /dev/null +++ b/backend/src/core/proxy-utils/surge-xhttp.js @@ -0,0 +1,65 @@ +import _ from 'lodash'; +import { + normalizeXhttpIntegerValue, + normalizeXhttpNonNegativeRange, + normalizeXhttpPositiveRange, + normalizeXhttpStrictPositiveRangeValue, +} from './xhttp-utils'; + +// Surge parameter suffixes and their corresponding paths in xhttp-opts. +export const SURGE_XHTTP_FIELDS = { + path: 'path', + host: 'host', + mode: 'mode', + 'padding-bytes': 'x-padding-bytes', + 'padding-obfs': 'x-padding-obfs-mode', + 'padding-key': 'x-padding-key', + 'padding-header': 'x-padding-header', + 'padding-placement': 'x-padding-placement', + 'padding-method': 'x-padding-method', + 'uplink-method': 'uplink-http-method', + 'session-placement': 'session-placement', + 'session-key': 'session-key', + 'session-table': 'session-table', + 'session-length': 'session-length', + 'seq-placement': 'seq-placement', + 'seq-key': 'seq-key', + 'uplink-data-placement': 'uplink-data-placement', + 'uplink-data-key': 'uplink-data-key', + 'uplink-chunk-size': 'uplink-chunk-size', + 'no-grpc-header': 'no-grpc-header', + 'max-each-post-bytes': 'sc-max-each-post-bytes', + 'min-posts-interval': 'sc-min-posts-interval-ms', + 'xmux-max-concurrency': 'reuse-settings.max-concurrency', + 'xmux-max-connections': 'reuse-settings.max-connections', + 'xmux-max-reuse-times': 'reuse-settings.c-max-reuse-times', + 'xmux-max-request-times': 'reuse-settings.h-max-request-times', + 'xmux-max-reusable-secs': 'reuse-settings.h-max-reusable-secs', + 'xmux-keep-alive': 'reuse-settings.h-keep-alive-period', +}; + +export function setSurgeXhttpOption(opts, key, rawValue) { + if (!Object.prototype.hasOwnProperty.call(SURGE_XHTTP_FIELDS, key)) return; + const field = SURGE_XHTTP_FIELDS[key]; + let value = rawValue; + switch (key) { + case 'padding-obfs': + case 'no-grpc-header': + if (rawValue !== 'true' && rawValue !== 'false') return; + value = rawValue === 'true'; + break; + case 'uplink-chunk-size': + value = normalizeXhttpNonNegativeRange(rawValue) ?? rawValue; + break; + case 'max-each-post-bytes': + value = normalizeXhttpStrictPositiveRangeValue(rawValue) ?? rawValue; + break; + case 'min-posts-interval': + value = normalizeXhttpPositiveRange(rawValue) ?? rawValue; + break; + case 'xmux-keep-alive': + value = normalizeXhttpIntegerValue(rawValue) ?? rawValue; + break; + } + _.set(opts, field, value); +} diff --git a/backend/src/test/proxy-producers/text.spec.js b/backend/src/test/proxy-producers/text.spec.js index e7ec389a..aaaa3aa1 100644 --- a/backend/src/test/proxy-producers/text.spec.js +++ b/backend/src/test/proxy-producers/text.spec.js @@ -2521,6 +2521,143 @@ describe('Proxy text producers', function () { }); }); + it('round-trips the documented Surge VLESS XHTTP options and share-link extra', function () { + const params = [ + 'xhttp=true', + 'xhttp-path=/edge', + 'xhttp-host=cdn.example.com', + 'xhttp-mode=packet-up', + 'xhttp-padding-bytes=64-128', + 'xhttp-padding-obfs=true', + 'xhttp-padding-key=padding', + 'xhttp-padding-header=X-Padding', + 'xhttp-padding-placement=queryInHeader', + 'xhttp-padding-method=tokenish', + 'xhttp-uplink-method=PUT', + 'xhttp-session-placement=header', + 'xhttp-session-key=X-Session', + 'xhttp-session-table=Base62', + 'xhttp-session-length=16', + 'xhttp-seq-placement=header', + 'xhttp-seq-key=X-Seq', + 'xhttp-uplink-data-placement=header', + 'xhttp-uplink-data-key=X-Chunk', + 'xhttp-uplink-chunk-size=1024', + 'xhttp-no-grpc-header=true', + 'xhttp-max-each-post-bytes=10000-20000', + 'xhttp-min-posts-interval=25', + 'xhttp-xmux-max-concurrency=8-16', + 'xhttp-xmux-max-connections=0', + 'xhttp-xmux-max-reuse-times=10', + 'xhttp-xmux-max-request-times=600-900', + 'xhttp-xmux-max-reusable-secs=1800-3000', + 'xhttp-xmux-keep-alive=-1', + ]; + const [proxy] = ProxyUtils.parse( + `XHTTP = vless, example.com, 443, username=${UUID}, ${params.join(', ')}, xhttp-headers="User-Agent:firefox|X-Test:'a,b|c:d'|hOsT:ignored.example.com", tls=true, alpn=h3`, + ); + const expected = { + network: 'xhttp', + tls: true, + alpn: ['h3'], + 'xhttp-opts': { + path: '/edge', + host: 'cdn.example.com', + mode: 'packet-up', + headers: { 'User-Agent': 'firefox', 'X-Test': 'a,b|c:d' }, + 'x-padding-bytes': '64-128', + 'x-padding-obfs-mode': true, + 'x-padding-key': 'padding', + 'x-padding-header': 'X-Padding', + 'x-padding-placement': 'queryInHeader', + 'x-padding-method': 'tokenish', + 'uplink-http-method': 'PUT', + 'session-placement': 'header', + 'session-key': 'X-Session', + 'session-table': 'Base62', + 'session-length': '16', + 'seq-placement': 'header', + 'seq-key': 'X-Seq', + 'uplink-data-placement': 'header', + 'uplink-data-key': 'X-Chunk', + 'uplink-chunk-size': 1024, + 'no-grpc-header': true, + 'sc-max-each-post-bytes': '10000-20000', + 'sc-min-posts-interval-ms': 25, + 'reuse-settings': { + 'max-concurrency': '8-16', + 'max-connections': '0', + 'c-max-reuse-times': '10', + 'h-max-request-times': '600-900', + 'h-max-reusable-secs': '1800-3000', + 'h-keep-alive-period': -1, + }, + }, + }; + expectSubset(proxy, expected); + expect(proxy['xhttp-opts'].headers).to.deep.equal( + expected['xhttp-opts'].headers, + ); + + const uri = produceExternal('URI', proxy).replace( + 'type=xhttp', + 'type=splithttp', + ); + const [fromUri] = ProxyUtils.parse( + uri.replace('#XHTTP', '&insecure=1#XHTTP'), + ); + expectSubset(fromUri, { ...expected, 'skip-cert-verify': true }); + for (const target of ['Surge', 'SurgeMac']) { + const output = produceExternal(target, fromUri); + for (const param of [...params, 'skip-cert-verify=true']) { + expect(output.split(',')).to.include(param); + } + expect(output).not.to.include('ignored.example.com'); + expectSubset(ProxyUtils.parse(output)[0], expected); + } + }); + + it('falls back to Mihomo for SurgeMac VLESS XHTTP with download settings', function () { + const proxy = { + type: 'vless', + name: 'Split Download', + server: '192.0.2.1', + port: 443, + uuid: UUID, + tls: true, + network: 'xhttp', + 'xhttp-opts': { + mode: 'stream-up', + 'download-settings': { server: 'download.example.com' }, + }, + }; + expect(ProxyUtils.produce([proxy], 'Surge', 'external')).to.equal(''); + const output = produceExternal('SurgeMac', proxy, { + useMihomoExternal: true, + }); + const [, config] = output.match(/args="([A-Za-z0-9+/=]+)"/); + const [wrapped] = JSON.parse(Base64.decode(config)).proxies; + expect(wrapped['xhttp-opts']['download-settings']).to.deep.equal({ + server: 'download.example.com', + }); + }); + + it('preserves explicit false, zero and empty Surge VLESS XHTTP options', function () { + const params = 'xhttp-padding-obfs=false,xhttp-session-table="",xhttp-no-grpc-header=false,xhttp-max-each-post-bytes=10000,xhttp-xmux-keep-alive=0'; + const [proxy] = ProxyUtils.parse( + `XHTTP=vless,example.com,443,username=${UUID},xhttp=true,${params}`, + ); + expect(proxy['xhttp-opts']).to.deep.equal({ + mode: 'auto', + 'x-padding-obfs-mode': false, + 'session-table': '', + 'no-grpc-header': false, + 'sc-max-each-post-bytes': 10000, + 'reuse-settings': { 'h-keep-alive-period': 0 }, + }); + expect(produceExternal('Surge', proxy)).to.include(params); + }); + it('round-trips Surge VLESS encryption with XHTTP', function () { const encryption = `mlkem768x25519plus.native.0rtt.100-111-1111.75-0-111.50-0-3333.${'Ab9_'.repeat(394)}a-A`; const [proxy] = ProxyUtils.parse( @@ -2539,6 +2676,31 @@ describe('Proxy text producers', function () { } }); + it('enables Surge VLESS Vision with encryption on RAW, WebSocket and XHTTP', function () { + const encryption = `mlkem768x25519plus.native.1rtt.${'A'.repeat(43)}`; + const flow = 'xtls-rprx-vision'; + for (const [transport, network] of [ + ['', 'tcp'], + [',ws=true', 'ws'], + [',xhttp=true', 'xhttp'], + ]) { + const [proxy] = ProxyUtils.parse( + `Vision=vless,example.com,443,username=${UUID},flow=${flow},encryption=${encryption}${transport}`, + ); + const output = produceExternal('Surge', proxy); + expectSubset(ProxyUtils.parse(output)[0], { + network, + flow, + encryption, + }); + expect(output).not.to.include('tls=true'); + } + const [grpc] = ProxyUtils.parse( + `Vision=vless,example.com,443,username=${UUID},flow=${flow},encryption=${encryption},grpc=true,tls=true`, + ); + expect(ProxyUtils.produce([grpc], 'Surge', 'external')).to.equal(''); + }); + it('preserves gRPC authority from a VLESS share link without a service name', function () { const [proxy] = ProxyUtils.parse( `vless://${UUID}@edge.example.com:443?type=grpc&security=tls&authority=grpc.example.com#VLESS`,