From cf8c0bb908f57487449979e1dc7d91442bb9d89e Mon Sep 17 00:00:00 2001 From: xream Date: Sun, 29 Nov 2026 00:59:29 +0800 Subject: [PATCH] feat: Loon mieru traffic-pattern, Hysteria 2 Gecko --- backend/package.json | 2 +- .../core/proxy-utils/mieru-traffic-pattern.js | 103 ++++++++++++ backend/src/core/proxy-utils/parsers/index.js | 5 +- .../core/proxy-utils/parsers/peggy/loon.js | 37 ++++- .../src/core/proxy-utils/producers/loon.js | 28 +++- backend/src/test/proxy-producers/text.spec.js | 150 +++++++++++++++++- 6 files changed, 310 insertions(+), 15 deletions(-) create mode 100644 backend/src/core/proxy-utils/mieru-traffic-pattern.js diff --git a/backend/package.json b/backend/package.json index f951c1ed..1f070675 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.44.32", + "version": "2.44.33", "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/mieru-traffic-pattern.js b/backend/src/core/proxy-utils/mieru-traffic-pattern.js new file mode 100644 index 00000000..5d29108a --- /dev/null +++ b/backend/src/core/proxy-utils/mieru-traffic-pattern.js @@ -0,0 +1,103 @@ +import { Buffer } from 'buffer'; + +// https://github.com/enfein/mieru/blob/v3.39.0/pkg/appctl/proto/base.proto#L133 +const twoVarintFields = { 1: 'varint', 2: 'varint' }; +const trafficPatternFields = { + ...twoVarintFields, + 3: twoVarintFields, // TCPFragment + 4: { ...twoVarintFields, 3: 'varint', 4: 'varint', 5: 'string' }, // NoncePattern + 5: twoVarintFields, // PaddingPattern + 6: twoVarintFields, // LowEntropyPattern +}; + +function invalidProtobuf(detail) { + return new Error(`Invalid Loon Mieru traffic-pattern Protobuf: ${detail}`); +} + +function validateMessage(bytes, fields) { + let offset = 0; + const groups = []; + + function readVarint() { + // Tags and lengths are bounded before use. Scalar values are skipped. + let value = 0; + for (let index = 0; index < 10 && offset < bytes.length; index++) { + const byte = bytes[offset++]; + if (index === 9 && byte > 1) break; + value += (byte & 0x7f) * 2 ** (index * 7); + if (byte < 0x80) return value; + } + throw invalidProtobuf('truncated or overflowing varint'); + } + + while (offset < bytes.length) { + const tag = readVarint(); + if (tag < 8 || tag > 0xffffffff) { + throw invalidProtobuf('invalid field number'); + } + const fieldNumber = tag >>> 3; + const wireType = tag & 7; + const field = groups.length ? undefined : fields[fieldNumber]; + if (field !== undefined && wireType !== (field === 'varint' ? 0 : 2)) { + throw invalidProtobuf( + `unexpected wire type for field ${fieldNumber}`, + ); + } + + switch (wireType) { + case 0: + readVarint(); + break; + case 1: + offset += 8; + break; + case 2: { + const length = readVarint(); + const end = offset + length; + if (end > bytes.length) { + throw invalidProtobuf('truncated length-delimited field'); + } + if (field !== undefined) { + const value = bytes.subarray(offset, end); + if (field === 'string') { + const text = value.toString('utf8'); + if (!value.equals(Buffer.from(text, 'utf8'))) { + throw invalidProtobuf('invalid UTF-8 string'); + } + } else { + validateMessage(value, field); + } + } + offset = end; + break; + } + case 3: + groups.push(fieldNumber); + break; + case 4: + if (groups.pop() !== fieldNumber) { + throw invalidProtobuf('mismatched end group'); + } + break; + case 5: + offset += 4; + break; + default: + throw invalidProtobuf('invalid wire type'); + } + if (offset > bytes.length) { + throw invalidProtobuf('truncated fixed-width field'); + } + } + + if (groups.length) throw invalidProtobuf('unterminated group'); +} + +export function validateMieruTrafficPattern(value) { + const bytes = + typeof value === 'string' ? Buffer.from(value, 'base64') : undefined; + if (!bytes || bytes.toString('base64') !== value) { + throw new Error('Loon Mieru traffic-pattern must be standard Base64'); + } + validateMessage(bytes, trafficPatternFields); +} diff --git a/backend/src/core/proxy-utils/parsers/index.js b/backend/src/core/proxy-utils/parsers/index.js index ebe34705..b4cc0a67 100644 --- a/backend/src/core/proxy-utils/parsers/index.js +++ b/backend/src/core/proxy-utils/parsers/index.js @@ -3187,7 +3187,10 @@ function Surge_WireGuard() { function Surge_Hysteria2() { const name = 'Surge Hysteria2 Parser'; const test = (line) => { - return /^.*=\s*hysteria2/.test(line.split(',')[0]); + return ( + /^.*=\s*hysteria2/.test(line.split(',')[0]) && + !/^[^=,]*=\s*hysteria2\s*,[^,]*,[^,]*,\s*"/.test(line) + ); }; const parse = (line) => getSurgeParser().parse(line); return { name, test, parse }; diff --git a/backend/src/core/proxy-utils/parsers/peggy/loon.js b/backend/src/core/proxy-utils/parsers/peggy/loon.js index 16f92c38..8620af54 100644 --- a/backend/src/core/proxy-utils/parsers/peggy/loon.js +++ b/backend/src/core/proxy-utils/parsers/peggy/loon.js @@ -1,3 +1,4 @@ +import { Buffer } from 'buffer'; import peggy from 'peggy'; import { setLoonXhttpOption } from '../../loon-xhttp'; @@ -135,7 +136,7 @@ anytls = tag equals "anytls"i address password (transport/transport_host/transpo proxy.type = "anytls"; handleTransport(); } -hysteria2 = tag equals "hysteria2"i address password (tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/tls_profile/alpn/udp_relay/fast_open/download_bandwidth/server_ports/hop_interval/salamander_password/ecn/ip_mode/block_quic/others)* { +hysteria2 = tag equals "hysteria2"i address password (tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/tls_profile/alpn/udp_relay/fast_open/download_bandwidth/server_ports/hop_interval/hysteria2_obfs_password/ecn/ip_mode/block_quic/others)* { proxy.type = "hysteria2"; } https = tag equals "https"i address (username password)? (tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/tls_profile/alpn/fast_open/udp_relay/ip_mode/block_quic/others)* { @@ -162,7 +163,7 @@ 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)* { +mieru = tag equals "mieru"i address comma user:option_value comma pass:option_value (udp_relay/ip_mode/block_quic/mieru_traffic_pattern/others)* { proxy.type = "mieru"; proxy.transport = "TCP"; proxy.username = user; @@ -320,7 +321,18 @@ ecn = comma "ecn" equals flag:bool { proxy.ecn = flag; } download_bandwidth = comma "download-bandwidth" equals match:[^,]+ { proxy.down = match.join(""); } server_ports = comma "server-ports" equals '"' match:$[^"]+ '"' { proxy.ports = match.trim().replace(/\s*-\s*/g, "-").replace(/\s*,\s*/g, ","); } hop_interval = comma "hop-interval" equals match:$[0-9]+ { proxy["hop-interval"] = parseInt(match, 10); } -salamander_password = comma "salamander-password" equals match:[^,]+ { proxy['obfs-password'] = match.join(""); proxy.obfs = 'salamander'; } +hysteria2_obfs_password = comma key:("gecko-password-base64"/"gecko-password"/"salamander-password") equals value:option_value { + if (obfs.passwordKey && obfs.passwordKey !== key) { + throw new Error("Loon Hysteria 2 obfuscation password options are mutually exclusive"); + } + obfs.passwordKey = key; + proxy.obfs = key === "salamander-password" ? "salamander" : "gecko"; + proxy["obfs-password"] = key === "gecko-password-base64" ? options.decodeGeckoPassword(value) : value; +} + +mieru_traffic_pattern = comma "traffic-pattern" equals value:option_value { + if (value) proxy["traffic-pattern"] = value; +} block_quic = comma "block-quic" equals flag:bool { if(flag) proxy["block-quic"] = "on"; else proxy["block-quic"] = "off"; } @@ -347,12 +359,29 @@ _ = [ \r\t]* bool = b:("true"/"false") { return b === "true" } others = server_dns / (comma [^=,]+ equals [^=,]+) `; + +function decodeGeckoPassword(value) { + const bytes = Buffer.from(value, 'base64'); + const password = bytes.toString('utf8'); + if ( + bytes.toString('base64') !== value || + !bytes.equals(Buffer.from(password, 'utf8')) + ) { + throw new Error('Invalid Loon Hysteria 2 gecko-password-base64'); + } + return password; +} + let parser; export default function getParser() { if (!parser) { const generated = peggy.generate(grammars); parser = { - parse: (input) => generated.parse(input, { setLoonXhttpOption }), + parse: (input) => + generated.parse(input, { + setLoonXhttpOption, + decodeGeckoPassword, + }), }; } return parser; diff --git a/backend/src/core/proxy-utils/producers/loon.js b/backend/src/core/proxy-utils/producers/loon.js index ec1e01eb..2052d88f 100644 --- a/backend/src/core/proxy-utils/producers/loon.js +++ b/backend/src/core/proxy-utils/producers/loon.js @@ -6,6 +6,7 @@ import { isPresent, Result } from './utils'; import { getIfNotBlank, isIPv4, isIPv6, isPlainObject } from '@/utils'; import $ from '@/core/app'; import { LOON_XHTTP_FIELDS, validateLoonXhttpXmux } from '../loon-xhttp'; +import { validateMieruTrafficPattern } from '../mieru-traffic-pattern'; import { formatLoonVmessSecurity } from '../vmess-security'; import { normalizeXhttpIntegerValue } from '../xhttp-utils'; @@ -1120,14 +1121,26 @@ function mieru(proxy) { `,block-quic=${blockQuic === 'on' || blockQuic === true}`, ); } + const trafficPattern = proxy['traffic-pattern']; + if (trafficPattern != null && trafficPattern !== '') { + validateMieruTrafficPattern(trafficPattern); + result.append(`,traffic-pattern=${trafficPattern}`); + } 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`); + const obfs = proxy.obfs; + const obfsPassword = proxy['obfs-password']; + if (obfs === 'gecko' && !obfsPassword) { + throw new Error('Loon Hysteria 2 Gecko requires obfs-password'); + } + if (obfsPassword && !['salamander', 'gecko'].includes(obfs)) { + throw new Error( + 'Loon Hysteria 2 only supports Salamander and Gecko obfuscation', + ); } const result = new Result(proxy); result.append(`${proxy.name}=Hysteria2,${proxy.server},${proxy.port}`); @@ -1162,8 +1175,15 @@ function hysteria2(proxy) { appendTlsProfile(result, proxy); appendAlpn(result, proxy); - if (proxy['obfs-password'] && proxy.obfs == 'salamander') { - result.append(`,salamander-password=${proxy['obfs-password']}`); + if (obfsPassword) { + const password = String(obfsPassword); + if (obfs === 'gecko' && /["\p{Cc}\u2028\u2029]/u.test(password)) { + const encoded = Buffer.from(password, 'utf8').toString('base64'); + result.append(`,gecko-password-base64=${encoded}`); + } else { + const formatted = formatLoonValue(password, obfs === 'gecko'); + result.append(`,${obfs}-password=${formatted}`); + } } // tfo diff --git a/backend/src/test/proxy-producers/text.spec.js b/backend/src/test/proxy-producers/text.spec.js index f28335ca..683bde4b 100644 --- a/backend/src/test/proxy-producers/text.spec.js +++ b/backend/src/test/proxy-producers/text.spec.js @@ -1583,9 +1583,9 @@ describe('Proxy text producers', function () { } }); - 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"'; + it('round-trips Loon Mieru credentials and traffic patterns', function () { + const trafficPattern = 'CI+/AQ=='; + const input = `Mieru=mieru,[2001:db8::1],8443," user,name "," pass,word ",udp=true,block-quic=false,traffic-pattern=${trafficPattern},ip-mode=prefer-v4,server-dns="system,2001:db8::53"`; const [proxy] = ProxyUtils.parse(input); expectSubset(proxy, { type: 'mieru', @@ -1596,6 +1596,7 @@ describe('Proxy text producers', function () { password: ' pass,word ', udp: true, 'block-quic': 'off', + 'traffic-pattern': trafficPattern, 'ip-version': 'prefer-v4', 'server-dns': ['system', '2001:db8::53'], }); @@ -1604,9 +1605,83 @@ describe('Proxy text producers', function () { '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', plain)).to.equal( + 'Plain=mieru,example.com,8443,"user","pass"', + ); + const uri = `mierus://user:pass@example.com?port=8443&protocol=TCP&traffic-pattern=${encodeURIComponent( + trafficPattern, + )}#URI`; expect(produceExternal('Loon', ProxyUtils.parse(uri))).to.equal( - 'URI=mieru,example.com,8443,"user","pass",udp=true', + `URI=mieru,example.com,8443,"user","pass",udp=true,traffic-pattern=${trafficPattern}`, + ); + }); + + it('rejects invalid Loon Mieru traffic-pattern encodings', function () { + const [proxy] = ProxyUtils.parse( + 'Mieru=mieru,example.com,8443,"user","pass"', + ); + for (const trafficPattern of [ + 'not-base64', + 'CI-_AQ==', + 'CI+/AQ', + 'CI+/AR==', + 'CI+/ AQ==', + 42, + ]) { + const { result, errors } = captureErrors(() => + produceInternal('Loon', { + ...proxy, + 'traffic-pattern': trafficPattern, + }), + ); + expect(result, String(trafficPattern)).to.be.empty; + expect(errors[0]).to.include( + 'traffic-pattern must be standard Base64', + ); + } + }); + + it('rejects malformed Protobuf in Loon Mieru traffic patterns', function () { + const input = 'Mieru=mieru,example.com,8443,"user","pass"'; + for (const [reason, bytes] of [ + ['zero field number', [0, 0, 0]], + ['truncated seed', [0x08, 0x80]], + ['overflowing seed', [0x08, ...Array(9).fill(0xff), 0x02]], + ['wrong wire type for TCPFragment', [0x18, 0x01]], + ['truncated TCPFragment', [0x1a, 0x02, 0x08]], + ['invalid tag inside TCPFragment', [0x1a, 0x01, 0x00]], + ['invalid UTF-8 in NoncePattern', [0x22, 0x03, 0x2a, 0x01, 0xff]], + ['truncated unknown fixed32 field', [0x3d, 0x01]], + ['mismatched unknown group', [0x3b, 0x44]], + ]) { + const trafficPattern = Base64.fromUint8Array( + Uint8Array.from(bytes), + ); + const proxies = ProxyUtils.parse( + `${input},traffic-pattern=${trafficPattern}`, + ); + expect(proxies, reason).to.have.length(1); + const { result, errors } = captureErrors(() => + produceInternal('Loon', proxies), + ); + expect(result, reason).to.be.empty; + expect(errors[0], reason).to.include( + 'Loon Mieru traffic-pattern Protobuf', + ); + } + }); + + it('preserves nested Mieru traffic patterns and unknown Protobuf fields', function () { + const bytes = Base64.toUint8Array( + 'CCoQARoECAEQAyIKCAMqBjBjYjFmZioECAwQGDIECAEQcA==', + ); + // Field 7 is length-delimited and may carry arbitrary bytes. + const trafficPattern = Base64.fromUint8Array( + Uint8Array.of(...bytes, 0x3a, 0x01, 0xff), + ); + const input = `Mieru=mieru,example.com,8443,"user","pass",traffic-pattern=${trafficPattern}`; + expect(produceExternal('Loon', ProxyUtils.parse(input))).to.equal( + input, ); }); @@ -2209,6 +2284,71 @@ describe('Proxy text producers', function () { expect(output).to.not.include('alpn='); }); + it('round-trips Loon Hysteria 2 Gecko and Salamander passwords', function () { + const password = ' key,with=comma '; + for (const obfs of ['gecko', 'salamander']) { + const options = `${obfs}-password="${password}",udp=true`; + const [proxy] = ProxyUtils.parse( + `Hy2=hysteria2,hy2.example.com,443,"auth=secret",sni=peer.example.com,${options}`, + ); + expectSubset(proxy, { + password: 'auth=secret', + obfs, + 'obfs-password': password, + }); + const output = produceExternal('Loon', proxy); + expect(output).to.equal( + `Hy2=Hysteria2,hy2.example.com,443,"auth=secret",tls-name=peer.example.com,${options}`, + ); + expect(ProxyUtils.parse(output)).to.deep.equal([proxy]); + } + }); + + it('round-trips Loon Hysteria 2 Gecko passwords that require Base64', function () { + for (const [scheme, password] of [ + ['hy2', ' 密,"码" '], + ['hysteria2', 'control\tchars\n\u0000'], + ]) { + const uri = `${scheme}://secret@hy2.example.com:443/?obfs=gecko&obfs-password=${encodeURIComponent( + password, + )}#Hy2`; + const output = produceExternal('Loon', ProxyUtils.parse(uri)); + expect(output).to.include( + `,gecko-password-base64=${Base64.encode(password)}`, + ); + expect(output).not.to.include(',gecko-password='); + expectSubset(ProxyUtils.parse(output)[0], { + password: 'secret', + obfs: 'gecko', + 'obfs-password': password, + }); + } + }); + + it('rejects invalid or conflicting Loon Hysteria 2 obfuscation passwords', function () { + const input = 'Hy2=hysteria2,hy2.example.com,443,"auth=secret"'; + for (const options of [ + 'gecko-password=', + 'gecko-password-base64=%%%', + 'gecko-password-base64=/w==', + 'gecko-password=mask,salamander-password=mask', + 'salamander-password=mask,gecko-password=mask', + 'gecko-password=mask,gecko-password-base64=bWFzaw==', + 'gecko-password-base64=bWFzaw==,gecko-password=mask', + ]) { + const { result } = captureErrors(() => + ProxyUtils.parse(`${input},${options}`), + ); + expect(result, options).to.be.empty; + } + + const [proxy] = ProxyUtils.parse(input); + const { result } = captureErrors(() => + produceInternal('Loon', { ...proxy, obfs: 'gecko' }), + ); + expect(result).to.be.empty; + }); + it('produces Loon Hysteria2 lines with port hopping', function () { const output = produceExternal('Loon', { type: 'hysteria2',