diff --git a/README.md b/README.md index 65c22ec6..ed36d30b 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ Push URLs may contain secrets: treat `SUB_STORE_PUSH_SERVICE` as privileged conf - [x] Clash Proxy JSON/JSON5/YAML(single line) > [NaiveProxy](https://telegram.me/zhetengsha/4308) - [x] QX (SS, SSR, VMess, Trojan, HTTP, SOCKS5, VLESS, AnyTLS, Hysteria 2) -- [x] Loon (SS, SSR, VMess, Trojan, HTTP, SOCKS5, SOCKS5-TLS, WireGuard, VLESS, Hysteria 2, AnyTLS, TailScale) +- [x] Loon (SS, SSR, VMess, Trojan, HTTP, SOCKS5, SOCKS5-TLS, WireGuard, VLESS, Hysteria 2, AnyTLS, TailScale, Snell) - [x] Surge (Direct, SS, VMess, Trojan, HTTP, HTTPS, HTTP/2 CONNECT, SOCKS5, SOCKS5-TLS, AnyTLS, TrustTunnel, TUIC, Snell, Hysteria 2, VLESS, MASQUE(Surge), SSH(Password authentication only), External Proxy Program(only for macOS), WireGuard(Surge to Surge)) - [x] mihomo(Clash.Meta) Compatible (Direct, SS, SSR, VMess, Trojan, HTTP, SOCKS5, Snell, VLESS, WireGuard, Hysteria, Hysteria 2, TUIC, SSH, mieru, sudoku, AnyTLS, MASQUE, Tailscale, GOST Relay, Shadow QUIC, ZeroTier, OpenVPN) diff --git a/backend/package.json b/backend/package.json index 369a1497..b1f1a753 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.44.17", + "version": "2.44.18", "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/loon-xhttp.js b/backend/src/core/proxy-utils/loon-xhttp.js new file mode 100644 index 00000000..a009a876 --- /dev/null +++ b/backend/src/core/proxy-utils/loon-xhttp.js @@ -0,0 +1,41 @@ +import { normalizeXhttpNonNegativeRange } from './xhttp-utils'; + +export const LOON_XHTTP_FIELDS = { + mode: 'mode', + 'uplink-method': 'uplink-http-method', + 'min-post-interval-ms': 'sc-min-posts-interval-ms', + 'max-post-bytes': 'sc-max-each-post-bytes', + 'uplink-data-placement': 'uplink-data-placement', + 'uplink-data-key': 'uplink-data-key', + 'uplink-chunk-size': 'uplink-chunk-size', + 'padding-bytes': 'x-padding-bytes', + 'padding-obfs-mode': 'x-padding-obfs-mode', + 'padding-placement': 'x-padding-placement', + 'padding-key': 'x-padding-key', + 'padding-header': 'x-padding-header', + 'padding-method': 'x-padding-method', + 'no-grpc-header': 'no-grpc-header', + 'session-id-placement': 'session-placement', + 'session-id-key': 'session-key', + 'session-id-table': 'session-table', + 'session-id-length': 'session-length', + 'seq-placement': 'seq-placement', + 'seq-key': 'seq-key', +}; + +export function setLoonXhttpOption(opts, key, value) { + if (!Object.prototype.hasOwnProperty.call(LOON_XHTTP_FIELDS, key)) return; + switch (key) { + case 'padding-obfs-mode': + case 'no-grpc-header': + if (value !== 'true' && value !== 'false') return; + value = value === 'true'; + break; + case 'min-post-interval-ms': + case 'max-post-bytes': + case 'uplink-chunk-size': + value = normalizeXhttpNonNegativeRange(value) ?? value; + break; + } + opts[LOON_XHTTP_FIELDS[key]] = value; +} diff --git a/backend/src/core/proxy-utils/parsers/index.js b/backend/src/core/proxy-utils/parsers/index.js index fd9681ac..4d66971c 100644 --- a/backend/src/core/proxy-utils/parsers/index.js +++ b/backend/src/core/proxy-utils/parsers/index.js @@ -2750,15 +2750,11 @@ function Loon_SSR() { return { name, test, parse }; } +const LOON_VMESS = /^[^=,]*=\s*vmess\s*,[^,]*,[^,]*,[^,]*,\s*"/i; + function Loon_VMess() { const name = 'Loon VMess Parser'; - const test = (line) => { - // distinguish between surge vmess - return ( - /^.*=\s*vmess/i.test(line.split(',')[0]) && - line.indexOf('username') === -1 - ); - }; + const test = (line) => LOON_VMESS.test(line); const parse = (line) => getLoonParser().parse(line); return { name, test, parse }; } @@ -3008,7 +3004,8 @@ function Surge_VMess() { const test = (line) => { return ( /^.*=\s*vmess/.test(line.split(',')[0]) && - line.indexOf('username') !== -1 + line.indexOf('username') !== -1 && + !LOON_VMESS.test(line) ); }; const parse = (line) => getSurgeParser().parse(line); @@ -3027,7 +3024,10 @@ function Surge_VLESS() { function Surge_Trojan() { const name = 'Surge Trojan Parser'; const test = (line) => { - return /^.*=\s*trojan/.test(line.split(',')[0]); + return ( + /^.*=\s*trojan/.test(line.split(',')[0]) && + !/^[^=,]*=\s*trojan\s*,[^,]*,[^,]*,\s*"/.test(line) + ); }; const parse = (line) => getSurgeParser().parse(line); return { name, test, parse }; @@ -3133,12 +3133,18 @@ function Surge_External() { return { name, test, parse }; } -function Surge_Snell() { - const name = 'Surge Snell Parser'; - const test = (line) => { - return /^.*=\s*snell/.test(line.split(',')[0]); +function Snell() { + const name = 'Snell Parser'; + const test = (line) => /^[^=,]*=\s*(?:snell|opensnell)\s*,/i.test(line); + const parse = (line) => { + const fields = line.match(/(?:[^",]+|"[^"]*")+/g).slice(3); + const loonOption = + /^(?:(?:udp|obfs-name|ip-mode|server-dns)\s*=|block-quic\s*=\s*(?:true|false)$)/; + const isLoon = + fields[0]?.trim().startsWith('"') || + fields.some((field) => loonOption.test(field.trim())); + return (isLoon ? getLoonParser() : getSurgeParser()).parse(line); }; - const parse = (line) => getSurgeParser().parse(line); return { name, test, parse }; } @@ -3207,7 +3213,7 @@ export default [ Surge_VLESS(), Surge_Trojan(), Surge_Http(), - Surge_Snell(), + Snell(), Surge_Tuic(), Surge_WireGuard(), Surge_Hysteria2(), diff --git a/backend/src/core/proxy-utils/parsers/peggy/loon.js b/backend/src/core/proxy-utils/parsers/peggy/loon.js index 69caeb51..a22b5539 100644 --- a/backend/src/core/proxy-utils/parsers/peggy/loon.js +++ b/backend/src/core/proxy-utils/parsers/peggy/loon.js @@ -1,4 +1,6 @@ import peggy from 'peggy'; +import { setLoonXhttpOption } from '../../loon-xhttp'; + const grammars = String.raw` // global initializer {{ @@ -19,6 +21,8 @@ const grammars = String.raw` const proxy = {}; const obfs = {}; const transport = {}; + const xhttpOpts = {}; + const xhttpHeaders = []; const shadowTLS = {}; const $ = {}; @@ -32,6 +36,16 @@ const grammars = String.raw` proxy.network = "http"; $set(proxy, "http-opts.path", transport.path); $set(proxy, "http-opts.headers.Host", transport.host); + } else if (transport.type === "xhttp") { + if (proxy.type === "vmess" && proxy.alterId !== 0) { + throw new Error("VMess XHTTP requires AEAD"); + } + proxy.network = "xhttp"; + proxy.udp ??= false; + if (transport.path != null) xhttpOpts.path = transport.path; + if (transport.host != null) xhttpOpts.host = transport.host; + if (xhttpHeaders.length) xhttpOpts.headers = Object.fromEntries(xhttpHeaders); + proxy["xhttp-opts"] = xhttpOpts; } } @@ -72,7 +86,7 @@ const grammars = String.raw` } } -start = (shadowsocksr/shadowsocks/vmess/vless/trojan/https/http/socks5/hysteria2/anytls/tailscale) { +start = (shadowsocksr/shadowsocks/vmess/vless/trojan/https/http/socks5/hysteria2/anytls/tailscale/snell) { return proxy; } @@ -93,17 +107,17 @@ shadowsocks = tag equals "shadowsocks"i address method password (obfs_typev obfs } handleShadowTLS(); } -vmess = tag equals "vmess"i address vmess_method uuid (transport/transport_host/transport_path/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/tls_profile/alpn/vmess_alterId/fast_open/udp_relay/ip_mode/public_key/short_id/block_quic/others)* { +vmess = tag equals "vmess"i address vmess_method uuid (xhttp_transport/transport/transport_host/transport_path/xhttp_header/xhttp_option/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/tls_profile/alpn/vmess_alterId/fast_open/udp_relay/ip_mode/public_key/short_id/block_quic/others)* { proxy.type = "vmess"; proxy.cipher = proxy.cipher || "auto"; proxy.alterId = proxy.alterId || 0; handleTransport(); } -vless = tag equals "vless"i address uuid (transport/transport_host/transport_path/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/tls_profile/alpn/fast_open/udp_relay/ip_mode/flow/public_key/short_id/block_quic/others)* { +vless = tag equals "vless"i address uuid (xhttp_transport/transport/transport_host/transport_path/xhttp_header/xhttp_option/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/tls_profile/alpn/fast_open/udp_relay/ip_mode/flow/public_key/short_id/block_quic/others)* { proxy.type = "vless"; handleTransport(); } -trojan = tag equals "trojan"i address password (transport/transport_host/transport_path/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/tls_profile/alpn/fast_open/udp_relay/ip_mode/public_key/short_id/block_quic/others)* { +trojan = tag equals "trojan"i address password (xhttp_transport/transport/transport_host/transport_path/xhttp_header/xhttp_option/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/tls_profile/alpn/fast_open/udp_relay/ip_mode/public_key/short_id/block_quic/others)* { proxy.type = "trojan"; handleTransport(); } @@ -129,6 +143,15 @@ tailscale = tag equals "tailscale"i (tailscale_string/tailscale_bool/tailscale_m if (proxy["exit-node"] === "auto") proxy["exit-node"] = "auto:any"; if (proxy["exit-node"] === "none") proxy["exit-node"] = ""; } +snell = tag equals ("snell"i/"opensnell"i) address snell_positional_psk? (snell_psk/snell_version/snell_obfs/obfs_host/obfs_uri/udp_relay/ip_mode/block_quic/others)* { + if (!proxy.psk) throw new Error("Missing Snell PSK"); + proxy.type = "snell"; + proxy.version ??= 4; + proxy.udp ??= false; + if (obfs.type === "http") { + proxy["obfs-opts"] = { mode: obfs.type, host: obfs.host, path: obfs.path }; + } +} tailscale_string = comma key:("auth-key"/"control-url"/"hostname"/"exit-node"/"path-mode"/"ip-mode") equals value:( '"' match:$[^"]* '"' { return match; } @@ -218,13 +241,29 @@ obfs_ss = comma "obfs-name" equals type:("http"/"tls") { obfs.type = type; } obfs_ssr = comma "obfs" equals type:("plain"/"http_simple"/"http_post"/"random_head"/"tls1.2_ticket_auth"/"tls1.2_ticket_fastauth") { obfs.type = type; } obfs_ssr_param = comma "obfs-param" equals match:$[^,]+ { proxy["obfs-param"] = match; } -obfs_host = comma "obfs-host" equals match:[^,]+ { obfs.host = match.join("").replace(/^"(.*)"$/, '$1'); } -obfs_uri = comma "obfs-uri" equals uri:uri { obfs.path = uri; } -uri = $[^,]+ +obfs_host = comma "obfs-host" equals value:option_value { obfs.host = value; } +obfs_uri = comma "obfs-uri" equals value:option_value { obfs.path = value; } + +snell_positional_psk = comma psk:quoted_value { proxy.psk = psk; } +snell_psk = comma "psk" equals psk:option_value { proxy.psk = psk; } +snell_version = comma "version" equals version:$[0-9]+ { proxy.version = Number(version); } +snell_obfs = comma ("obfs-name"/"obfs") equals type:("none"/"http") { obfs.type = type; } transport = comma "transport" equals type:("tcp"/"ws"/"http") { transport.type = type; } -transport_host = comma "host" equals match:[^,]+ { transport.host = match.join("").replace(/^"(.*)"$/, '$1'); } -transport_path = comma "path" equals path:uri { transport.path = path; } +transport_host = comma "host" equals value:option_value { transport.host = value; } +transport_path = comma "path" equals value:option_value { transport.path = value; } + +xhttp_transport = comma "transport" equals "xhttp" { transport.type = "xhttp"; } +xhttp_header = comma "xhttp-header" equals value:option_value { + const colon = value.indexOf(":"); + const name = value.slice(0, colon).trim(); + if (colon > 0 && name && !/^host$/i.test(name)) { + xhttpHeaders.push([name, value.slice(colon + 1).trim()]); + } +} +xhttp_option = comma "xhttp-" key:$[a-z0-9-]+ equals value:option_value { + options.setLoonXhttpOption(xhttpOpts, key, value); +} ssr_protocol = comma "protocol" equals protocol:("origin"/"auth_sha1_v4"/"auth_aes128_md5"/"auth_aes128_sha1"/"auth_chain_a"/"auth_chain_b") { proxy.protocol = protocol; } ssr_protocol_param = comma "protocol-param" equals param:$[^=,]+ { proxy["protocol-param"] = param; } @@ -248,7 +287,7 @@ tls_profile = comma "tls-profile" equals match:[^,]+ { const clientFingerprint = loonClientFingerprint(tlsProfile); if (clientFingerprint) proxy["client-fingerprint"] = clientFingerprint; } -alpn = comma "alpn" equals '"' match:$[^"]* '"' { +alpn = comma "alpn" equals match:option_value { const values = match .split(",") .map((item) => item.trim()) @@ -258,7 +297,7 @@ alpn = comma "alpn" equals '"' match:$[^"]* '"' { flow = comma "flow" equals match:[^,]+ { proxy["flow"] = match.join("").replace(/^"(.*)"$/, '$1'); } public_key = comma "public-key" equals match:[^,]+ { proxy["reality-opts"] = proxy["reality-opts"] || {}; proxy["reality-opts"]["public-key"] = match.join("").replace(/^"(.*)"$/, '$1'); } -short_id = comma "short-id" equals match:[^,]+ { proxy["reality-opts"] = proxy["reality-opts"] || {}; proxy["reality-opts"]["short-id"] = match.join("").replace(/^"(.*)"$/, '$1'); } +short_id = comma "short-id" equals value:option_value { proxy["reality-opts"] = proxy["reality-opts"] || {}; proxy["reality-opts"]["short-id"] = value; } fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; } udp_relay = comma "udp" equals flag:bool { proxy.udp = flag; } @@ -287,6 +326,8 @@ server_dns = comma "server-dns" equals value:( } tag = match:[^=,]* { proxy.name = match.join("").trim(); } +quoted_value = '"' match:$[^"]* '"' { return match; } +option_value = quoted_value / match:$[^,"]* { return match.trim(); } comma = _ "," _ equals = _ "=" _ _ = [ \r\t]* @@ -296,7 +337,10 @@ others = server_dns / (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, { setLoonXhttpOption }), + }; } return parser; } diff --git a/backend/src/core/proxy-utils/parsers/peggy/surge.js b/backend/src/core/proxy-utils/parsers/peggy/surge.js index 3e224947..d472d6dd 100644 --- a/backend/src/core/proxy-utils/parsers/peggy/surge.js +++ b/backend/src/core/proxy-utils/parsers/peggy/surge.js @@ -436,7 +436,7 @@ ssh = tag equals "ssh" address (username password)? (usernamek passwordk)? (serv proxy.type = "ssh"; handleShadowTLS(); } -snell = tag equals "snell" address (snell_version/snell_mode/snell_psk/obfs/obfs_host/obfs_uri/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/udp_relay/reuse/alpn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* { +snell = tag equals ("snell"i/"opensnell"i) address (snell_version/snell_mode/snell_psk/obfs/obfs_host/obfs_uri/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/udp_relay/reuse/alpn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* { proxy.type = "snell"; // handle obfs if (obfs.type == "http" || obfs.type === "tls") { @@ -562,7 +562,7 @@ tls_verification = comma "skip-cert-verify" equals flag:bool { proxy["skip-cert- tls_fingerprint = comma "server-cert-fingerprint-sha256" equals tls_fingerprint:$[^,]+ { proxy["tls-fingerprint"] = tls_fingerprint.trim(); } client_cert = comma "client-cert" equals match:[^,]+ { proxy["keystore-client-cert"] = stripQuotes(match.join("")); } -snell_psk = comma "psk" equals match:[^,]+ { proxy.psk = match.join("").replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); } +snell_psk = comma "psk" equals value:quoted_value { proxy.psk = value; } snell_version = comma "version" equals match:$[0-9]+ { proxy.version = parseInt(match.trim()); } snell_mode = comma "mode" equals match:[^,]+ { const mode = stripQuotes(match.join("")).trim(); diff --git a/backend/src/core/proxy-utils/producers/loon.js b/backend/src/core/proxy-utils/producers/loon.js index b2b67509..1ccb2e94 100644 --- a/backend/src/core/proxy-utils/producers/loon.js +++ b/backend/src/core/proxy-utils/producers/loon.js @@ -1,8 +1,9 @@ /* eslint-disable no-case-declarations */ const targetPlatform = 'Loon'; import { isPresent, Result } from './utils'; -import { isIPv4, isIPv6 } from '@/utils'; +import { isIPv4, isIPv6, isPlainObject } from '@/utils'; import $ from '@/core/app'; +import { LOON_XHTTP_FIELDS } from '../loon-xhttp'; import { formatLoonVmessSecurity } from '../vmess-security'; const ipVersions = { @@ -28,6 +29,8 @@ export default function Loon_Producer() { return shadowsocks(proxy); case 'ssr': return shadowsocksr(proxy); + case 'snell': + return snell(proxy); case 'trojan': return trojan(proxy); case 'vmess': @@ -79,6 +82,46 @@ function appendAlpn(result, proxy) { if (alpn) result.append(`,alpn="${alpn}"`); } +function formatLoonValue(value, quoted = false) { + const text = String(value); + if (/["\r\n]/.test(text)) { + throw new Error('Unsupported characters in Loon option'); + } + return quoted || !text || /[,\s]/.test(text) ? `"${text}"` : text; +} + +function appendXhttp(result, proxy) { + const xhttp = proxy['xhttp-opts']; + if (xhttp?.['download-settings']) { + throw new Error('Loon XHTTP does not support download-settings'); + } + + const headers = isPlainObject(xhttp?.headers) + ? Object.entries(xhttp.headers) + : []; + const host = + xhttp?.host ?? headers.find(([key]) => /^host$/i.test(key))?.[1]; + result.append(',transport=xhttp'); + for (const [key, value] of [ + ['path', xhttp?.path], + ['host', host], + ]) { + if (value != null) result.append(`,${key}=${formatLoonValue(value)}`); + } + for (const [key, field] of Object.entries(LOON_XHTTP_FIELDS)) { + const value = xhttp?.[field]; + if (value != null) + result.append(`,xhttp-${key}=${formatLoonValue(value)}`); + } + for (const [key, value] of headers) { + if (!/^host$/i.test(key) && value != null) { + result.append( + `,xhttp-header=${formatLoonValue(`${key}: ${value}`, true)}`, + ); + } + } +} + function getLoonShadowTLSAlpn(proxy) { const values = proxy?.['plugin-opts']?.alpn ?? proxy?.alpn; const normalized = Array.isArray(values) @@ -296,8 +339,48 @@ function shadowsocksr(proxy) { return result.toString(); } +function snell(proxy) { + const version = Number(proxy.version); + if (![4, 5].includes(version)) { + throw new Error( + `Loon does not support Snell version ${proxy.version ?? 1}`, + ); + } + if (proxy.psk == null || proxy.psk === '') { + throw new Error('Missing Snell PSK'); + } + const obfs = proxy['obfs-opts']; + if (proxy.plugin || (obfs?.mode && !['none', 'http'].includes(obfs.mode))) { + throw new Error('Loon Snell only supports HTTP obfs'); + } + + const result = new Result(proxy); + result.append( + `${proxy.name}=snell,${proxy.server},${proxy.port},${formatLoonValue( + proxy.psk, + true, + )},version=${version}`, + ); + if (obfs?.mode === 'http') { + result.append(',obfs=http'); + if (obfs.host != null) + result.append(`,obfs-host=${formatLoonValue(obfs.host)}`); + if (obfs.path != null) + result.append(`,obfs-uri=${formatLoonValue(obfs.path)}`); + } + result.appendIfPresent(`,udp=${proxy.udp}`, 'udp'); + const blockQuic = proxy['block-quic']; + if (blockQuic === 'on' || blockQuic === 'off') { + result.append(`,block-quic=${blockQuic === 'on'}`); + } + const ipVersion = ipVersions[proxy['ip-version']] || proxy['ip-version']; + result.appendIfPresent(`,ip-mode=${ipVersion}`, 'ip-version'); + return result.toString(); +} + function trojan(proxy) { const isReality = !!proxy['reality-opts']; + const isXhttp = proxy.network === 'xhttp'; const result = new Result(proxy); result.append( `${proxy.name}=trojan,${proxy.server},${proxy.port},"${proxy.password}"`, @@ -317,6 +400,8 @@ function trojan(proxy) { `,host=${proxy['ws-opts']?.headers?.Host}`, 'ws-opts.headers.Host', ); + } else if (isXhttp) { + appendXhttp(result, proxy); } else { throw new Error(`network ${proxy.network} is unsupported`); } @@ -334,7 +419,10 @@ function trojan(proxy) { appendReality(result, proxy); } else { // sni - result.appendIfPresent(`,tls-name=${proxy.sni}`, 'sni'); + result.appendIfPresent( + `,${isXhttp ? 'sni' : 'tls-name'}=${proxy.sni}`, + 'sni', + ); result.appendIfPresent( `,tls-cert-sha256=${proxy['tls-fingerprint']}`, 'tls-fingerprint', @@ -429,6 +517,7 @@ function anytls(proxy) { function vmess(proxy) { const isReality = !!proxy['reality-opts']; + const isXhttp = proxy.network === 'xhttp'; const security = formatLoonVmessSecurity(proxy.cipher); const result = new Result(proxy); @@ -462,6 +551,8 @@ function vmess(proxy) { `,host=${Array.isArray(httpHost) ? httpHost[0] : httpHost}`, 'http-opts.headers.Host', ); + } else if (isXhttp) { + appendXhttp(result, proxy); } else { throw new Error(`network ${proxy.network} is unsupported`); } @@ -477,16 +568,17 @@ function vmess(proxy) { `,skip-cert-verify=${proxy['skip-cert-verify']}`, 'skip-cert-verify', ); - if (proxy.tls || isReality) { - appendTlsProfile(result, proxy); - appendAlpn(result, proxy); - } + if (proxy.tls || isReality) appendTlsProfile(result, proxy); + if (proxy.tls || isReality || isXhttp) appendAlpn(result, proxy); if (isReality) { appendReality(result, proxy); } else { // sni - result.appendIfPresent(`,tls-name=${proxy.sni}`, 'sni'); + result.appendIfPresent( + `,${isXhttp ? 'sni' : 'tls-name'}=${proxy.sni}`, + 'sni', + ); result.appendIfPresent( `,tls-cert-sha256=${proxy['tls-fingerprint']}`, 'tls-fingerprint', @@ -498,11 +590,13 @@ function vmess(proxy) { } // AEAD - if (isPresent(proxy, 'aead')) { - result.append(`,alterId=${proxy.aead ? 0 : 1}`); - } else { - result.append(`,alterId=${proxy.alterId}`); + let alterId = proxy.alterId; + if (isPresent(proxy, 'aead')) alterId = proxy.aead ? 0 : 1; + if (isXhttp) { + alterId ??= 0; + if (Number(alterId) !== 0) throw new Error('VMess XHTTP requires AEAD'); } + result.append(`,alterId=${alterId}`); // tfo result.appendIfPresent(`,fast-open=${proxy.tfo}`, 'tfo'); @@ -528,8 +622,11 @@ function vless(proxy) { throw new Error(`VLESS encryption is not supported`); let isXtls = false; const isReality = !!proxy['reality-opts']; + const isXhttp = proxy.network === 'xhttp'; - if (typeof proxy.flow !== 'undefined') { + if (isXhttp && proxy.flow) + throw new Error('VLESS XHTTP does not support flow'); + if (!isXhttp && typeof proxy.flow !== 'undefined') { if (['xtls-rprx-vision'].includes(proxy.flow)) { isXtls = true; } else { @@ -568,6 +665,8 @@ function vless(proxy) { `,host=${Array.isArray(httpHost) ? httpHost[0] : httpHost}`, 'http-opts.headers.Host', ); + } else if (isXhttp) { + appendXhttp(result, proxy); } else { throw new Error(`network ${proxy.network} is unsupported`); } @@ -583,10 +682,8 @@ function vless(proxy) { `,skip-cert-verify=${proxy['skip-cert-verify']}`, 'skip-cert-verify', ); - if (proxy.tls || isReality || isXtls) { - appendTlsProfile(result, proxy); - appendAlpn(result, proxy); - } + if (proxy.tls || isReality || isXtls) appendTlsProfile(result, proxy); + if (proxy.tls || isReality || isXtls || isXhttp) appendAlpn(result, proxy); if (isXtls) { result.appendIfPresent(`,flow=${proxy.flow}`, 'flow'); @@ -595,7 +692,10 @@ function vless(proxy) { appendReality(result, proxy); } else { // sni - result.appendIfPresent(`,tls-name=${proxy.sni}`, 'sni'); + result.appendIfPresent( + `,${isXhttp ? 'sni' : 'tls-name'}=${proxy.sni}`, + 'sni', + ); result.appendIfPresent( `,tls-cert-sha256=${proxy['tls-fingerprint']}`, 'tls-fingerprint', diff --git a/backend/src/test/proxy-producers/text.spec.js b/backend/src/test/proxy-producers/text.spec.js index c99d4e3b..327f93e1 100644 --- a/backend/src/test/proxy-producers/text.spec.js +++ b/backend/src/test/proxy-producers/text.spec.js @@ -629,6 +629,7 @@ describe('Proxy text producers', function () { 'Trojan=trojan,trojan.example.com,443,"secret"', 'AnyTLS=anytls,anytls.example.com,443,"secret"', 'Hysteria2=hysteria2,hy2.example.com,443,"secret"', + 'Snell=snell,snell.example.com,6160,psk=secret,version=4', 'HTTP=http,http.example.com,8080', 'HTTPS=https,https.example.com,443', 'SOCKS5=socks5,socks.example.com,1080', @@ -712,6 +713,135 @@ describe('Proxy text producers', function () { } }); + it('round-trips Loon XHTTP for VLESS, VMess AEAD, and Trojan', function () { + const input = [ + `VLESS=vless,example.com,80,"${UUID}",transport=xhttp,path="/xhttp?route=a,b",host=cdn.example.com,over-tls=false,alpn=http/1.1,xhttp-mode=packet-up,xhttp-max-post-bytes=0,xhttp-min-post-interval-ms=30-60,xhttp-padding-obfs-mode=false,xhttp-session-id-table=Base62,xhttp-session-id-length=16-32,xhttp-header="X-Trace: a, b",xhttp-header="X-Origin: https://example.org",udp=true`, + `VMess=vmess,example.com,443,aes-128-gcm,"${UUID}",transport=xhttp,path=/xhttp?username=test,over-tls=true,alpn=h2,xhttp-mode=stream-up,xhttp-no-grpc-header=true,alterId=0`, + 'Trojan=trojan,example.com,443,"dGVzdA==",transport=xhttp,sni=cdn.example.com,public-key=pubkey,short-id="",alpn=h2,xhttp-mode=stream-one', + ].join('\n'); + const proxies = ProxyUtils.parse(input); + expect(proxies.map(({ type }) => type)).to.deep.equal([ + 'vless', + 'vmess', + 'trojan', + ]); + expect(proxies.every(({ network }) => network === 'xhttp')).to.be.true; + const [vless, vmess, trojan] = proxies; + expectSubset(vless, { + tls: false, + alpn: ['http/1.1'], + udp: true, + 'xhttp-opts': { + path: '/xhttp?route=a,b', + host: 'cdn.example.com', + mode: 'packet-up', + 'sc-max-each-post-bytes': 0, + 'sc-min-posts-interval-ms': '30-60', + 'x-padding-obfs-mode': false, + 'session-table': 'Base62', + 'session-length': '16-32', + headers: { + 'X-Trace': 'a, b', + 'X-Origin': 'https://example.org', + }, + }, + }); + expectSubset(vmess, { + alterId: 0, + tls: true, + alpn: ['h2'], + 'xhttp-opts': { mode: 'stream-up', 'no-grpc-header': true }, + }); + expectSubset(trojan, { + password: 'dGVzdA==', + tls: true, + 'reality-opts': { 'public-key': 'pubkey', 'short-id': '' }, + 'xhttp-opts': { mode: 'stream-one' }, + }); + + const output = produceExternal('Loon', proxies); + expect(output).to.include(',xhttp-header="X-Trace: a, b"'); + expect(output).to.include( + ',xhttp-header="X-Origin: https://example.org"', + ); + expect(output).not.to.include(',block-quic='); + expect(ProxyUtils.parse(output)).to.deep.equal(proxies); + }); + + it('rejects non-AEAD VMess over Loon XHTTP', function () { + const input = `VMess=vmess,example.com,443,auto,"${UUID}",transport=xhttp,alterId=1`; + expect(captureErrors(() => ProxyUtils.parse(input)).result).to.be.empty; + expect( + captureErrors(() => + produceInternal('Loon', { + name: 'VMess', + type: 'vmess', + server: 'example.com', + port: 443, + uuid: UUID, + aead: false, + network: 'xhttp', + }), + ).result, + ).to.be.empty; + }); + + it('distinguishes Loon Snell v4/v5 inputs from Surge and emits Loon Snell', function () { + const input = [ + 'Surge v4=opensnell,example.com,6160,psk=secret,version=4,reuse=true,udp-relay=true,block-quic=off', + 'Loon v4=Snell,example.com,6160,"key,with=comma"', + 'Loon v5=OpenSnell,example.com,6161,psk="secret",version=5,obfs-name=http,obfs-host=cdn.example.com,obfs-uri="/a,b?c=d",udp=true,block-quic=false,ip-mode=prefer-v4,server-dns="system,2001:db8::53"', + 'Loon block=snell,example.com,6161,psk=secret,version=5,block-quic=true', + 'Surge default=snell,example.com,6161,psk="key,udp=true",reuse=true,obfs=http,obfs-uri=/obfs', + ].join('\n'); + const proxies = ProxyUtils.parse(input); + expect(proxies).to.have.length(5); + const [surgeV4, loonV4, loonV5, loonBlock, surgeDefault] = proxies; + expect(surgeV4).to.include({ + type: 'snell', + reuse: true, + udp: true, + 'block-quic': 'off', + }); + expect(loonV4).to.include({ + type: 'snell', + psk: 'key,with=comma', + version: 4, + udp: false, + }); + expect(loonV4).not.to.have.property('block-quic'); + expectSubset(loonV5, { + type: 'snell', + version: 5, + udp: true, + 'block-quic': 'off', + 'ip-version': 'prefer-v4', + 'server-dns': ['system', '2001:db8::53'], + 'obfs-opts': { + mode: 'http', + host: 'cdn.example.com', + path: '/a,b?c=d', + }, + }); + expect(loonBlock).to.include({ udp: false, 'block-quic': 'on' }); + expect(surgeDefault).to.include({ reuse: true, psk: 'key,udp=true' }); + expect(surgeDefault).not.to.have.property('version'); + expect(surgeDefault).not.to.have.property('block-quic'); + + const { result: output } = captureErrors(() => + produceExternal('Loon', proxies), + ); + expect(output.split('\n')).to.deep.equal([ + 'Surge v4=snell,example.com,6160,"secret",version=4,udp=true,block-quic=false', + 'Loon v4=snell,example.com,6160,"key,with=comma",version=4,udp=false', + 'Loon v5=snell,example.com,6161,"secret",version=5,obfs=http,obfs-host=cdn.example.com,obfs-uri="/a,b?c=d",udp=true,block-quic=false,ip-mode=prefer-v4,server-dns="system,2001:db8::53"', + 'Loon block=snell,example.com,6161,"secret",version=5,udp=false,block-quic=true', + ]); + expect(ProxyUtils.parse(output).slice(1)).to.deep.equal( + proxies.slice(1, 4), + ); + }); + it('produces Loon VLESS reality websocket lines', function () { const output = produceExternal('Loon', { type: 'vless',