feat: Loon XHTTP alpn 逻辑优化
build / build (push) Canceled after 0s

This commit is contained in:
xream committed 2026-12-03 21:12:49 +08:00
1 parent 11e52447e9
commit 838bf242e8
5 files changed
+167 -118

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "sub-store",
"version": "2.44.38",
"version": "2.44.39",
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.",
"main": "src/main.js",
"packageManager": "pnpm@11.0.9",
+44 -17
View File
@@ -72,29 +72,53 @@ export const LOON_XHTTP_FIELDS = {
),
};
function splitAlpn(value) {
return String(value ?? '')
.split(',')
.map((protocol) => protocol.trim())
.filter(Boolean);
}
export function getLoonXhttpAlpnSettings(endpoint, isDownload = false) {
const configured = splitAlpn(endpoint.alpn);
const protocols = configured.filter((protocol) =>
['http/1.1', 'h2', 'h3'].includes(protocol),
);
if (configured.length && !protocols.length) {
const field = isDownload ? 'xhttp-download-alpn' : 'XHTTP alpn';
throw new Error(`Loon ${field} must include http/1.1, h2 or h3`);
}
const singleProtocol = protocols.length === 1 ? protocols[0] : undefined;
if (isNotBlank(endpoint['reality-opts']?.['public-key'])) {
return { defaultAlpn: 'h2', priority: ['h2'] };
return { protocols, httpVersion: 'h2' };
}
if (
(!isDownload && endpoint.type === 'trojan') ||
[true, 'true'].includes(endpoint.tls)
) {
return { defaultAlpn: 'h2', priority: ['h3', 'h2', 'http/1.1'] };
return { protocols, httpVersion: singleProtocol ?? 'h2' };
}
return { defaultAlpn: 'http/1.1', priority: ['http/1.1'] };
if (!isDownload && singleProtocol === 'h3') {
throw new Error('Loon XHTTP upload with alpn=h3 requires TLS');
}
return { protocols, httpVersion: 'http/1.1' };
}
export function validateLoonXhttpXmux(opts) {
export function validateLoonXhttpXmux(opts, uploadVersion, downloadVersion) {
if (!opts) return;
for (const prefix of ['', 'download-']) {
const getOption = (key) =>
_.get(opts, LOON_XHTTP_FIELDS[`${prefix}${key}`]);
for (const [prefix, endpoint, httpVersion] of [
['', opts, uploadVersion],
['download-', opts['download-settings'], downloadVersion],
]) {
if (!endpoint) continue;
for (const key of Object.keys(XMUX_FIELDS)) {
const value = getOption(key);
let hasXmux = false;
for (const [key, path] of Object.entries(XMUX_FIELDS)) {
const value = _.get(endpoint, path);
if (value == null) continue;
hasXmux = true;
const isKeepalive = key === 'xmux-http-keepalive-secs';
const normalized = isKeepalive
@@ -110,15 +134,19 @@ export function validateLoonXhttpXmux(opts) {
}
}
const maxConcurrency = getOption('xmux-max-concurrency');
const maxConnections = getOption('xmux-max-connections');
if (httpVersion === 'h2') continue;
// An HTTP/3 download inherits the whole uplink XMUX group unless it sets its own.
const inheritsXmux =
prefix === 'download-' && httpVersion === 'h3' && !hasXmux;
const reuse = (inheritsXmux ? opts : endpoint)['reuse-settings'];
if (
normalizeXhttpPositiveRange(maxConcurrency) != null &&
normalizeXhttpPositiveRange(maxConnections) != null
normalizeXhttpPositiveRange(reuse?.['max-concurrency']) != null &&
normalizeXhttpPositiveRange(reuse?.['max-connections']) != null
) {
const optionPrefix = `xhttp-${prefix}xmux`;
const source = inheritsXmux ? ' (inherited from the upload)' : '';
throw new Error(
`Loon ${optionPrefix}-max-concurrency and ${optionPrefix}-max-connections cannot both be positive`,
`Loon ${optionPrefix}-max-concurrency and ${optionPrefix}-max-connections cannot both be positive for ${httpVersion}${source}`,
);
}
}
@@ -158,9 +186,8 @@ export function setLoonXhttpOption(opts, key, value) {
value = normalizeXhttpIntegerValue(value) ?? value;
break;
case 'alpn':
value = value.trim();
if (!value) return;
value = [value];
value = splitAlpn(value);
if (!value.length) return;
break;
}
_.set(opts, LOON_XHTTP_FIELDS[key], value);
@@ -28,6 +28,12 @@ const grammars = String.raw`
const shadowTLS = {};
const $ = {};
function setXhttpAlpn(endpoint, isDownload = false) {
const { protocols, httpVersion } = options.getLoonXhttpAlpnSettings(endpoint, isDownload);
// An explicit default keeps other formats from inheriting the upload ALPN.
endpoint.alpn = protocols.length ? protocols : [httpVersion];
}
function handleTransport() {
if (transport.type === "tcp") { /* do nothing */ }
else if (transport.type === "ws") {
@@ -62,13 +68,13 @@ const grammars = String.raw`
}
proxy.network = "xhttp";
proxy.udp ??= false;
proxy.alpn ??= [options.getLoonXhttpAlpnSettings(proxy).defaultAlpn];
setXhttpAlpn(proxy);
if (transport.path != null) xhttpOpts.path = transport.path;
if (transport.host != null) xhttpOpts.host = transport.host;
const download = xhttpOpts["download-settings"];
if (download) {
download.tls ??= Boolean(download["reality-opts"]?.["public-key"]);
download.alpn ??= [options.getLoonXhttpAlpnSettings(download, true).defaultAlpn];
setXhttpAlpn(download, true);
const fingerprint = loonClientFingerprint(download._loon_tls_profile);
if (fingerprint) download["client-fingerprint"] = fingerprint;
}
+15 -31
View File
@@ -88,8 +88,8 @@ function appendTlsProfile(result, proxy) {
if (tlsProfile) result.append(`,tls-profile=${tlsProfile}`);
}
function appendAlpn(result, proxy, isXhttp = false) {
const alpn = isXhttp ? getLoonXhttpAlpn(proxy) : getLoonAlpn(proxy);
function appendAlpn(result, proxy) {
const alpn = getLoonAlpn(proxy);
if (alpn) result.append(`,alpn="${alpn}"`);
}
@@ -124,7 +124,9 @@ function appendXhttp(result, proxy) {
if (download?.plugin || download?.['shadow-tls-opts']) {
throw new Error('Loon XHTTP download-settings do not support plugins');
}
validateLoonXhttpXmux(xhttp);
const { protocols, httpVersion } = getLoonXhttpAlpnSettings(proxy);
const downloadAlpn = download && getLoonXhttpAlpnSettings(download, true);
validateLoonXhttpXmux(xhttp, httpVersion, downloadAlpn?.httpVersion);
let options = xhttp;
if (download) {
@@ -156,8 +158,6 @@ function appendXhttp(result, proxy) {
);
}
const alpn = getLoonXhttpAlpn(download, true);
const fingerprint = download.fingerprint ?? download['tls-fingerprint'];
const pubkeyFingerprint = download['tls-pubkey-sha256'];
const skipCertVerify = download['skip-cert-verify'];
@@ -179,7 +179,7 @@ function appendXhttp(result, proxy) {
server: server.trim(),
port,
host: getXhttpHost(download),
alpn,
alpn: downloadAlpn.protocols.join(',') || undefined,
servername: download.servername ?? download.sni,
fingerprint: hasReality ? undefined : fingerprint,
'tls-pubkey-sha256': hasReality ? undefined : pubkeyFingerprint,
@@ -196,10 +196,12 @@ function appendXhttp(result, proxy) {
]) {
if (value != null) result.append(`,${key}=${formatLoonValue(value)}`);
}
if (protocols.length) result.append(`,alpn="${protocols.join(',')}"`);
for (const [key, field] of Object.entries(LOON_XHTTP_FIELDS)) {
const value = _.get(options, field);
if (value != null)
result.append(`,xhttp-${key}=${formatLoonValue(value)}`);
if (value == null) continue;
const formatted = formatLoonValue(value, key === 'download-alpn');
result.append(`,xhttp-${key}=${formatted}`);
}
for (const [option, headers] of [
['xhttp-header', xhttp?.headers],
@@ -279,24 +281,6 @@ function getLoonAlpn(proxy) {
.join(',');
}
function getLoonXhttpAlpn(endpoint, isDownload = false) {
const value = getLoonAlpn(endpoint);
if (!value) return;
const candidates = value.split(',').map((item) => item.trim());
const { priority } = getLoonXhttpAlpnSettings(endpoint, isDownload);
const alpn = priority.find((protocol) => candidates.includes(protocol));
if (!alpn) {
const field = isDownload ? 'xhttp-download-alpn' : 'XHTTP alpn';
throw new Error(
`Loon ${field} must be ${priority.join(
' or ',
)} for the configured security`,
);
}
return alpn;
}
function getLoonTlsProfile(proxy) {
const tlsProfile = `${proxy._loon_tls_profile || ''}`.trim();
if (
@@ -536,7 +520,7 @@ function trojan(proxy) {
'skip-cert-verify',
);
appendTlsProfile(result, proxy);
if (!isGrpc) appendAlpn(result, proxy, isXhttp);
if (!isGrpc && !isXhttp) appendAlpn(result, proxy);
if (isReality) {
appendReality(result, proxy);
@@ -695,8 +679,8 @@ function vmess(proxy) {
'skip-cert-verify',
);
if (proxy.tls || isReality) appendTlsProfile(result, proxy);
if (!isGrpc && (proxy.tls || isReality || isXhttp)) {
appendAlpn(result, proxy, isXhttp);
if (!isGrpc && !isXhttp && (proxy.tls || isReality)) {
appendAlpn(result, proxy);
}
if (isReality) {
@@ -869,8 +853,8 @@ function vless(proxy) {
'skip-cert-verify',
);
if (proxy.tls || isReality || isXtls) appendTlsProfile(result, proxy);
if (!isGrpc && (proxy.tls || isReality || isXtls || isXhttp)) {
appendAlpn(result, proxy, isXhttp);
if (!isGrpc && !isXhttp && (proxy.tls || isReality || isXtls)) {
appendAlpn(result, proxy);
}
appendVlessEncryption(result, proxy.encryption);
+99 -67
View File
@@ -1201,7 +1201,7 @@ describe('Proxy text producers', function () {
'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-alpn="h3, 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"',
@@ -1220,7 +1220,7 @@ describe('Proxy text producers', function () {
port: 8443,
host: 'cdn.example.com',
path: '/down?route=a,b',
alpn: ['h2'],
alpn: ['h3', 'h2'],
tls: true,
servername: 'peer.example.com',
'skip-cert-verify': false,
@@ -1245,6 +1245,8 @@ describe('Proxy text producers', function () {
},
});
const output = produceExternal('Loon', proxy);
expect(output).to.include(',alpn="h3"');
expect(output).to.include(',xhttp-download-alpn="h3,h2"');
expect(output).to.include(',xhttp-download-header="X-Trace: a,b"');
expect(ProxyUtils.parse(output)).to.deep.equal([proxy]);
@@ -1299,34 +1301,71 @@ describe('Proxy text producers', function () {
}
});
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'],
it('allows both Loon XHTTP XMUX quotas only for an endpoint using HTTP/2', function () {
const input = `Split=vless,upload.example.com,443,"${UUID}",transport=xhttp,xhttp-mode=stream-up`;
const split = `${input},xhttp-download-server=download.example.com,xhttp-download-port=8443`;
for (const [line, prefix] of [
[input, ''],
[split, 'xhttp-download-'],
]) {
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}`,
);
const xmux = prefix ? 'xhttp-download-xmux' : 'xhttp-xmux';
for (const [security, alpn, allowsBoth] of [
['', 'h2', false],
['over-tls=true', '', true],
['over-tls=true', 'http/1.1', false],
['over-tls=true', 'h2', true],
['over-tls=true', 'h3', false],
['over-tls=true', 'h3,http/1.1', true],
['over-tls=true', 'http/1.1,h3', true],
['public-key=key', 'h3', true],
]) {
const options = [
line,
security && prefix + security,
alpn && `${prefix}alpn="${alpn}"`,
`${xmux}-max-concurrency=0-8`,
`${xmux}-max-connections=3-4`,
]
.filter(Boolean)
.join(',');
const proxies = ProxyUtils.parse(options);
expect(proxies, options).to.have.length(1);
if (allowsBoth) {
const output = produceExternal('Loon', proxies);
expect(output).to.include(`,${xmux}-max-concurrency=0-8`);
expect(output).to.include(`,${xmux}-max-connections=3-4`);
} else {
const { result, errors } = captureErrors(() =>
produceInternal('Loon', proxies),
);
expect(result, options).to.be.empty;
expect(errors[0]).to.include(
`${xmux}-max-concurrency and ${xmux}-max-connections`,
);
const zero = ProxyUtils.parse(
options.replace('=0-8', '=0'),
);
expect(produceExternal('Loon', zero)).to.include(
`,${xmux}-max-connections=3-4`,
);
}
}
}
});
it('checks inherited XMUX quotas against the independent HTTP/3 download', function () {
const input = `Split=vless,upload.example.com,443,"${UUID}",transport=xhttp,over-tls=true,xhttp-mode=stream-up,xhttp-xmux-max-concurrency=8,xhttp-xmux-max-connections=3,xhttp-download-server=download.example.com,xhttp-download-port=443,xhttp-download-over-tls=true,xhttp-download-alpn=h3`;
const { result, errors } = captureErrors(() =>
produceInternal('Loon', ProxyUtils.parse(input)),
);
expect(result).to.be.empty;
expect(errors[0]).to.include('h3 (inherited from the upload)');
const ownQuota = ',xhttp-download-xmux-max-concurrency=0';
expect(
produceExternal('Loon', ProxyUtils.parse(input + ownQuota)),
).to.include(ownQuota);
});
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`;
@@ -1428,6 +1467,7 @@ describe('Proxy text producers', function () {
for (const [input, uploadAlpn, downloadAlpn] of [
[`${vless},xhttp-download-over-tls=true`, 'http/1.1', 'h2'],
[`${vless},over-tls=true`, 'h2', 'http/1.1'],
[`${trojan},alpn=h3,xhttp-download-over-tls=true`, 'h3', 'h2'],
[
`${vless},public-key=up-key,xhttp-download-public-key=down-key`,
'h2',
@@ -1446,7 +1486,7 @@ describe('Proxy text producers', function () {
}
});
it('selects Loon XHTTP main ALPN by security', function () {
it('preserves the configured Loon XHTTP main ALPN list', function () {
const proxy = {
type: 'vless',
name: 'Main',
@@ -1458,16 +1498,9 @@ describe('Proxy text producers', function () {
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: false, alpn: ['h3', 'h2'] }, 'XHTTP alpn must be http/1.1'],
[{ ...reality, alpn: ['http/1.1', 'h3'] }, 'XHTTP alpn must be h2'],
[
{ tls: true, alpn: ['h4', 'unknown'] },
'XHTTP alpn must be h3 or h2 or http/1.1',
],
[{ tls: false, alpn: ['h3'] }, 'h3 requires TLS'],
[{ type: 'vmess', alpn: ['h3'] }, 'h3 requires TLS'],
[{ tls: true, alpn: ['h4', 'unknown'] }, 'XHTTP alpn must include'],
]) {
const { result, errors } = captureErrors(() =>
produceInternal('Loon', { ...proxy, ...settings }),
@@ -1480,16 +1513,22 @@ describe('Proxy text producers', function () {
produceExternal('Loon', { ...proxy, tls: false }),
).not.to.include(',alpn=');
for (const [settings, alpn] of [
[{ tls: false, alpn: ['h3', 'http/1.1'] }, 'http/1.1'],
[{ tls: true, alpn: ['http/1.1', 'h2', 'h3'] }, 'h3'],
[{ tls: true, alpn: 'http/1.1, h2, unknown' }, 'h2'],
[{ ...reality, tls: true, alpn: ['h3', 'h2'] }, 'h2'],
[{ ...trojan, alpn: ['h2', 'h3'] }, 'h3'],
[{ tls: false, alpn: ['h2'] }, 'h2'],
[{ tls: false, alpn: ['h3', 'http/1.1'] }, 'h3,http/1.1'],
[{ tls: true, alpn: ['http/1.1', 'h2', 'h3'] }, 'http/1.1,h2,h3'],
[{ tls: true, alpn: 'http/1.1, h2, unknown' }, 'http/1.1,h2'],
[{ ...reality, tls: true, alpn: ['h3', 'h2'] }, 'h3,h2'],
[{ ...trojan, ...reality, alpn: ['h3'] }, 'h3'],
[{ ...trojan, alpn: ['h2', 'h3'] }, 'h2,h3'],
]) {
expect(
produceExternal('Loon', { ...proxy, ...settings }),
).to.include(`,alpn="${alpn}"`);
const output = produceExternal('Loon', { ...proxy, ...settings });
expect(output).to.include(`,alpn="${alpn}"`);
expect(ProxyUtils.parse(output)[0].alpn).to.deep.equal(
alpn.split(','),
);
}
const plain = `Main=vless,example.com,80,"${UUID}",transport=xhttp,alpn=h3`;
expect(captureErrors(() => ProxyUtils.parse(plain)).result).to.be.empty;
});
it('rejects incomplete REALITY for Loon XHTTP downloads', function () {
@@ -1537,24 +1576,13 @@ describe('Proxy text producers', function () {
for (const [settings, reason] of [
[{ ...reality, tls: false }, realityConflict],
[{ ...reality, tls: 'false' }, realityConflict],
[{ alpn: ['h2', 'h3'] }, 'xhttp-download-alpn must be http/1.1'],
[{ 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'],
[
{ ...reality, alpn: ['h3', 'http/1.1'] },
'xhttp-download-alpn must be h2',
],
[
{ tls: true, alpn: ['unknown'] },
'xhttp-download-alpn must be h3 or h2 or http/1.1',
'xhttp-download-alpn must include',
],
[
{ tls: true, alpn: ['h4', 'unknown'] },
'xhttp-download-alpn must be h3 or h2 or http/1.1',
'xhttp-download-alpn must include',
],
[{ ...reality, 'skip-cert-verify': true }, certificateConflict],
[{ ...reality, 'skip-cert-verify': 'true' }, certificateConflict],
@@ -1577,17 +1605,21 @@ describe('Proxy text producers', function () {
for (const [settings, alpn] of [
[{ alpn: ['http/1.1'] }, 'http/1.1'],
[{ alpn: ['h2', 'http/1.1'] }, 'http/1.1'],
[{ alpn: ['h2, http/1.1'] }, 'http/1.1'],
[{ alpn: 'h2, http/1.1' }, 'http/1.1'],
[{ tls: false, alpn: ['h3'] }, 'h3'],
[{ alpn: ['h2', 'http/1.1'] }, 'h2,http/1.1'],
[{ alpn: ['h2, http/1.1'] }, 'h2,http/1.1'],
[{ alpn: 'h2, http/1.1' }, 'h2,http/1.1'],
[{ tls: true, alpn: ['http/1.1'] }, 'http/1.1'],
[{ tls: true, alpn: ['http/1.1', 'h2'] }, 'h2'],
[{ tls: 'true', alpn: ['http/1.1', 'h2', 'h3'] }, 'h3'],
[{ ...reality, alpn: ['h3', 'h2'] }, 'h2'],
[{ tls: true, alpn: ['http/1.1', 'h2'] }, 'http/1.1,h2'],
[{ tls: 'true', alpn: ['http/1.1', 'h2', 'h3'] }, 'http/1.1,h2,h3'],
[{ ...reality, alpn: ['h3', 'h2'] }, 'h3,h2'],
]) {
expect(produceExternal('Loon', makeProxy(settings))).to.include(
`,xhttp-download-alpn=${alpn}`,
);
const output = produceExternal('Loon', makeProxy(settings));
expect(output).to.include(`,xhttp-download-alpn="${alpn}"`);
const [parsed] = ProxyUtils.parse(output);
expect(
parsed['xhttp-opts']['download-settings'].alpn,
).to.deep.equal(alpn.split(','));
}
for (const settings of [{}, { tls: true }, reality]) {