From 85948dcf96bcb81eb66963a615f24491ecc19e14 Mon Sep 17 00:00:00 2001 From: xream Date: Mon, 23 Nov 2026 22:51:16 +0800 Subject: [PATCH] feat: Loon XHTTP, VLESS Encryption, mieru --- backend/package.json | 2 +- backend/src/core/proxy-utils/loon-xhttp.js | 132 ++++- backend/src/core/proxy-utils/parsers/index.js | 8 + .../core/proxy-utils/parsers/peggy/loon.js | 39 +- .../src/core/proxy-utils/producers/loon.js | 282 +++++++-- backend/src/test/proxy-producers/text.spec.js | 543 +++++++++++++++++- 6 files changed, 942 insertions(+), 64 deletions(-) diff --git a/backend/package.json b/backend/package.json index 3264f385..9d9c404c 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.44.26", + "version": "2.44.27", "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 index a009a876..3bed2315 100644 --- a/backend/src/core/proxy-utils/loon-xhttp.js +++ b/backend/src/core/proxy-utils/loon-xhttp.js @@ -1,4 +1,51 @@ -import { normalizeXhttpNonNegativeRange } from './xhttp-utils'; +import _ from 'lodash'; +import { + normalizeXhttpIntegerValue, + normalizeXhttpNonNegativeRange, + normalizeXhttpPositiveRange, +} from './xhttp-utils'; + +const PADDING_FIELDS = { + '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', +}; + +const SESSION_FIELDS = { + 'session-id-placement': 'session-placement', + 'session-id-key': 'session-key', +}; + +const XMUX_FIELDS = { + '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-http-max-requests': 'reuse-settings.h-max-request-times', + 'xmux-http-max-reusable-secs': 'reuse-settings.h-max-reusable-secs', + 'xmux-http-keepalive-secs': 'reuse-settings.h-keep-alive-period', +}; + +const DOWNLOAD_FIELDS = { + server: 'server', + port: 'port', + host: 'host', + path: 'path', + alpn: 'alpn', + 'over-tls': 'tls', + sni: 'servername', + 'skip-cert-verify': 'skip-cert-verify', + 'tls-profile': '_loon_tls_profile', + 'tls-cert-sha256': 'fingerprint', + 'tls-pubkey-sha256': 'tls-pubkey-sha256', + 'public-key': 'reality-opts.public-key', + 'short-id': 'reality-opts.short-id', + ...XMUX_FIELDS, + ...PADDING_FIELDS, + ...SESSION_FIELDS, +}; export const LOON_XHTTP_FIELDS = { mode: 'mode', @@ -8,26 +55,82 @@ export const LOON_XHTTP_FIELDS = { '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', + ...PADDING_FIELDS, 'no-grpc-header': 'no-grpc-header', - 'session-id-placement': 'session-placement', - 'session-id-key': 'session-key', + ...SESSION_FIELDS, 'session-id-table': 'session-table', 'session-id-length': 'session-length', 'seq-placement': 'seq-placement', 'seq-key': 'seq-key', + ...XMUX_FIELDS, + ...Object.fromEntries( + Object.entries(DOWNLOAD_FIELDS).map(([key, path]) => [ + `download-${key}`, + `download-settings.${path}`, + ]), + ), }; +export function validateLoonXhttpXmux(opts) { + if (!opts) return; + + for (const prefix of ['', 'download-']) { + const getOption = (key) => + _.get(opts, LOON_XHTTP_FIELDS[`${prefix}${key}`]); + + for (const key of Object.keys(XMUX_FIELDS)) { + const value = getOption(key); + if (value == null) continue; + + const isKeepalive = key === 'xmux-http-keepalive-secs'; + const normalized = isKeepalive + ? normalizeXhttpIntegerValue(value) + : normalizeXhttpNonNegativeRange(value); + if (normalized == null || (isKeepalive && normalized < -1)) { + const expected = isKeepalive + ? 'an integer of at least -1' + : 'a non-negative integer or a valid non-negative integer range'; + throw new Error( + `Loon xhttp-${prefix}${key} must be ${expected}`, + ); + } + } + + const maxConcurrency = getOption('xmux-max-concurrency'); + const maxConnections = getOption('xmux-max-connections'); + if ( + normalizeXhttpPositiveRange(maxConcurrency) != null && + normalizeXhttpPositiveRange(maxConnections) != null + ) { + const optionPrefix = `xhttp-${prefix}xmux`; + throw new Error( + `Loon ${optionPrefix}-max-concurrency and ${optionPrefix}-max-connections cannot both be positive`, + ); + } + } +} + export function setLoonXhttpOption(opts, key, value) { + if (key === 'header' || key === 'download-header') { + const colon = value.indexOf(':'); + if (colon <= 0) return; + const name = value.slice(0, colon).trim(); + if (!name || /^host$/i.test(name)) return; + const target = + key === 'header' ? opts : (opts['download-settings'] ??= {}); + target.headers = { + ...target.headers, + [name]: value.slice(colon + 1).trim(), + }; + return; + } + if (!Object.prototype.hasOwnProperty.call(LOON_XHTTP_FIELDS, key)) return; - switch (key) { + switch (key.replace(/^download-/, '')) { case 'padding-obfs-mode': case 'no-grpc-header': + case 'over-tls': + case 'skip-cert-verify': if (value !== 'true' && value !== 'false') return; value = value === 'true'; break; @@ -36,6 +139,13 @@ export function setLoonXhttpOption(opts, key, value) { case 'uplink-chunk-size': value = normalizeXhttpNonNegativeRange(value) ?? value; break; + case 'port': + case 'xmux-http-keepalive-secs': + value = normalizeXhttpIntegerValue(value) ?? value; + break; + case 'alpn': + value = [value]; + break; } - opts[LOON_XHTTP_FIELDS[key]] = value; + _.set(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 0dfa76fe..732fd8d9 100644 --- a/backend/src/core/proxy-utils/parsers/index.js +++ b/backend/src/core/proxy-utils/parsers/index.js @@ -2910,6 +2910,13 @@ function Loon_Tailscale() { return { name, test, parse }; } +function Loon_Mieru() { + const name = 'Loon Mieru Parser'; + const test = (line) => /^[^=,]*=\s*mieru\s*,/i.test(line); + const parse = (line) => getLoonParser().parse(line); + return { name, test, parse }; +} + function Loon_WireGuard() { const name = 'Loon WireGuard Parser'; const test = (line) => { @@ -3319,6 +3326,7 @@ export default [ Loon_Socks5(), Loon_WireGuard(), Loon_Tailscale(), + Loon_Mieru(), QX_SS(), QX_SSR(), QX_VMess(), diff --git a/backend/src/core/proxy-utils/parsers/peggy/loon.js b/backend/src/core/proxy-utils/parsers/peggy/loon.js index a22b5539..16f92c38 100644 --- a/backend/src/core/proxy-utils/parsers/peggy/loon.js +++ b/backend/src/core/proxy-utils/parsers/peggy/loon.js @@ -22,7 +22,7 @@ const grammars = String.raw` const obfs = {}; const transport = {}; const xhttpOpts = {}; - const xhttpHeaders = []; + const vlessEncryption = {}; const shadowTLS = {}; const $ = {}; @@ -44,7 +44,12 @@ const grammars = String.raw` 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); + const download = xhttpOpts["download-settings"]; + if (download) { + download.tls ??= Boolean(download["reality-opts"]?.["public-key"]); + const fingerprint = loonClientFingerprint(download._loon_tls_profile); + if (fingerprint) download["client-fingerprint"] = fingerprint; + } proxy["xhttp-opts"] = xhttpOpts; } } @@ -86,7 +91,7 @@ const grammars = String.raw` } } -start = (shadowsocksr/shadowsocks/vmess/vless/trojan/https/http/socks5/hysteria2/anytls/tailscale/snell) { +start = (shadowsocksr/shadowsocks/vmess/vless/trojan/https/http/socks5/hysteria2/anytls/tailscale/snell/mieru) { return proxy; } @@ -107,17 +112,22 @@ shadowsocks = tag equals "shadowsocks"i address method password (obfs_typev obfs } handleShadowTLS(); } -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)* { +vmess = tag equals "vmess"i address vmess_method uuid (xhttp_transport/transport/transport_host/transport_path/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 (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)* { +vless = tag equals "vless"i address uuid (xhttp_transport/transport/transport_host/transport_path/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/vless_encryption/public_key/short_id/block_quic/others)* { proxy.type = "vless"; + const { mode, rtt, padding, "public-keys": publicKeys } = vlessEncryption; + if (mode && mode !== "none") { + if (!publicKeys) throw new Error("VLESS encryption requires public keys"); + proxy.encryption = ["mlkem768x25519plus", mode, rtt || "0rtt", padding, publicKeys].filter(Boolean).join("."); + } handleTransport(); } -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)* { +trojan = tag equals "trojan"i address password (xhttp_transport/transport/transport_host/transport_path/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(); } @@ -152,6 +162,13 @@ snell = tag equals ("snell"i/"opensnell"i) address snell_positional_psk? (snell_ proxy["obfs-opts"] = { mode: obfs.type, host: obfs.host, path: obfs.path }; } } +mieru = tag equals "mieru"i address comma user:option_value comma pass:option_value (udp_relay/ip_mode/block_quic/others)* { + proxy.type = "mieru"; + proxy.transport = "TCP"; + proxy.username = user; + proxy.password = pass; + proxy.udp ??= false; +} tailscale_string = comma key:("auth-key"/"control-url"/"hostname"/"exit-node"/"path-mode"/"ip-mode") equals value:( '"' match:$[^"]* '"' { return match; } @@ -254,13 +271,6 @@ 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); } @@ -296,6 +306,9 @@ alpn = comma "alpn" equals match:option_value { } flow = comma "flow" equals match:[^,]+ { proxy["flow"] = match.join("").replace(/^"(.*)"$/, '$1'); } +vless_encryption = comma "encryption-" key:("mode"/"rtt"/"public-keys"/"padding") equals value:option_value { + vlessEncryption[key] = value; +} 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 value:option_value { proxy["reality-opts"] = proxy["reality-opts"] || {}; proxy["reality-opts"]["short-id"] = value; } diff --git a/backend/src/core/proxy-utils/producers/loon.js b/backend/src/core/proxy-utils/producers/loon.js index 1ccb2e94..87639dcd 100644 --- a/backend/src/core/proxy-utils/producers/loon.js +++ b/backend/src/core/proxy-utils/producers/loon.js @@ -1,10 +1,13 @@ /* eslint-disable no-case-declarations */ const targetPlatform = 'Loon'; +import { Buffer } from 'buffer'; +import _ from 'lodash'; import { isPresent, Result } from './utils'; -import { isIPv4, isIPv6, isPlainObject } from '@/utils'; +import { getIfNotBlank, isIPv4, isIPv6, isPlainObject } from '@/utils'; import $ from '@/core/app'; -import { LOON_XHTTP_FIELDS } from '../loon-xhttp'; +import { LOON_XHTTP_FIELDS, validateLoonXhttpXmux } from '../loon-xhttp'; import { formatLoonVmessSecurity } from '../vmess-security'; +import { normalizeXhttpIntegerValue } from '../xhttp-utils'; const ipVersions = { dual: 'dual', @@ -47,6 +50,8 @@ export default function Loon_Producer() { return tailscale(proxy); case 'hysteria2': return hysteria2(proxy); + case 'mieru': + return mieru(proxy); } if (proxy.type === 'anytls') { if (proxy.network && !['tcp'].includes(proxy.network)) { @@ -77,8 +82,8 @@ function appendTlsProfile(result, proxy) { if (tlsProfile) result.append(`,tls-profile=${tlsProfile}`); } -function appendAlpn(result, proxy) { - const alpn = getLoonAlpn(proxy); +function appendAlpn(result, proxy, isXhttp = false) { + const alpn = isXhttp ? getLoonXhttpAlpn(proxy) : getLoonAlpn(proxy); if (alpn) result.append(`,alpn="${alpn}"`); } @@ -92,36 +97,110 @@ function formatLoonValue(value, quoted = false) { function appendXhttp(result, proxy) { const xhttp = proxy['xhttp-opts']; - if (xhttp?.['download-settings']) { - throw new Error('Loon XHTTP does not support download-settings'); + const download = xhttp?.['download-settings']; + if (download?.plugin || download?.['shadow-tls-opts']) { + throw new Error('Loon XHTTP download-settings do not support plugins'); + } + validateLoonXhttpXmux(xhttp); + + let options = xhttp; + if (download) { + const server = + getIfNotBlank(download.server) ?? getIfNotBlank(proxy.server); + if (server == null) { + throw new Error( + 'Loon xhttp-download-server requires a server address', + ); + } + + const port = normalizeXhttpIntegerValue(download.port ?? proxy.port); + if (port == null || port < 1 || port > 65535) { + throw new Error( + 'Loon xhttp-download-port must be an integer from 1 to 65535', + ); + } + + const reality = download['reality-opts']; + const hasReality = Boolean(getIfNotBlank(reality?.['public-key'])); + if (reality && !hasReality) { + throw new Error( + 'Loon XHTTP download REALITY requires a non-blank public-key', + ); + } + if (hasReality && [false, 'false'].includes(download.tls)) { + throw new Error( + 'Loon XHTTP download REALITY conflicts with xhttp-download-over-tls=false', + ); + } + + const alpn = getLoonXhttpAlpn(download, true); + + const fingerprint = download.fingerprint ?? download['tls-fingerprint']; + const pubkeyFingerprint = download['tls-pubkey-sha256']; + const skipCertVerify = download['skip-cert-verify']; + if ( + hasReality && + (fingerprint || + pubkeyFingerprint || + [true, 'true'].includes(skipCertVerify)) + ) { + throw new Error( + 'Loon XHTTP download REALITY conflicts with skip-cert-verify=true or TLS certificate fingerprints', + ); + } + + options = { + ...xhttp, + 'download-settings': { + ...download, + server: server.trim(), + port, + host: getXhttpHost(download), + alpn: alpn || undefined, + servername: download.servername ?? download.sni, + fingerprint: hasReality ? undefined : fingerprint, + 'tls-pubkey-sha256': hasReality ? undefined : pubkeyFingerprint, + 'skip-cert-verify': hasReality ? undefined : skipCertVerify, + _loon_tls_profile: getLoonTlsProfile(download), + }, + }; } - 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], + ['host', getXhttpHost(xhttp)], ]) { if (value != null) result.append(`,${key}=${formatLoonValue(value)}`); } for (const [key, field] of Object.entries(LOON_XHTTP_FIELDS)) { - const value = xhttp?.[field]; + const value = _.get(options, field); if (value != null) result.append(`,xhttp-${key}=${formatLoonValue(value)}`); } - for (const [key, value] of headers) { - if (!/^host$/i.test(key) && value != null) { + for (const [option, headers] of [ + ['xhttp-header', xhttp?.headers], + ['xhttp-download-header', download?.headers], + ]) { + if (!isPlainObject(headers)) continue; + for (const [key, value] of Object.entries(headers)) { + if (/^host$/i.test(key) || value == null) continue; result.append( - `,xhttp-header=${formatLoonValue(`${key}: ${value}`, true)}`, + `,${option}=${formatLoonValue(`${key}: ${value}`, true)}`, ); } } } +function getXhttpHost(opts) { + if (opts?.host != null) return opts.host; + if (isPlainObject(opts?.headers)) { + return Object.entries(opts.headers).find(([key]) => + /^host$/i.test(key), + )?.[1]; + } +} + function getLoonShadowTLSAlpn(proxy) { const values = proxy?.['plugin-opts']?.alpn ?? proxy?.alpn; const normalized = Array.isArray(values) @@ -177,6 +256,34 @@ function getLoonAlpn(proxy) { .join(','); } +function getLoonXhttpAlpn(endpoint, isDownload = false) { + const alpn = getLoonAlpn(endpoint); + if (!alpn) return alpn; + if (alpn.includes(',')) { + const scope = isDownload ? ' download' : ''; + throw new Error(`Loon XHTTP${scope} supports only a single ALPN`); + } + + const hasReality = Boolean(endpoint['reality-opts']?.['public-key']); + const hasTls = + (!isDownload && endpoint.type === 'trojan') || + [true, 'true'].includes(endpoint.tls); + const allowed = hasReality + ? ['h2'] + : hasTls + ? ['http/1.1', 'h2', 'h3'] + : ['http/1.1']; + if (!allowed.includes(alpn)) { + const field = isDownload ? 'xhttp-download-alpn' : 'XHTTP alpn'; + throw new Error( + `Loon ${field} must be ${allowed.join( + ' or ', + )} for the configured security`, + ); + } + return alpn; +} + function getLoonTlsProfile(proxy) { const tlsProfile = `${proxy._loon_tls_profile || ''}`.trim(); if ( @@ -413,7 +520,7 @@ function trojan(proxy) { 'skip-cert-verify', ); appendTlsProfile(result, proxy); - appendAlpn(result, proxy); + appendAlpn(result, proxy, isXhttp); if (isReality) { appendReality(result, proxy); @@ -569,7 +676,7 @@ function vmess(proxy) { 'skip-cert-verify', ); if (proxy.tls || isReality) appendTlsProfile(result, proxy); - if (proxy.tls || isReality || isXhttp) appendAlpn(result, proxy); + if (proxy.tls || isReality || isXhttp) appendAlpn(result, proxy, isXhttp); if (isReality) { appendReality(result, proxy); @@ -617,21 +724,76 @@ function vmess(proxy) { return result.toString(); } -function vless(proxy) { - if (proxy.encryption && proxy.encryption !== 'none') - throw new Error(`VLESS encryption is not supported`); - let isXtls = false; - const isReality = !!proxy['reality-opts']; - const isXhttp = proxy.network === 'xhttp'; +function appendVlessEncryption(result, encryption) { + if (!encryption || encryption === 'none') return; - 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 { - throw new Error(`VLESS flow(${proxy.flow}) is not supported`); + const [method, mode, rtt, ...settings] = encryption.split('.'); + const paddingGroup = /^(-?\d+)-(-?\d+)-(-?\d+)$/; + const keyIndex = settings.findIndex((part) => !paddingGroup.test(part)); + if ( + method !== 'mlkem768x25519plus' || + !['native', 'xorpub', 'random'].includes(mode) || + !['0rtt', '1rtt'].includes(rtt) || + !settings[keyIndex] + ) { + throw new Error('Unsupported VLESS encryption format'); + } + + const padding = settings.slice(0, keyIndex); + for (const [index, group] of padding.entries()) { + const [, probability, min, max] = paddingGroup.exec(group).map(Number); + if (index === 0 && (probability !== 100 || min < 35 || max < 35)) { + throw new Error( + 'Loon VLESS encryption-padding first group requires probability 100 and lengths of at least 35', + ); } + if ( + probability < 0 || + probability > 100 || + min < 0 || + min > max || + !Number.isSafeInteger(max) + ) { + throw new Error( + 'Loon VLESS encryption-padding requires probabilities from 0 to 100 and ordered non-negative integer bounds', + ); + } + } + + const publicKeys = settings.slice(keyIndex).join('.'); + result.append(`,encryption-mode=${mode},encryption-rtt=${rtt}`); + result.append( + `,encryption-public-keys=${formatLoonValue(publicKeys, true)}`, + ); + if (padding.length) { + result.append( + `,encryption-padding=${formatLoonValue(padding.join('.'))}`, + ); + } +} + +function vless(proxy) { + const isXtls = !!proxy.flow; + const reality = proxy['reality-opts']; + const isReality = Boolean(getIfNotBlank(reality?.['public-key'])); + const isXhttp = proxy.network === 'xhttp'; + const isTcp = (proxy.network ?? 'tcp') === 'tcp'; + const isSecure = isReality || [true, 'true'].includes(proxy.tls); + const encryptionEnabled = proxy.encryption && proxy.encryption !== 'none'; + + if (reality && !isReality) { + throw new Error('Loon VLESS REALITY requires a non-blank public-key'); + } + if ( + isXtls && + !['xtls-rprx-vision', 'xtls-rprx-vision-udp443'].includes(proxy.flow) + ) { + throw new Error(`VLESS flow(${proxy.flow}) is not supported`); + } + if (isXtls && !encryptionEnabled && (!isTcp || !isSecure)) { + throw new Error( + 'Loon VLESS Vision without encryption requires TCP with TLS or REALITY', + ); } const result = new Result(proxy); @@ -683,11 +845,11 @@ function vless(proxy) { 'skip-cert-verify', ); if (proxy.tls || isReality || isXtls) appendTlsProfile(result, proxy); - if (proxy.tls || isReality || isXtls || isXhttp) appendAlpn(result, proxy); + if (proxy.tls || isReality || isXtls || isXhttp) + appendAlpn(result, proxy, isXhttp); - if (isXtls) { - result.appendIfPresent(`,flow=${proxy.flow}`, 'flow'); - } + appendVlessEncryption(result, proxy.encryption); + if (isXtls) result.append(`,flow=${proxy.flow}`); if (isReality) { appendReality(result, proxy); } else { @@ -915,6 +1077,56 @@ function wireguard(proxy) { return result.toString(); } +function mieru(proxy) { + if (proxy.transport && String(proxy.transport).toUpperCase() !== 'TCP') { + throw new Error('Loon Mieru requires TCP transport'); + } + if (proxy.tls || proxy['reality-opts']) { + throw new Error('Loon Mieru does not support TLS or REALITY'); + } + const server = getIfNotBlank(proxy.server)?.trim(); + if (!server) throw new Error('Loon Mieru requires a server'); + + const portText = String(proxy.port ?? '').trim(); + const port = Number(portText); + if (!/^\d+$/.test(portText) || port < 1 || port > 65535) { + throw new Error('Loon Mieru port must be an integer from 1 to 65535'); + } + + const credentials = [proxy.username, proxy.password].map((value) => + String(value ?? ''), + ); + if ( + credentials.some( + (value) => !value || Buffer.byteLength(value, 'utf8') > 64, + ) + ) { + throw new Error( + 'Loon Mieru username and password must each be 1-64 UTF-8 bytes', + ); + } + + const result = new Result(proxy); + const address = isIPv6(server) ? `[${server}]` : server; + const [username, password] = credentials.map((value) => + formatLoonValue(value, true), + ); + result.append( + `${proxy.name}=mieru,${address},${port},${username},${password}`, + ); + if (proxy.udp) result.append(',udp=true'); + + const blockQuic = proxy['block-quic']; + if (['on', 'off', true, false].includes(blockQuic)) { + result.append( + `,block-quic=${blockQuic === 'on' || blockQuic === true}`, + ); + } + const ipVersion = ipVersions[proxy['ip-version']] || proxy['ip-version']; + result.appendIfPresent(`,ip-mode=${ipVersion}`, 'ip-version'); + return result.toString(); +} + function hysteria2(proxy) { if (proxy['obfs-password'] && proxy.obfs != 'salamander') { throw new Error(`only salamander obfs is supported`); diff --git a/backend/src/test/proxy-producers/text.spec.js b/backend/src/test/proxy-producers/text.spec.js index c7205ad4..b6ae7a34 100644 --- a/backend/src/test/proxy-producers/text.spec.js +++ b/backend/src/test/proxy-producers/text.spec.js @@ -4,6 +4,7 @@ import { describe, it } from 'mocha'; import $ from '@/core/app'; import { ProxyUtils } from '@/core/proxy-utils'; +import Loon_Producer from '@/core/proxy-utils/producers/loon'; import QX_Producer from '@/core/proxy-utils/producers/qx'; import { expectSubset, @@ -841,7 +842,7 @@ 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`, + `VMess=vmess,example.com,443,aes-128-gcm,"${UUID}",transport=xhttp,path=/xhttp?username=test,over-tls=true,alpn=h3,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); @@ -874,7 +875,7 @@ describe('Proxy text producers', function () { expectSubset(vmess, { alterId: 0, tls: true, - alpn: ['h2'], + alpn: ['h3'], 'xhttp-opts': { mode: 'stream-up', 'no-grpc-header': true }, }); expectSubset(trojan, { @@ -893,6 +894,537 @@ describe('Proxy text producers', function () { expect(ProxyUtils.parse(output)).to.deep.equal(proxies); }); + it('round-trips Loon XHTTP XMUX and independent download options', function () { + const input = [ + 'Split=trojan,upload.example.com,443,"secret",transport=xhttp,alpn=h3,xhttp-mode=stream-up', + 'xhttp-xmux-max-connections=3,xhttp-xmux-http-max-requests=600-900,xhttp-xmux-http-keepalive-secs=0', + 'xhttp-download-server=download.example.com,xhttp-download-port=8443,xhttp-download-host=cdn.example.com,xhttp-download-path="/down?route=a,b"', + 'xhttp-download-alpn=h2,xhttp-download-over-tls=true,xhttp-download-sni=peer.example.com,xhttp-download-skip-cert-verify=false,xhttp-download-tls-profile=chrome,xhttp-download-tls-cert-sha256=cert-pin,xhttp-download-tls-pubkey-sha256=key-pin', + 'xhttp-download-xmux-max-concurrency=8-16,xhttp-download-xmux-max-reuse-times=0,xhttp-download-xmux-http-max-reusable-secs=1800-3000,xhttp-download-xmux-http-keepalive-secs=-1', + 'xhttp-download-padding-bytes=100-300,xhttp-download-padding-obfs-mode=false,xhttp-download-session-id-placement=header,xhttp-download-session-id-key=X-Session', + 'xhttp-download-header="X-Trace: a,b",xhttp-download-header="X-Origin: https://example.org"', + ].join(','); + const [proxy] = ProxyUtils.parse(input); + expectSubset(proxy, { + alpn: ['h3'], + 'xhttp-opts': { + 'reuse-settings': { + 'max-connections': '3', + 'h-max-request-times': '600-900', + 'h-keep-alive-period': 0, + }, + 'download-settings': { + server: 'download.example.com', + port: 8443, + host: 'cdn.example.com', + path: '/down?route=a,b', + alpn: ['h2'], + tls: true, + servername: 'peer.example.com', + 'skip-cert-verify': false, + 'client-fingerprint': 'chrome', + fingerprint: 'cert-pin', + 'tls-pubkey-sha256': 'key-pin', + 'reuse-settings': { + 'max-concurrency': '8-16', + 'c-max-reuse-times': '0', + 'h-max-reusable-secs': '1800-3000', + 'h-keep-alive-period': -1, + }, + 'x-padding-bytes': '100-300', + 'x-padding-obfs-mode': false, + 'session-placement': 'header', + 'session-key': 'X-Session', + headers: { + 'X-Trace': 'a,b', + 'X-Origin': 'https://example.org', + }, + }, + }, + }); + const output = produceExternal('Loon', proxy); + expect(output).to.include(',xhttp-download-header="X-Trace: a,b"'); + expect(ProxyUtils.parse(output)).to.deep.equal([proxy]); + + const [reality] = ProxyUtils.parse( + `Split=vless,upload.example.com,443,"${UUID}",transport=xhttp,over-tls=true,alpn=h3,xhttp-download-server=download.example.com,xhttp-download-port=8443,xhttp-download-sni=peer.example.com,xhttp-download-public-key="public-key",xhttp-download-short-id=""`, + ); + expectSubset(reality['xhttp-opts']['download-settings'], { + tls: true, + 'reality-opts': { 'public-key': 'public-key', 'short-id': '' }, + }); + expect( + ProxyUtils.parse(produceExternal('Loon', reality)), + ).to.deep.equal([reality]); + }); + + it('validates Loon XHTTP XMUX quotas per endpoint', function () { + const input = `Split=vless,upload.example.com,443,"${UUID}",transport=xhttp,over-tls=true,alpn=h2,xhttp-mode=stream-up`; + const split = `${input},xhttp-download-server=download.example.com,xhttp-download-port=8443,xhttp-download-over-tls=true,xhttp-download-alpn=h2`; + for (const [line, prefix, concurrency, connections] of [ + [input, 'xhttp-xmux', '8', '3'], + [split, 'xhttp-download-xmux', '0-8', '3-4'], + ]) { + const proxies = ProxyUtils.parse( + `${line},${prefix}-max-concurrency=${concurrency},${prefix}-max-connections=${connections}`, + ); + expect(proxies).to.have.length(1); + const { result, errors } = captureErrors(() => + produceInternal('Loon', proxies), + ); + expect(result).to.be.empty; + expect(errors[0]).to.include( + `${prefix}-max-concurrency and ${prefix}-max-connections`, + ); + + const valid = ProxyUtils.parse( + `${line},${prefix}-max-concurrency=0,${prefix}-max-connections=${connections}`, + ); + expect(produceExternal('Loon', valid)).to.include( + `,${prefix}-max-connections=${connections}`, + ); + } + }); + + it('validates the range of every Loon XHTTP XMUX field on both endpoints', function () { + const input = `Split=vless,upload.example.com,443,"${UUID}",transport=xhttp,over-tls=true,alpn=h2,xhttp-mode=stream-up`; + const split = `${input},xhttp-download-server=download.example.com,xhttp-download-port=8443,xhttp-download-over-tls=true,xhttp-download-alpn=h2`; + for (const [line, prefix] of [ + [input, 'xhttp-xmux'], + [split, 'xhttp-download-xmux'], + ]) { + for (const [key, invalid, valid] of [ + ['max-concurrency', '8-2', '8-16'], + ['max-connections', '-1', '3'], + ['max-reuse-times', 'invalid', '0'], + ['http-max-requests', '1.5', '600-900'], + ['http-max-reusable-secs', '-5', '1800'], + ['http-keepalive-secs', '-2', '-1'], + ['http-keepalive-secs', '10-20', '0'], + ['http-keepalive-secs', '1.5', '15'], + ]) { + const option = `${prefix}-${key}`; + const proxies = ProxyUtils.parse( + `${line},${option}=${invalid}`, + ); + expect(proxies).to.have.length(1); + const { result, errors } = captureErrors(() => + produceInternal('Loon', proxies), + ); + expect(result, option).to.be.empty; + expect(errors[0]).to.include(`${option} must be`); + + const accepted = ProxyUtils.parse(`${line},${option}=${valid}`); + expect(produceExternal('Loon', accepted)).to.include( + `,${option}=${valid}`, + ); + } + } + }); + + it('uses a non-blank server for Loon XHTTP downloads', function () { + const input = `Split=vless,upload.example.com,443,"${UUID}",transport=xhttp,xhttp-download-port=8443`; + for (const [option, expected] of [ + ['', 'upload.example.com'], + [',xhttp-download-server=""', 'upload.example.com'], + [',xhttp-download-server=" "', 'upload.example.com'], + [ + ',xhttp-download-server=" download.example.com "', + 'download.example.com', + ], + ]) { + const proxies = ProxyUtils.parse(input + option); + expect(produceExternal('Loon', proxies)).to.include( + `,xhttp-download-server=${expected}`, + ); + } + + const [proxy] = ProxyUtils.parse(`${input},xhttp-download-server=" "`); + const { result, errors } = captureErrors(() => + produceInternal('Loon', { ...proxy, server: ' ' }), + ); + expect(result).to.be.empty; + expect(errors[0]).to.include( + 'xhttp-download-server requires a server address', + ); + }); + + it('validates Loon XHTTP download port boundaries on export', function () { + const input = `Split=vless,upload.example.com,443,"${UUID}",transport=xhttp,xhttp-download-server=download.example.com`; + for (const port of [0, -1, 70000, 443.5, 'invalid']) { + const proxies = ProxyUtils.parse( + `${input},xhttp-download-port=${port}`, + ); + expect(proxies).to.have.length(1); + const { result, errors } = captureErrors(() => + produceInternal('Loon', proxies), + ); + expect(result).to.be.empty; + expect(errors[0]).to.include( + 'xhttp-download-port must be an integer', + ); + } + + for (const port of [1, 65535]) { + const proxies = ProxyUtils.parse( + `${input},xhttp-download-port=${port}`, + ); + expect(produceExternal('Loon', proxies)).to.include( + `,xhttp-download-port=${port}`, + ); + } + expect(produceExternal('Loon', ProxyUtils.parse(input))).to.include( + ',xhttp-download-port=443', + ); + }); + + it('enforces Loon XHTTP main ALPN by security', function () { + const proxy = { + type: 'vless', + name: 'Main', + server: 'example.com', + port: 443, + uuid: UUID, + network: 'xhttp', + }; + const reality = { 'reality-opts': { 'public-key': 'A'.repeat(43) } }; + const trojan = { type: 'trojan', password: 'secret' }; + for (const [settings, reason] of [ + [{ tls: false, alpn: ['h2'] }, 'XHTTP alpn must be http/1.1'], + [{ type: 'vmess', alpn: ['h3'] }, 'XHTTP alpn must be http/1.1'], + [{ ...reality, tls: true, alpn: ['h3'] }, 'XHTTP alpn must be h2'], + [{ ...trojan, ...reality, alpn: ['h3'] }, 'XHTTP alpn must be h2'], + [{ tls: true, alpn: ['h2', 'h3'] }, 'only a single ALPN'], + ]) { + const { result, errors } = captureErrors(() => + produceInternal('Loon', { ...proxy, ...settings }), + ); + expect(result).to.be.empty; + expect(errors[0]).to.include(reason); + } + + expect( + produceExternal('Loon', { ...proxy, tls: false }), + ).not.to.include(',alpn='); + expect( + produceExternal('Loon', { ...proxy, ...trojan, alpn: ['h3'] }), + ).to.include(',alpn="h3"'); + }); + + it('rejects incomplete REALITY for Loon XHTTP downloads', function () { + const key = 'A'.repeat(43); + const options = + 'transport=xhttp,xhttp-mode=stream-up,xhttp-download-server=down.example.com,xhttp-download-port=8443'; + for (const input of [ + `Split=vless,example.com,443,"${UUID}",over-tls=true,public-key="${key}",${options},xhttp-download-public-key=""`, + `Split=vmess,example.com,443,aes-128-gcm,"${UUID}",alterId=0,${options},xhttp-download-public-key=" "`, + `Split=trojan,example.com,443,"secret",${options},xhttp-download-short-id=08`, + ]) { + const proxies = ProxyUtils.parse(input); + expect(proxies).to.have.length(1); + const { result, errors } = captureErrors(() => + produceInternal('Loon', proxies), + ); + expect(result).to.be.empty; + expect(errors[0]).to.include( + 'Loon XHTTP download REALITY requires a non-blank public-key', + ); + } + }); + + it('enforces Loon XHTTP download ALPN and certificate settings by security', function () { + const reality = { 'reality-opts': { 'public-key': 'A'.repeat(43) } }; + const realityConflict = 'conflicts with xhttp-download-over-tls=false'; + const certificateConflict = 'or TLS certificate fingerprints'; + const makeProxy = (settings) => ({ + type: 'vless', + name: 'Split', + server: 'upload.example.com', + port: 443, + uuid: UUID, + network: 'xhttp', + tls: true, + 'xhttp-opts': { + mode: 'stream-up', + 'download-settings': { + server: 'download.example.com', + port: 8443, + ...settings, + }, + }, + }); + for (const [settings, reason] of [ + [{ ...reality, tls: false }, realityConflict], + [{ ...reality, tls: 'false' }, realityConflict], + [{ alpn: ['h2', 'http/1.1'] }, 'a single ALPN'], + [{ alpn: ['h2,http/1.1'] }, 'a single ALPN'], + [{ alpn: 'h2,http/1.1' }, 'a single ALPN'], + [{ alpn: ['h2'] }, 'xhttp-download-alpn must be http/1.1'], + [ + { tls: false, alpn: ['h3'] }, + 'xhttp-download-alpn must be http/1.1', + ], + [{ ...reality, alpn: ['h3'] }, 'xhttp-download-alpn must be h2'], + [ + { tls: true, alpn: ['unknown'] }, + 'xhttp-download-alpn must be http/1.1 or h2 or h3', + ], + [{ ...reality, 'skip-cert-verify': true }, certificateConflict], + [{ ...reality, 'skip-cert-verify': 'true' }, certificateConflict], + [{ ...reality, fingerprint: 'cert-pin' }, certificateConflict], + [ + { ...reality, 'tls-fingerprint': 'cert-pin' }, + certificateConflict, + ], + [ + { ...reality, 'tls-pubkey-sha256': 'key-pin' }, + certificateConflict, + ], + ]) { + const { result, errors } = captureErrors(() => + produceInternal('Loon', makeProxy(settings)), + ); + expect(result).to.be.empty; + expect(errors[0]).to.include(reason); + } + + for (const settings of [ + { alpn: ['http/1.1'] }, + { tls: true, alpn: ['http/1.1'] }, + { tls: true, alpn: ['h2'] }, + { tls: 'true', alpn: ['h3'] }, + { ...reality, alpn: ['h2'] }, + ]) { + expect(produceExternal('Loon', makeProxy(settings))).to.include( + `,xhttp-download-alpn=${settings.alpn[0]}`, + ); + } + + const output = produceExternal( + 'Loon', + makeProxy({ + ...reality, + 'skip-cert-verify': false, + fingerprint: '', + 'tls-pubkey-sha256': '', + }), + ); + expect(output).to.include(',xhttp-download-public-key='); + expect(output).not.to.match( + /xhttp-download-(skip-cert-verify|tls-cert-sha256|tls-pubkey-sha256)=/, + ); + }); + + it('requires TCP with TLS or REALITY for Loon VLESS Vision without encryption', function () { + const proxy = { + type: 'vless', + name: 'Vision', + server: 'example.com', + port: 443, + uuid: UUID, + flow: 'xtls-rprx-vision', + }; + for (const settings of [ + { network: 'ws', tls: true }, + { network: 'http', tls: true, encryption: 'none' }, + { network: 'xhttp', tls: true }, + { network: 'tcp', tls: false }, + { tls: 'false', flow: 'xtls-rprx-vision-udp443' }, + ]) { + const { result, errors } = captureErrors(() => + produceInternal('Loon', { ...proxy, ...settings }), + ); + expect(result).to.be.empty; + expect(errors[0]).to.include('requires TCP with TLS or REALITY'); + } + + for (const settings of [ + { network: 'tcp', tls: true }, + { 'reality-opts': { 'public-key': 'A'.repeat(43) } }, + ]) { + expect( + produceExternal('Loon', { ...proxy, ...settings }), + ).to.include(',flow=xtls-rprx-vision'); + } + }); + + it('rejects incomplete REALITY in the Loon VLESS Vision producer', function () { + const { produce } = Loon_Producer(); + const proxy = { + type: 'vless', + name: 'Vision', + server: 'example.com', + port: 443, + uuid: UUID, + network: 'tcp', + tls: false, + flow: 'xtls-rprx-vision', + }; + for (const reality of [ + { 'short-id': '08' }, + { 'public-key': '' }, + { 'public-key': ' \t ' }, + ]) { + expect(() => + produce({ ...proxy, 'reality-opts': reality }, 'external'), + ).to.throw('Loon VLESS REALITY requires a non-blank public-key'); + } + }); + + it('converts Loon VLESS Encryption and Vision through VLESS links', function () { + const keys = `${'A'.repeat(43)}.${'B'.repeat(43)}`; + const padding = '100-128-128.75-0-111.50-0-3333'; + for (const [network, mode, rtt] of [ + ['tcp', 'native'], + ['ws', 'xorpub', '1rtt'], + ['http', 'random', '0rtt'], + ['xhttp', 'native', '1rtt'], + ]) { + const flow = 'xtls-rprx-vision-udp443'; + const rttOption = rtt ? `,encryption-rtt=${rtt}` : ''; + const expectedRtt = rtt ?? '0rtt'; + const [proxy] = ProxyUtils.parse( + `Encrypted=vless,example.com,443,"${UUID}",transport=${network},flow=${flow},encryption-mode=${mode},encryption-public-keys="${keys}",encryption-padding=${padding}${rttOption}`, + ); + const encryption = `mlkem768x25519plus.${mode}.${expectedRtt}.${padding}.${keys}`; + expect(proxy).to.include({ network, encryption, flow }); + + const uri = produceExternal('URI', proxy); + const output = produceExternal('Loon', ProxyUtils.parse(uri)); + expect(output).to.include(`,encryption-mode=${mode}`); + expect(output).to.include(`,encryption-rtt=${expectedRtt}`); + expect(output).to.include(`,encryption-public-keys="${keys}"`); + expect(output).to.include(`,encryption-padding=${padding}`); + expect(ProxyUtils.parse(output)[0]).to.include({ + network, + encryption, + flow, + }); + } + }); + + it('validates Loon VLESS Encryption padding probabilities and ranges', function () { + const key = 'A'.repeat(43); + const input = `Encrypted=vless,example.com,443,"${UUID}",transport=tcp,encryption-mode=native,encryption-public-keys="${key}"`; + for (const [padding, reason] of [ + ['100-1-1', 'lengths of at least 35'], + ['99-35-35', 'first group requires probability 100'], + ['100-35-34', 'lengths of at least 35'], + ['100--1-35', 'lengths of at least 35'], + ['100-36-35', 'ordered non-negative integer bounds'], + ['100-35-35.50-5-1', 'ordered non-negative integer bounds'], + ['100-35-35.50--1-1', 'ordered non-negative integer bounds'], + ['100-35-35.101-0-1', 'probabilities from 0 to 100'], + ]) { + const proxies = ProxyUtils.parse( + `${input},encryption-padding=${padding}`, + ); + expect(proxies).to.have.length(1); + const { result, errors } = captureErrors(() => + produceInternal('Loon', proxies), + ); + expect(result, padding).to.be.empty; + expect(errors[0]).to.include(reason); + } + + for (const padding of ['100-35-35', '100-35-36.75-0-1.50-0-0']) { + const proxies = ProxyUtils.parse( + `${input},encryption-padding=${padding}`, + ); + expect(produceExternal('Loon', proxies)).to.include( + `,encryption-padding=${padding}`, + ); + } + }); + + it('round-trips Loon Mieru TCP nodes with quoted credentials', function () { + const input = + 'Mieru=mieru,[2001:db8::1],8443," user,name "," pass,word ",udp=true,block-quic=false,ip-mode=prefer-v4,server-dns="system,2001:db8::53"'; + const [proxy] = ProxyUtils.parse(input); + expectSubset(proxy, { + type: 'mieru', + server: '2001:db8::1', + port: 8443, + transport: 'TCP', + username: ' user,name ', + password: ' pass,word ', + udp: true, + 'block-quic': 'off', + 'ip-version': 'prefer-v4', + 'server-dns': ['system', '2001:db8::53'], + }); + expect(produceExternal('Loon', proxy)).to.equal(input); + const [plain] = ProxyUtils.parse( + 'Plain=mieru,example.com,8443,"user","pass"', + ); + expect(plain.udp).to.be.false; + const uri = 'mierus://user:pass@example.com?port=8443&protocol=TCP#URI'; + expect(produceExternal('Loon', ProxyUtils.parse(uri))).to.equal( + 'URI=mieru,example.com,8443,"user","pass",udp=true', + ); + }); + + it('requires and trims the server address for Loon Mieru', function () { + const proxy = { + type: 'mieru', + name: 'Mieru', + port: 8443, + username: 'user', + password: 'pass', + }; + for (const server of ['', ' ', '\t ']) { + const { result, errors } = captureErrors(() => + produceInternal('Loon', { ...proxy, server }), + ); + expect(result).to.be.empty; + expect(errors[0]).to.include('Loon Mieru requires a server'); + } + + for (const [server, address] of [ + [' example.com ', 'example.com'], + [' 2001:db8::1 ', '[2001:db8::1]'], + ]) { + expect(produceExternal('Loon', { ...proxy, server })).to.equal( + `Mieru=mieru,${address},8443,"user","pass"`, + ); + } + }); + + it('validates Loon Mieru port and UTF-8 credential ranges', function () { + const proxy = { + type: 'mieru', + name: 'Mieru', + server: 'example.com', + port: 1, + username: '密'.repeat(21) + 'a', + password: '🔒'.repeat(16), + }; + for (const port of [1, '65535']) { + expect(produceExternal('Loon', { ...proxy, port })).to.include( + `,${port},"${proxy.username}","${proxy.password}"`, + ); + } + + for (const settings of [ + { port: 0 }, + { port: 65536 }, + { port: 443.5 }, + { port: '0x1bb' }, + { username: '' }, + { password: '' }, + { username: '密'.repeat(22) }, + { password: 'a'.repeat(65) }, + ]) { + const { result, errors } = captureErrors(() => + produceInternal('Loon', { ...proxy, ...settings }), + ); + expect(result).to.be.empty; + expect(errors[0]).to.include( + 'port' in settings ? 'from 1 to 65535' : '1-64 UTF-8 bytes', + ); + } + }); + 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; @@ -967,7 +1499,8 @@ describe('Proxy text producers', function () { ); }); - it('produces Loon VLESS reality websocket lines', function () { + it('produces Loon VLESS reality websocket lines with encryption and Vision', function () { + const publicKey = 'A'.repeat(43); const output = produceExternal('Loon', { type: 'vless', name: 'Loon Reality', @@ -977,6 +1510,7 @@ describe('Proxy text producers', function () { tls: true, sni: 'sni.example.com', flow: 'xtls-rprx-vision', + encryption: `mlkem768x25519plus.native.1rtt.${publicKey}`, network: 'ws', 'ws-opts': { path: '/ws', @@ -992,7 +1526,7 @@ describe('Proxy text producers', function () { }); expect(output).to.equal( - `Loon Reality=vless,vless.example.com,443,"${UUID}",transport=ws,path=/ws,host=cdn.example.com,over-tls=true,skip-cert-verify=true,flow=xtls-rprx-vision,sni=sni.example.com,public-key="pubkey",short-id=08`, + `Loon Reality=vless,vless.example.com,443,"${UUID}",transport=ws,path=/ws,host=cdn.example.com,over-tls=true,skip-cert-verify=true,encryption-mode=native,encryption-rtt=1rtt,encryption-public-keys="${publicKey}",flow=xtls-rprx-vision,sni=sni.example.com,public-key="pubkey",short-id=08`, ); }); @@ -1227,6 +1761,7 @@ describe('Proxy text producers', function () { server: 'vless-xtls.example.com', port: 443, uuid: UUID, + tls: true, flow: 'xtls-rprx-vision', sni: 'sni.example.com', 'client-fingerprint': 'chrome',