From 6f162d03a16b66b24540ec8acdb916175994de26 Mon Sep 17 00:00:00 2001 From: Gleb Kochergin <12710451+k-g-a@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:34:55 +0500 Subject: [PATCH] feat(xhttp): configure a separate download endpoint and preserve it in subscriptions (#7187) An operator who wanted XHTTP downloads to go through another endpoint, such as a relay or a CDN, had no field for it, and downloadSettings typed into the advanced JSON editor was dropped the next time the inbound was saved (#6307). Add a separate-download switch to the inbound and outbound XHTTP forms, keep the download stream through save, share links, JSON and Clash output, and validate it before it is stored: transport, address, port, REALITY key and short id, and a uTLS fingerprint the core accepts. Saving an inbound re-applies its own session, sequence and padding rules to the download leg, since the listener checks the download request against them. --- docs/content/docs/en/config/transports.mdx | 6 + docs/content/docs/fa/config/transports.mdx | 6 + docs/content/docs/ru/config/transports.mdx | 7 + docs/content/docs/zh/config/transports.mdx | 5 + .../forms/transport/XhttpDownloadForm.tsx | 155 ++++++++++++++++++ frontend/src/lib/xray/inbound-form-adapter.ts | 5 +- frontend/src/lib/xray/inbound-link.ts | 14 ++ .../src/lib/xray/outbound-form-adapter.ts | 8 +- frontend/src/lib/xray/outbound-link-parser.ts | 8 +- .../src/lib/xray/stream-wire-normalize.ts | 10 +- .../pages/inbounds/form/advanced-editors.tsx | 16 +- .../pages/inbounds/form/transport/xhttp.tsx | 50 ++++-- .../xray/outbounds/OutboundFormModal.tsx | 11 +- .../pages/xray/outbounds/transport/xhttp.tsx | 40 +++-- frontend/src/schemas/forms/inbound-form.ts | 47 +++++- .../src/schemas/protocols/stream/xhttp.ts | 111 ++++++++----- .../inbound-form-blocks.test.tsx.snap | 1 + .../test/__snapshots__/stream.test.ts.snap | 1 - .../src/test/advanced-all-editor.test.tsx | 50 +++++- .../src/test/inbound-form-adapter.test.ts | 114 ++++++++++++- frontend/src/test/inbound-link.test.ts | 31 ++++ .../src/test/outbound-form-adapter.test.ts | 13 +- .../src/test/stream-wire-normalize.test.ts | 5 +- frontend/src/test/stream.test.ts | 9 + .../src/test/xhttp-download-form.test.tsx | 100 +++++++++++ internal/database/model/model.go | 29 +++- internal/sub/clash_service.go | 76 ++++++++- internal/sub/clash_service_test.go | 37 ++++- internal/sub/json_service.go | 4 +- internal/sub/service.go | 1 + internal/web/service/inbound.go | 4 + internal/web/service/inbound_xhttp.go | 155 ++++++++++++++++++ internal/web/service/inbound_xhttp_test.go | 59 +++++++ internal/web/translation/ar-EG.json | 1 + internal/web/translation/en-US.json | 1 + internal/web/translation/es-ES.json | 1 + internal/web/translation/fa-IR.json | 1 + internal/web/translation/id-ID.json | 1 + internal/web/translation/ja-JP.json | 1 + internal/web/translation/pt-BR.json | 1 + internal/web/translation/ru-RU.json | 1 + internal/web/translation/sk-SK.json | 1 + internal/web/translation/tr-TR.json | 1 + internal/web/translation/uk-UA.json | 1 + internal/web/translation/vi-VN.json | 1 + internal/web/translation/zh-CN.json | 1 + internal/web/translation/zh-TW.json | 1 + 47 files changed, 1081 insertions(+), 121 deletions(-) create mode 100644 frontend/src/lib/xray/forms/transport/XhttpDownloadForm.tsx create mode 100644 frontend/src/test/xhttp-download-form.test.tsx create mode 100644 internal/web/service/inbound_xhttp.go create mode 100644 internal/web/service/inbound_xhttp_test.go diff --git a/docs/content/docs/en/config/transports.mdx b/docs/content/docs/en/config/transports.mdx index d9c7450c2..2d0b517a8 100644 --- a/docs/content/docs/en/config/transports.mdx +++ b/docs/content/docs/en/config/transports.mdx @@ -107,6 +107,12 @@ Session-ID fields (`sessionIDPlacement`, `sessionIDKey`, `sessionIDTable`, `sessionIDLength`) and the `scMin/MaxEachPostBytes` knobs are advanced; leave them empty unless you're matching a specific upstream. +Enable **Use separate download** to send the client's download requests to a +second endpoint. Enter its address and port, then set the HTTP host, path, and +security settings to match that endpoint. Both routes must reach the same XHTTP +listener. On an inbound, the panel includes these settings in client subscriptions. +The switch is available in `auto`, `packet-up`, and `stream-up` modes. + ### Hysteria — `hysteriaSettings` Only valid when the protocol is **Hysteria2**. diff --git a/docs/content/docs/fa/config/transports.mdx b/docs/content/docs/fa/config/transports.mdx index 058d6311b..98ee358c5 100644 --- a/docs/content/docs/fa/config/transports.mdx +++ b/docs/content/docs/fa/config/transports.mdx @@ -108,6 +108,12 @@ icon: Network `sessionIDLength`) و کلیدهای `scMin/MaxEachPostBytes` پیشرفته‌اند؛ آن‌ها را خالی بگذارید مگر آنکه با یک بالادست مشخص هماهنگ می‌شوید. +برای فرستادن درخواست‌های دانلود کلاینت به مقصدی جداگانه، **استفاده از مسیر دانلود جداگانه** +را فعال کنید. آدرس و پورت مقصد را وارد کنید و مقادیر `host` و `path` در HTTP و +تنظیمات امنیتی را مطابق آن مقصد تنظیم کنید. هر دو مسیر باید به یک شنوندهٔ XHTTP +برسند. اگر این گزینه را در اتصال ورودی فعال کنید، پنل این تنظیمات را در اشتراک +کلاینت‌ها قرار می‌دهد. این گزینه در حالت‌های `auto`، `packet-up` و `stream-up` در دسترس است. + ### Hysteria — `hysteriaSettings` تنها زمانی معتبر است که پروتکل **Hysteria2** باشد. diff --git a/docs/content/docs/ru/config/transports.mdx b/docs/content/docs/ru/config/transports.mdx index f70901269..8122d0657 100644 --- a/docs/content/docs/ru/config/transports.mdx +++ b/docs/content/docs/ru/config/transports.mdx @@ -110,6 +110,13 @@ HTTPUpgrade — это одноразовый HTTP/1.1 `Upgrade` без фрей `sessionIDLength`) и параметры `scMin/MaxEachPostBytes` — продвинутые; оставьте их пустыми, если только вы не подстраиваетесь под конкретный upstream. +Включите **Использовать отдельный канал загрузки**, чтобы клиент отправлял запросы +на скачивание на другой адрес. Укажите адрес и порт, затем задайте HTTP-параметры +`host` и `path` и настройки безопасности для этой точки подключения. Оба маршрута +должны вести к одному и тому же обработчику XHTTP. Если задать эти параметры для +входящего подключения, панель включит их в клиентские подписки. Переключатель +доступен в режимах `auto`, `packet-up` и `stream-up`. + ### Hysteria — `hysteriaSettings` Допустимо, только когда протокол — **Hysteria2**. diff --git a/docs/content/docs/zh/config/transports.mdx b/docs/content/docs/zh/config/transports.mdx index f40641254..1e178ef9e 100644 --- a/docs/content/docs/zh/config/transports.mdx +++ b/docs/content/docs/zh/config/transports.mdx @@ -103,6 +103,11 @@ Session-ID 字段(`sessionIDPlacement`、`sessionIDKey`、`sessionIDTable`、 `sessionIDLength`)以及 `scMin/MaxEachPostBytes` 旋钮属于高级项;除非要匹配某个特定的 上游,否则保持为空。 +启用**使用独立下载通道**后,客户端会向另一个端点发送下载请求。填写该端点的地址和端口, +并按其要求设置 HTTP 主机名、路径和安全参数。上传和下载两条路由必须通往同一个 XHTTP +监听器。在入站配置中启用此选项后,面板会将这些设置加入客户端订阅。此开关适用于 +`auto`、`packet-up` 和 `stream-up` 模式。 + ### Hysteria — `hysteriaSettings` 仅当协议为 **Hysteria2** 时有效。 diff --git a/frontend/src/lib/xray/forms/transport/XhttpDownloadForm.tsx b/frontend/src/lib/xray/forms/transport/XhttpDownloadForm.tsx new file mode 100644 index 000000000..da7845c58 --- /dev/null +++ b/frontend/src/lib/xray/forms/transport/XhttpDownloadForm.tsx @@ -0,0 +1,155 @@ +import { useId } from 'react'; +import { Form, Input, InputNumber, Switch } from 'antd'; +import { useTranslation } from 'react-i18next'; +import { useFormContext, useWatch } from 'react-hook-form'; + +import { NativeSelect } from '@/components/form/NativeSelect'; +import { FormField } from '@/components/form/rhf'; +import { UTLS_FINGERPRINT } from '@/schemas/primitives'; + +const root = 'streamSettings.xhttpSettings.downloadSettings'; + +// The core refuses to build a REALITY client whose fingerprint is unsafe or unknown. +const REALITY_FINGERPRINT_OPTIONS = Object.values(UTLS_FINGERPRINT) + .filter((fp) => fp !== UTLS_FINGERPRINT.UTLS_UNSAFE) + .map((fp) => ({ value: fp, label: fp })); + +export function XhttpDownloadForm({ mode }: { mode?: string }) { + const { t } = useTranslation(); + const id = useId(); + const { control, getValues, setValue, unregister } = useFormContext(); + const download = useWatch({ control, name: root }); + const security = download?.security; + const securityBlock = security === 'reality' ? 'realitySettings' : 'tlsSettings'; + + return ( + <> + + { + if (enabled) { + const upload = getValues('streamSettings.xhttpSettings') ?? {}; + const xhttpSettings: Record = { path: upload.path || '/' }; + for (const key of [ + 'host', + 'headers', + 'sessionIDPlacement', + 'sessionIDKey', + 'sessionIDTable', + 'sessionIDLength', + 'seqPlacement', + 'seqKey', + 'xPaddingBytes', + 'xPaddingObfsMode', + 'xPaddingKey', + 'xPaddingHeader', + 'xPaddingPlacement', + 'xPaddingMethod', + ]) { + if (upload[key] !== undefined) xhttpSettings[key] = structuredClone(upload[key]); + } + setValue( + root, + { network: 'xhttp', port: 443, security: 'tls', xhttpSettings }, + { shouldDirty: true }, + ); + } else { + unregister(root); + } + }} + /> + + {download && ( + <> + !!String(v).trim() || 'pages.xray.outboundForm.addressRequired', + }} + > + + + + + + + + + + + + { + unregister(root + '.tlsSettings'); + unregister(root + '.realitySettings'); + if (value === 'reality') + setValue(root + '.realitySettings', { fingerprint: 'chrome' }); + }} + > + ({ value, label: value }))} + /> + + {(security === 'tls' || security === 'reality') && ( + + + + )} + {security === 'reality' && ( + <> + + + + + + + + + + + )} + + )} + + ); +} diff --git a/frontend/src/lib/xray/inbound-form-adapter.ts b/frontend/src/lib/xray/inbound-form-adapter.ts index 5bc566931..334bf93da 100644 --- a/frontend/src/lib/xray/inbound-form-adapter.ts +++ b/frontend/src/lib/xray/inbound-form-adapter.ts @@ -27,11 +27,9 @@ import { import { canEnableSniffing } from '@/lib/xray/protocol-capabilities'; import { tlsCertUsesFiles } from '@/schemas/protocols/security/tls'; import { SockoptStreamSettingsSchema } from '@/schemas/protocols/stream/sockopt'; -import { XHttpStreamSettingsSchema, XHttpXmuxSchema } from '@/schemas/protocols/stream/xhttp'; +import { XHttpStreamSettingsSchema } from '@/schemas/protocols/stream/xhttp'; import { liftLegacyXDriveService } from '@/schemas/protocols/stream/xdrive'; -const XMUX_DEFAULTS = XHttpXmuxSchema.parse({}); - // Plain-data adapter between the panel's stored inbound row shape and // the typed InboundFormValues that Form.useForm carries inside // InboundFormModal. No dependency on the legacy Inbound/DBInbound @@ -197,7 +195,6 @@ export function rawInboundToFormValues(row: RawInboundRow): InboundFormValues { const xmux = xhttp.xmux; if (xmux && typeof xmux === 'object' && !Array.isArray(xmux)) { xhttp.enableXmux = true; - xhttp.xmux = { ...XMUX_DEFAULTS, ...(xmux as Record) }; } } const so = streamRecord.sockopt; diff --git a/frontend/src/lib/xray/inbound-link.ts b/frontend/src/lib/xray/inbound-link.ts index 6904c9b03..c16688b7b 100644 --- a/frontend/src/lib/xray/inbound-link.ts +++ b/frontend/src/lib/xray/inbound-link.ts @@ -14,6 +14,7 @@ import type { ExternalProxyEntry } from '@/schemas/protocols/stream/external-pro import type { FinalMaskStreamSettings } from '@/schemas/protocols/stream/finalmask'; import type { XHttpStreamSettings } from '@/schemas/protocols/stream/xhttp'; +import { resolveXmuxExclusivity } from './stream-wire-normalize'; import { parseGeckoPacketSize } from '@/lib/xray/forms/transport/FinalMaskForm'; import { UTLS_FINGERPRINT } from '@/schemas/primitives'; import { hasWgQuickHook, joinConfLines } from './conf-lines'; @@ -87,12 +88,14 @@ function buildXhttpExtra(xhttp: XHttpStreamSettings | undefined): Record> = { scMaxEachPostBytes: '1000000', + scMinPostsIntervalMs: '30', }; for (const k of stringFields) { const v = xhttp[k]; @@ -108,6 +111,17 @@ function buildXhttpExtra(xhttp: XHttpStreamSettings | undefined): Record 0) { + extra.xmux = resolveXmuxExclusivity(xhttp.xmux); + } + if (xhttp.downloadSettings && Object.keys(xhttp.downloadSettings).length > 0) { + extra.downloadSettings = xhttp.downloadSettings; + } + if (xhttp.noGRPCHeader) extra.noGRPCHeader = true; + if (xhttp.uplinkChunkSize && xhttp.uplinkChunkSize !== '0') { + extra.uplinkChunkSize = xhttp.uplinkChunkSize; + } + // Headers on the wire are a record; emit them as a map upstream's // SplitHTTPConfig.headers expects, dropping Host (already on the URL). if (xhttp.headers && Object.keys(xhttp.headers).length > 0) { diff --git a/frontend/src/lib/xray/outbound-form-adapter.ts b/frontend/src/lib/xray/outbound-form-adapter.ts index 340fdb476..06facd676 100644 --- a/frontend/src/lib/xray/outbound-form-adapter.ts +++ b/frontend/src/lib/xray/outbound-form-adapter.ts @@ -1,4 +1,4 @@ -import { XHttpXmuxSchema } from '@/schemas/protocols/stream/xhttp'; +import { flattenXhttpExtra } from '@/schemas/protocols/stream/xhttp'; import { liftLegacyXDriveService } from '@/schemas/protocols/stream/xdrive'; import { OutboundDomainStrategySchema } from '@/schemas/protocols/outbound'; import { AmneziaWGOutboundSettingsSchema } from '@/schemas/protocols/outbound'; @@ -572,8 +572,6 @@ export interface RawOutboundRow { mux?: unknown; } -const XMUX_DEFAULTS = XHttpXmuxSchema.parse({}); - function hydrateStreamForm(stream: Raw): OutboundStreamFormValues { const next = { ...stream }; if (typeof next.method === 'string' && next.method !== '') { @@ -583,11 +581,11 @@ function hydrateStreamForm(stream: Raw): OutboundStreamFormValues { liftLegacyXDriveService(next); const xh = next.xhttpSettings; if (xh && typeof xh === 'object' && !Array.isArray(xh)) { - const xhttp = { ...(xh as Raw) }; + const xhttp = flattenXhttpExtra(xh as Raw); const xmux = xhttp.xmux; if (xmux && typeof xmux === 'object' && !Array.isArray(xmux)) { xhttp.enableXmux = true; - xhttp.xmux = { ...XMUX_DEFAULTS, ...(xmux as Raw) }; + xhttp.xmux = { ...(xmux as Raw) }; } next.xhttpSettings = xhttp; } diff --git a/frontend/src/lib/xray/outbound-link-parser.ts b/frontend/src/lib/xray/outbound-link-parser.ts index 1b3b68db3..eed9d3d60 100644 --- a/frontend/src/lib/xray/outbound-link-parser.ts +++ b/frontend/src/lib/xray/outbound-link-parser.ts @@ -100,7 +100,9 @@ function applyXhttpStringFromParams(xhttp: Raw, params: URLSearchParams): void { } for (const k of XHTTP_NUMBER_KEYS) { const v = params.get(k); - if (v !== null && v !== '') xhttp[k] = Number(v) || 0; + if (v !== null && v !== '') { + xhttp[k] = k === 'uplinkChunkSize' && v.includes('-') ? v : Number(v) || 0; + } } for (const k of XHTTP_BOOL_KEYS) { const v = params.get(k); @@ -125,7 +127,9 @@ function applyXhttpStringFromJson(xhttp: Raw, json: Record): vo } } for (const k of XHTTP_NUMBER_KEYS) { - if (typeof json[k] === 'number') xhttp[k] = json[k]; + if (typeof json[k] === 'number' || (k === 'uplinkChunkSize' && typeof json[k] === 'string')) { + xhttp[k] = json[k]; + } } for (const k of XHTTP_BOOL_KEYS) { if (typeof json[k] === 'boolean') xhttp[k] = json[k]; diff --git a/frontend/src/lib/xray/stream-wire-normalize.ts b/frontend/src/lib/xray/stream-wire-normalize.ts index 18c87ce12..a1b098d17 100644 --- a/frontend/src/lib/xray/stream-wire-normalize.ts +++ b/frontend/src/lib/xray/stream-wire-normalize.ts @@ -5,6 +5,8 @@ // them anyway bloats configs and — for sockopt — can inject doc-example // values like tcpWindowClamp: 600 that throttle throughput. +import { flattenXhttpExtra } from '@/schemas/protocols/stream/xhttp'; + export type StreamWireSide = 'inbound' | 'outbound'; const PACKET_UP_FIELDS = [ @@ -60,7 +62,7 @@ export function int32RangeUpper(v: unknown): number { // and maxConcurrency. A positive maxConnections is an explicit opt-in to // connection-pool mode — honor it and drop the leftover maxConcurrency // default that load-time hydration backfills onto older saved configs. -function resolveXmuxExclusivity(xmux: Record): Record { +export function resolveXmuxExclusivity(xmux: Record): Record { if (int32RangeUpper(xmux.maxConnections) > 0 && int32RangeUpper(xmux.maxConcurrency) > 0) { const out = { ...xmux }; delete out.maxConcurrency; @@ -222,7 +224,7 @@ export function normalizeXhttpForWire( raw: Record, side: StreamWireSide, ): Record { - const out: Record = { ...raw }; + const out = flattenXhttpExtra(raw); liftLegacyXhttpSessionKeys(out); const mode = typeof out.mode === 'string' && out.mode !== '' ? out.mode : 'auto'; const enableXmux = out.enableXmux === true; @@ -236,7 +238,6 @@ export function normalizeXhttpForWire( if (out.scMinPostsIntervalMs === '' || out.scMinPostsIntervalMs === '30') { delete out.scMinPostsIntervalMs; } - delete out.uplinkChunkSize; } if (isRecord(out.xmux)) { @@ -259,7 +260,8 @@ export function normalizeXhttpForWire( if (out.noGRPCHeader !== true) delete out.noGRPCHeader; if (out.noSSEHeader !== true) delete out.noSSEHeader; if (out.serverMaxHeaderBytes === 0) delete out.serverMaxHeaderBytes; - if (out.uplinkChunkSize === 0) delete out.uplinkChunkSize; + if (out.uplinkChunkSize === 0 || out.uplinkChunkSize === '' || out.uplinkChunkSize === '0') + delete out.uplinkChunkSize; if (mode === 'stream-one') { for (const key of PACKET_UP_FIELDS) delete out[key]; diff --git a/frontend/src/pages/inbounds/form/advanced-editors.tsx b/frontend/src/pages/inbounds/form/advanced-editors.tsx index a8d948762..6f58a0bb8 100644 --- a/frontend/src/pages/inbounds/form/advanced-editors.tsx +++ b/frontend/src/pages/inbounds/form/advanced-editors.tsx @@ -1,6 +1,7 @@ import { useEffect, useRef, useState } from 'react'; import { useFormContext, useWatch } from 'react-hook-form'; +import { flattenXhttpExtra } from '@/schemas/protocols/stream/xhttp'; import { JsonEditor } from '@/components/form'; import { pruneEmpty, @@ -9,6 +10,15 @@ import { dropLegacyOptionalEmpties, } from '@/lib/xray/inbound-form-adapter'; +function normalizeAdvancedStream(stream: unknown): unknown { + if (!stream || typeof stream !== 'object' || !('xhttpSettings' in stream)) return stream; + const xhttp = stream.xhttpSettings; + if (!xhttp || typeof xhttp !== 'object' || Array.isArray(xhttp)) return stream; + const flat = flattenXhttpExtra(xhttp as Record); + if (flat.xmux) flat.enableXmux = true; + return { ...stream, xhttpSettings: flat }; +} + /* * Sub-editor for one slice of the form (settings, streamSettings, sniffing). * Holds a local text buffer so the user can type freely; on every keystroke @@ -71,8 +81,9 @@ export function AdvancedSliceEditor({ wrapKey && parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? ((parsed as Record)[wrapKey] ?? {}) : parsed; - setValue(path, toWrite); - lastEmitRef.current = JSON.stringify(wrapKey ? { [wrapKey]: toWrite } : toWrite, null, 2); + const value = path === 'streamSettings' ? normalizeAdvancedStream(toWrite) : toWrite; + setValue(path, value); + lastEmitRef.current = serialize(value); } catch { /* invalid JSON; keep buffer, don't push to form */ } @@ -228,6 +239,7 @@ export function AdvancedAllEditor({ setValue('sniffing', parsed.sniffing); } if (streamEnabled && parsed.streamSettings && typeof parsed.streamSettings === 'object') { + parsed.streamSettings = normalizeAdvancedStream(parsed.streamSettings); setValue('streamSettings', parsed.streamSettings); } const canonical = serialize(); diff --git a/frontend/src/pages/inbounds/form/transport/xhttp.tsx b/frontend/src/pages/inbounds/form/transport/xhttp.tsx index 257db7d6a..cfce41f60 100644 --- a/frontend/src/pages/inbounds/form/transport/xhttp.tsx +++ b/frontend/src/pages/inbounds/form/transport/xhttp.tsx @@ -3,9 +3,15 @@ import { useTranslation } from 'react-i18next'; import { AutoComplete, Input, InputNumber, Switch } from 'antd'; import { useFormContext, useWatch } from 'react-hook-form'; +import { XhttpDownloadForm } from '@/lib/xray/forms/transport/XhttpDownloadForm'; import { HeaderMapEditor } from '@/components/form'; -import { FormField } from '@/components/form/rhf'; -import { XHTTP_SESSION_ID_TABLES, XMUX_FRESH_DEFAULTS } from '@/schemas/protocols/stream/xhttp'; +import { FormField, rhfZodValidate } from '@/components/form/rhf'; +import { + XHttpChunkSizeSchema, + xhttpUplinkMethods, + XHTTP_SESSION_ID_TABLES, + XMUX_FRESH_DEFAULTS, +} from '@/schemas/protocols/stream/xhttp'; import { validateSessionIDLength, validateSessionIDTable } from '@/lib/xray/xhttp-session-id'; import { int32RangeUpper } from '@/lib/xray/stream-wire-normalize'; @@ -46,6 +52,11 @@ export default function XhttpForm() { control, name: 'streamSettings.xhttpSettings.uplinkDataPlacement', }) as string | undefined; + const method = useWatch({ control, name: 'streamSettings.xhttpSettings.uplinkHTTPMethod' }); + const hasDownload = !!useWatch({ + control, + name: 'streamSettings.xhttpSettings.downloadSettings', + }); const enableXmux = !!useWatch({ control, name: 'streamSettings.xhttpSettings.enableXmux' }); function onXmuxToggle(checked: boolean) { @@ -87,6 +98,9 @@ export default function XhttpForm() { options={(['auto', 'packet-up', 'stream-up', 'stream-one'] as const).map((m) => ({ value: m, label: m, + disabled: + (m === 'stream-one' && hasDownload) || + !!xhttpUplinkMethods(m).find((option) => option.value === method)?.disabled, }))} /> @@ -150,19 +164,9 @@ export default function XhttpForm() { name={['streamSettings', 'xhttpSettings', 'uplinkHTTPMethod']} label={t('pages.inbounds.form.uplinkHttpMethod')} > - + + + {(xhttpMode === 'auto' || xhttpMode === 'stream-up' || xhttpMode === 'stream-one') && ( + + + + )} + {xhttpMode === 'packet-up' && xhttpUplinkPlacement && xhttpUplinkPlacement !== 'body' && ( + + + + )} {/* XMUX is the connection-multiplexing layer xHTTP uses to fan out parallel requests over a small pool of upstream connections. UI-only diff --git a/frontend/src/pages/xray/outbounds/OutboundFormModal.tsx b/frontend/src/pages/xray/outbounds/OutboundFormModal.tsx index 4e574494a..e05a87e1d 100644 --- a/frontend/src/pages/xray/outbounds/OutboundFormModal.tsx +++ b/frontend/src/pages/xray/outbounds/OutboundFormModal.tsx @@ -9,7 +9,7 @@ import { Wireguard } from '@/utils'; import { formValuesToWirePayload, rawOutboundToFormValues } from '@/lib/xray/outbound-form-adapter'; import { parseOutboundLink } from '@/lib/xray/outbound-link-parser'; import XDriveForm from '@/lib/xray/forms/transport/XDriveForm'; -import { XMUX_FRESH_DEFAULTS } from '@/schemas/protocols/stream/xhttp'; +import { XHttpChunkSizeSchema, XMUX_FRESH_DEFAULTS } from '@/schemas/protocols/stream/xhttp'; import { OutboundFormBaseSchema, type OutboundFormValues } from '@/schemas/forms/outbound-form'; import { canEnableReality, @@ -350,6 +350,15 @@ export default function OutboundFormModal({ if (!(await methods.trigger())) return; values = methods.getValues(); } + if (values.streamSettings?.network === 'xhttp') { + const result = XHttpChunkSizeSchema.safeParse( + values.streamSettings.xhttpSettings?.uplinkChunkSize, + ); + if (!result.success) { + messageApi.error(result.error.issues[0].message); + return; + } + } const tagValue = (values.tag ?? '').trim(); if (!tagValue) { messageApi.error(t('pages.xray.outboundForm.tagRequired')); diff --git a/frontend/src/pages/xray/outbounds/transport/xhttp.tsx b/frontend/src/pages/xray/outbounds/transport/xhttp.tsx index a18f6a634..3b15163db 100644 --- a/frontend/src/pages/xray/outbounds/transport/xhttp.tsx +++ b/frontend/src/pages/xray/outbounds/transport/xhttp.tsx @@ -2,11 +2,16 @@ import { useTranslation } from 'react-i18next'; import { AutoComplete, Input, InputNumber, Select, Switch } from 'antd'; import { useFormContext, useWatch } from 'react-hook-form'; +import { XhttpDownloadForm } from '@/lib/xray/forms/transport/XhttpDownloadForm'; import { HeaderMapEditor } from '@/components/form'; -import { FormField } from '@/components/form/rhf'; +import { FormField, rhfZodValidate } from '@/components/form/rhf'; import { validateSessionIDLength, validateSessionIDTable } from '@/lib/xray/xhttp-session-id'; import { int32RangeUpper } from '@/lib/xray/stream-wire-normalize'; -import { XHTTP_SESSION_ID_TABLES } from '@/schemas/protocols/stream/xhttp'; +import { + XHttpChunkSizeSchema, + xhttpUplinkMethods, + XHTTP_SESSION_ID_TABLES, +} from '@/schemas/protocols/stream/xhttp'; import { MODE_OPTIONS } from '../outbound-form-constants'; @@ -40,6 +45,11 @@ export default function XhttpForm({ onXmuxToggle }: XhttpFormProps) { const uplinkDataPlacement = useWatch({ control, name: `${XH}.uplinkDataPlacement` }) as | string | undefined; + const method = useWatch({ control, name: 'streamSettings.xhttpSettings.uplinkHTTPMethod' }); + const hasDownload = !!useWatch({ + control, + name: 'streamSettings.xhttpSettings.downloadSettings', + }); const enableXmux = !!useWatch({ control, name: `${XH}.enableXmux` }); function onXmuxMaxConcurrencyChange(value: unknown) { @@ -68,7 +78,15 @@ export default function XhttpForm({ onXmuxToggle }: XhttpFormProps) { label={t('pages.inbounds.info.mode')} name={['streamSettings', 'xhttpSettings', 'mode']} > - ({ + ...option, + disabled: + (option.value === 'stream-one' && hasDownload) || + !!xhttpUplinkMethods(option.value).find((option) => option.value === method) + ?.disabled, + }))} + /> - + {/* Session + sequence + uplinkData placements: three orthogonal slots Xray uses to thread @@ -266,14 +277,15 @@ export default function XhttpForm({ onXmuxToggle }: XhttpFormProps) { - + )} )} - {(mode === 'stream-up' || mode === 'stream-one') && ( + {(mode === 'auto' || mode === 'stream-up' || mode === 'stream-one') && ( ; // Full form values = base + db fields + protocol-discriminated settings. // Consumers narrow on `.protocol` to access the matching settings branch. -export const InboundFormSchema = - InboundFormBaseSchema.and(InboundDbFieldsSchema).and(InboundSettingsSchema); +export const InboundFormSchema = InboundFormBaseSchema.and(InboundDbFieldsSchema) + .and(InboundSettingsSchema) + .superRefine((form, ctx) => { + const stream = form.streamSettings; + if (stream?.network !== 'xhttp') return; + const xhttp = stream.xhttpSettings; + const down = xhttp?.downloadSettings; + if (!down) return; + const issue = (field: string[], message: string) => + ctx.addIssue({ + code: 'custom', + path: ['streamSettings', 'xhttpSettings', 'downloadSettings', ...field], + message, + }); + if (xhttp.mode === 'stream-one') + issue([], 'Separate download is incompatible with stream-one.'); + if (!['xhttp', 'splithttp'].includes(String(down.method ?? down.network).toLowerCase())) + issue(['network'], 'Select XHTTP for the download transport.'); + if (typeof down.address !== 'string' || !down.address.trim()) + issue(['address'], 'Enter a download address.'); + if ( + typeof down.port !== 'number' || + !Number.isInteger(down.port) || + down.port < 1 || + down.port > 65535 + ) + issue(['port'], 'Enter a port from 1 to 65535.'); + const security = String(down.security ?? '').toLowerCase(); + if (!['', 'none', 'tls', 'reality'].includes(security)) + issue(['security'], 'Select none, TLS or REALITY.'); + if (security === 'reality') { + const r = down.realitySettings as Record | undefined; + const key = r?.password || r?.publicKey; + if (typeof key !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(key)) + issue( + ['realitySettings', r?.password || !r?.publicKey ? 'password' : 'publicKey'], + 'Enter a 32-byte unpadded base64url REALITY public key.', + ); + if ( + r?.shortId != null && + (typeof r.shortId !== 'string' || !/^(?:[0-9a-fA-F]{2}){0,8}$/.test(r.shortId)) + ) + issue(['realitySettings', 'shortId'], 'Enter up to 8 hexadecimal bytes.'); + } + }); export type InboundFormValues = z.infer; export const FallbackRowSchema = z.object({ diff --git a/frontend/src/schemas/protocols/stream/xhttp.ts b/frontend/src/schemas/protocols/stream/xhttp.ts index 4b92f8a81..2512be8cf 100644 --- a/frontend/src/schemas/protocols/stream/xhttp.ts +++ b/frontend/src/schemas/protocols/stream/xhttp.ts @@ -5,40 +5,41 @@ import { WsHeaderMapSchema } from '@/schemas/protocols/stream/ws'; export const XHttpModeSchema = z.enum(['auto', 'packet-up', 'stream-up', 'stream-one']); export type XHttpMode = z.infer; -// xHTTP (SplitHTTPConfig) is xray-core's modern stream-multiplexed transport. -// The field set is large because the schema mirrors what the server-side -// listener reads — plus a few client-only fields (`uplinkHTTPMethod`, -// `headers`) the panel embeds into share-link `extra` blobs even though the -// server ignores them at runtime. Outbound has additional fields (uplinkChunk -// sizes, noGRPCHeader, scMinPostsIntervalMs, xmux, downloadSettings) which -// belong on the outbound class instead, not modeled here. -// XMUX is the connection-multiplexing layer xHTTP uses to fan out -// parallel requests over a small pool of upstream connections. Fields -// are strings because they accept dash-range values like '16-32'. -// maxConcurrency and maxConnections are mutually exclusive strategies -// (xray-core rejects a config that sets both), so the bare schema -// default keeps only one of them non-zero — a non-zero maxConnections -// default resurrected on load made every re-save silently delete the -// user's maxConcurrency. -export const XHttpXmuxSchema = z.object({ - maxConcurrency: z.string().default('16-32'), - maxConnections: z.union([z.string(), z.number()]).default(0), - cMaxReuseTimes: z.union([z.string(), z.number()]).default(0), - hMaxRequestTimes: z.string().default('600-900'), - hMaxReusableSecs: z.string().default('1800-3000'), - hKeepAlivePeriod: z.number().int().min(0).default(0), +export function xhttpUplinkMethods(mode?: string) { + return [ + { value: '', label: 'Default (POST)' }, + ...['POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'].map((value) => ({ value, label: value })), + { value: 'GET', label: 'GET (packet-up only)', disabled: mode !== 'packet-up' }, + // OpenStream drains the upload response before closing its request body. + // HEAD has no response body to keep a streaming upload open. + { value: 'HEAD', label: 'HEAD (packet-up only)', disabled: mode !== 'packet-up' }, + ]; +} + +// Xray accepts an int32 or a range string. Text controls use the string form. +const rangeText = z.union([z.string(), z.int32().transform(String)]); + +// A stored XMUX object is sparse. Xray chooses its own fallback when the +// block is empty. Preserve explicit zeros, numeric ranges and omitted keys. +const xmuxRange = z.union([z.int32(), z.string()]).optional(); +export const XHttpXmuxSchema = z.looseObject({ + maxConcurrency: xmuxRange, + maxConnections: xmuxRange, + cMaxReuseTimes: xmuxRange, + hMaxRequestTimes: xmuxRange, + hMaxReusableSecs: xmuxRange, + hKeepAlivePeriod: z.number().int().min(0).optional(), }); export type XHttpXmux = z.infer; -// Seed for freshly enabling XMUX on a config that had no xmux block: -// mirrors xray-core's own maxConnections fallback rather than the -// concurrency strategy. v26.7.28 lowered that fallback from 6 to 3 for -// anti-TSPU, so track it here to keep a fresh panel config matching what -// the core would have picked on its own. +// Seed only a newly enabled block. Select one connection-limit strategy. export const XMUX_FRESH_DEFAULTS: XHttpXmux = { - ...XHttpXmuxSchema.parse({}), maxConcurrency: '', maxConnections: 3, + cMaxReuseTimes: 0, + hMaxRequestTimes: '600-900', + hMaxReusableSecs: '1800-3000', + hKeepAlivePeriod: 0, }; // Predefined sessionIDTable names xray-core accepts as a shorthand for a @@ -61,9 +62,22 @@ export const XHTTP_SESSION_ID_TABLES = [ // sessionIDTable/sessionIDLength. Lift any legacy keys persisted by an older // panel onto the new names so a saved inbound/outbound never silently loses // its session setting, then drop the legacy keys so we never emit both. +// In core's wrapped syntax only host, path and mode come from the outer +// object. The panel edits the equivalent flat syntax. +export function flattenXhttpExtra(raw: Record): Record { + const { extra, host, path, mode } = raw; + const flat: Record = + extra === null || (typeof extra === 'object' && !Array.isArray(extra)) + ? { ...extra, host, path, mode } + : { ...raw }; + if (flat.xmux === null) delete flat.xmux; + if (flat.downloadSettings === null) delete flat.downloadSettings; + return flat; +} + function migrateLegacyXhttp(v: unknown): unknown { if (v == null || typeof v !== 'object' || Array.isArray(v)) return v; - const o = { ...(v as Record) }; + const o = flattenXhttpExtra(v as Record); if (o.sessionIDPlacement === undefined && o.sessionPlacement !== undefined) { o.sessionIDPlacement = o.sessionPlacement; } @@ -75,13 +89,35 @@ function migrateLegacyXhttp(v: unknown): unknown { return o; } +const maxChunkSize = 0x7fffffff; +const chunkSizeMessage = + 'Enter a nonnegative integer or byte range, e.g. 512-1024 (maximum 2147483647).'; +export const XHttpChunkSizeSchema = z + .union( + [ + z.number().int().min(0).max(maxChunkSize), + z + .string() + .refine( + (value) => + value === '' || + (/^\d+(?:-\d+)?$/.test(value) && + value.split('-').every((part) => Number(part) <= maxChunkSize)), + chunkSizeMessage, + ), + ], + { error: chunkSizeMessage }, + ) + .default(0); + export const XHttpStreamSettingsSchema = z.preprocess( migrateLegacyXhttp, - z.object({ + z.looseObject({ + downloadSettings: z.record(z.string(), z.unknown()).optional(), path: z.string().default('/'), host: z.string().default(''), mode: XHttpModeSchema.default('auto'), - xPaddingBytes: z.string().default('100-1000'), + xPaddingBytes: rangeText.default('100-1000'), xPaddingObfsMode: z.boolean().default(false), xPaddingKey: z.string().default(''), xPaddingHeader: z.string().default(''), @@ -93,7 +129,7 @@ export const XHttpStreamSettingsSchema = z.preprocess( // ASCII charset. sessionIDLength: dash-range string (e.g. '8-16'); only // honored when a table is set. xray-core enforces the room-size minimum. sessionIDTable: z.string().default(''), - sessionIDLength: z.string().default(''), + sessionIDLength: rangeText.default(''), seqPlacement: z.string().default(''), seqKey: z.string().default(''), uplinkDataPlacement: z.string().default(''), @@ -101,10 +137,12 @@ export const XHttpStreamSettingsSchema = z.preprocess( // Empty default on purpose: xray-core already defaults to 1MB/30ms, and // baking the literal values into every config and share link gives DPI a // stable fingerprint (#5141 — TSPU keys on scMinPostsIntervalMs=30). - scMaxEachPostBytes: z.string().default(''), + scMaxEachPostBytes: z + .union([z.string(), z.number().int().nonnegative().transform(String)]) + .default(''), noSSEHeader: z.boolean().default(false), scMaxBufferedPosts: z.number().int().min(0).default(30), - scStreamUpServerSecs: z.string().default('20-80'), + scStreamUpServerSecs: rangeText.default('20-80'), serverMaxHeaderBytes: z.number().int().min(0).default(0), uplinkHTTPMethod: z.string().default(''), headers: WsHeaderMapSchema.default({}), @@ -115,9 +153,8 @@ export const XHttpStreamSettingsSchema = z.preprocess( // them in share-link `extra` blobs so the same xhttp config can // round-trip on both sides. // - scMinPostsIntervalMs: preserved when non-default (stripped at '' or '30') - // - uplinkChunkSize & noGRPCHeader: outbound-only; stripped from inbound wire - scMinPostsIntervalMs: z.string().default(''), - uplinkChunkSize: z.number().int().min(0).default(0), + scMinPostsIntervalMs: rangeText.default(''), + uplinkChunkSize: XHttpChunkSizeSchema, noGRPCHeader: z.boolean().default(false), xmux: XHttpXmuxSchema.optional(), // UI-only toggle controlling whether the XMUX sub-form is expanded. diff --git a/frontend/src/test/__snapshots__/inbound-form-blocks.test.tsx.snap b/frontend/src/test/__snapshots__/inbound-form-blocks.test.tsx.snap index 1d71a2501..2afe583ca 100644 --- a/frontend/src/test/__snapshots__/inbound-form-blocks.test.tsx.snap +++ b/frontend/src/test/__snapshots__/inbound-form-blocks.test.tsx.snap @@ -117,6 +117,7 @@ exports[`inbound transport forms > XhttpForm field structure is stable 1`] = ` "Padding Bytes", "Headers", "Uplink HTTP Method", + "Use separate download", "Padding Obfs Mode", "Session Placement", "Session ID Table", diff --git a/frontend/src/test/__snapshots__/stream.test.ts.snap b/frontend/src/test/__snapshots__/stream.test.ts.snap index 66e0e26e0..4f9cc4166 100644 --- a/frontend/src/test/__snapshots__/stream.test.ts.snap +++ b/frontend/src/test/__snapshots__/stream.test.ts.snap @@ -209,7 +209,6 @@ exports[`NetworkSettingsSchema fixtures > parses xhttp-extra-tuning byte-stably "hMaxRequestTimes": "600-900", "hMaxReusableSecs": "1800-3000", "maxConcurrency": "16-32", - "maxConnections": 0, }, }, } diff --git a/frontend/src/test/advanced-all-editor.test.tsx b/frontend/src/test/advanced-all-editor.test.tsx index 50c020f0a..355da2202 100644 --- a/frontend/src/test/advanced-all-editor.test.tsx +++ b/frontend/src/test/advanced-all-editor.test.tsx @@ -3,7 +3,8 @@ import { describe, expect, it, vi } from 'vitest'; import { act, fireEvent, render, screen } from '@testing-library/react'; import { FormProvider, useForm, useWatch } from 'react-hook-form'; -import { AdvancedAllEditor } from '@/pages/inbounds/form/advanced-editors'; +import { XhttpDownloadForm } from '@/lib/xray/forms/transport/XhttpDownloadForm'; +import { AdvancedAllEditor, AdvancedSliceEditor } from '@/pages/inbounds/form/advanced-editors'; vi.mock('@/components/form', () => ({ JsonEditor: ({ value, onChange }: { value: string; onChange: (next: string) => void }) => ( @@ -124,3 +125,50 @@ describe('AdvancedAllEditor JSON buffer (#6854)', () => { expect(input.value).toContain('"port": 8443,\n\n'); }); }); + +function XhttpHarness({ slice }: { slice: boolean }) { + const methods = useForm({ defaultValues: { streamSettings: { network: 'xhttp' } } }); + return ( + + {slice ? ( + + ) : ( + + )} + + + ); +} + +it.each([ + [true, true], + [true, false], + [false, true], + [false, false], +])('edits pasted XMUX and download settings (slice=%s, wrapped=%s)', async (slice, wrapped) => { + render(); + const json = editor(); + const pasted = JSON.parse(json.value); + const tuning = { + futureOption: { strategy: 'keep' }, + xmux: { maxConnections: 9 }, + downloadSettings: { network: 'xhttp', address: 'old.example', port: 443 }, + }; + pasted.streamSettings = { + network: 'xhttp', + xhttpSettings: { path: '/up', ...(wrapped ? { extra: tuning } : tuning) }, + }; + fireEvent.change(json, { target: { value: JSON.stringify(pasted) } }); + expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('true'); + fireEvent.change(screen.getByDisplayValue('old.example'), { target: { value: 'new.example' } }); + await flushFormEffects(); + const saved = JSON.parse(json.value).streamSettings.xhttpSettings; + expect(saved).toMatchObject({ + path: '/up', + futureOption: { strategy: 'keep' }, + xmux: { maxConnections: 9 }, + enableXmux: true, + downloadSettings: { address: 'new.example' }, + }); + expect(saved).not.toHaveProperty('extra'); +}); diff --git a/frontend/src/test/inbound-form-adapter.test.ts b/frontend/src/test/inbound-form-adapter.test.ts index 57b6f96d0..fb90e1f53 100644 --- a/frontend/src/test/inbound-form-adapter.test.ts +++ b/frontend/src/test/inbound-form-adapter.test.ts @@ -11,6 +11,10 @@ import { InboundDbFieldsSchema, InboundFormSchema } from '@/schemas/forms/inboun import { normalizeXhttpForWire } from '@/lib/xray/stream-wire-normalize'; import { SockoptStreamSettingsSchema } from '@/schemas/protocols/stream/sockopt'; +import { InboundSchema } from '@/schemas/api/inbound'; +import { genVlessLink } from '@/lib/xray/inbound-link'; +import { parseVlessLink } from '@/lib/xray/outbound-link-parser'; + // Round-trip: raw DB row → InboundFormValues → wire payload, asserting // that the JSON-stringified settings/streamSettings/sniffing in the // payload deserialize back to the same data the raw row carried. @@ -484,7 +488,7 @@ describe('xhttp xmux maxConcurrency survives a load/re-save round-trip', () => { expect(xhttp.enableXmux).toBe(true); const xmux = xhttp.xmux as Record; expect(xmux.maxConcurrency).toBe('1-2'); - expect(xmux.maxConnections).toBe(0); + expect(xmux).not.toHaveProperty('maxConnections'); }); it('formValuesToWirePayload keeps maxConcurrency on an unedited re-save', () => { @@ -495,3 +499,111 @@ describe('xhttp xmux maxConcurrency survives a load/re-save round-trip', () => { expect(xmux.maxConcurrency).toBe('1-2'); }); }); + +describe('XHTTP separate download', () => { + const downloadSettings = { + address: 'download.example.org', + port: 443, + network: 'xhttp', + security: 'tls', + tlsSettings: { serverName: 'download.example.org', alpn: ['h2'] }, + xhttpSettings: { path: '/down' }, + }; + + it.each([ + ['stream-one', downloadSettings, 'Separate download is incompatible with stream-one.'], + ['auto', { ...downloadSettings, network: 'tcp' }, 'Select XHTTP for the download transport.'], + [ + 'auto', + { ...downloadSettings, security: 'reality', realitySettings: { password: 'abc' } }, + 'Enter a 32-byte unpadded base64url REALITY public key.', + ], + ] as const)('rejects invalid separate download settings before save', (mode, download, why) => { + const form = rawInboundToFormValues({ + ...vlessRow, + streamSettings: { + network: 'xhttp', + security: 'none', + xhttpSettings: { mode, extra: { downloadSettings: download } }, + }, + }); + const result = InboundFormSchema.safeParse(form); + expect(result.error?.issues.map((issue) => issue.message)).toEqual([why]); + }); + + it.each([true, false])('retains the entire download stream (wrapped=%s)', (wrapped) => { + const tuning = { + downloadSettings, + noGRPCHeader: true, + uplinkChunkSize: '512-1024', + scMinPostsIntervalMs: '60', + xmux: { maxConnections: 4 }, + }; + const advanced = { ...tuning, futureOption: { weights: [1, 2] } }; + const xhttpSettings = { path: '/up', ...(wrapped ? { extra: advanced } : advanced) }; + const stream = { network: 'xhttp', security: 'none', xhttpSettings }; + const form = rawInboundToFormValues({ ...vlessRow, streamSettings: JSON.stringify(stream) }); + const saved = JSON.parse(formValuesToWirePayload(InboundFormSchema.parse(form)).streamSettings); + expect(saved.xhttpSettings).toMatchObject({ path: '/up', ...advanced }); + const inbound = InboundSchema.parse({ ...vlessRow, streamSettings: saved }); + const url = genVlessLink({ + inbound, + address: 'up.example.org', + clientId: '8c14d6f7-2e3b-4a91-9d24-3f7a6b8c1e02', + }); + expect(parseVlessLink(url)).toMatchObject({ streamSettings: { xhttpSettings: tuning } }); + const extra = JSON.parse(new URL(url).searchParams.get('extra')!); + expect(extra.xmux).not.toHaveProperty('maxConcurrency'); + }); +}); + +it.each([true, false])( + 'saves an unrelated edit with numeric XHTTP ranges (wrapped=%s)', + (wrapped) => { + const ranges = { + xPaddingBytes: 512, + scMinPostsIntervalMs: 60, + scMaxEachPostBytes: 32768, + scStreamUpServerSecs: 25, + sessionIDLength: 12, + sessionIDTable: 'Base62', + xmux: { maxConcurrency: 4, hMaxRequestTimes: 700, hMaxReusableSecs: 2400 }, + }; + const form = rawInboundToFormValues({ + ...vlessRow, + streamSettings: { + network: 'xhttp', + security: 'none', + xhttpSettings: wrapped ? { extra: ranges } : ranges, + }, + }); + const parsed = InboundFormSchema.parse({ ...form, remark: 'edited' }); + const payload = formValuesToWirePayload(parsed); + expect(payload.remark).toBe('edited'); + expect(JSON.parse(payload.streamSettings).xhttpSettings).toMatchObject({ + xPaddingBytes: '512', + scMinPostsIntervalMs: '60', + scMaxEachPostBytes: '32768', + scStreamUpServerSecs: '25', + sessionIDLength: '12', + xmux: { maxConcurrency: 4, hMaxRequestTimes: 700, hMaxReusableSecs: 2400 }, + }); + }, +); + +it.each([true, false])( + 'treats explicit null downloadSettings as disabled (wrapped=%s)', + (wrapped) => { + const tuning = { downloadSettings: null, xPaddingBytes: '200-300' }; + const stream = { + network: 'xhttp', + security: 'none', + xhttpSettings: wrapped ? { extra: tuning } : tuning, + }; + const form = rawInboundToFormValues({ ...vlessRow, streamSettings: JSON.stringify(stream) }); + const parsed = InboundFormSchema.parse({ ...form, remark: 'edited' }); + const saved = JSON.parse(formValuesToWirePayload(parsed).streamSettings); + expect(saved.xhttpSettings).not.toHaveProperty('downloadSettings'); + expect(saved.xhttpSettings.xPaddingBytes).toBe('200-300'); + }, +); diff --git a/frontend/src/test/inbound-link.test.ts b/frontend/src/test/inbound-link.test.ts index 9b7c873bb..94c765f40 100644 --- a/frontend/src/test/inbound-link.test.ts +++ b/frontend/src/test/inbound-link.test.ts @@ -1598,3 +1598,34 @@ describe('isPostQuantumLink', () => { }); }); }); + +describe('copied XHTTP links from stored inbounds', () => { + it.each([ + undefined, + null, + {}, + { hKeepAlivePeriod: 45 }, + { hKeepAlivePeriod: 0 }, + { maxConcurrency: '16-32' }, + { maxConcurrency: 8, hMaxRequestTimes: 700 }, + ])('exports only explicitly stored XMUX settings (%j)', (xmux) => { + const inbound = inboundFromDb({ + protocol: 'vless', + port: 443, + listen: '', + settings: {}, + sniffing: {}, + streamSettings: JSON.stringify({ network: 'xhttp', xhttpSettings: { path: '/up', xmux } }), + }); + const url = genVlessLink({ + inbound, + address: 'up.example', + clientId: '8c14d6f7-2e3b-4a91-9d24-3f7a6b8c1e02', + }); + const params = new URL(url).searchParams; + expect(params.get('path')).toBe('/up'); + const extra = JSON.parse(params.get('extra')!); + if (xmux && Object.keys(xmux).length) expect(extra.xmux).toEqual(xmux); + else expect(extra).not.toHaveProperty('xmux'); + }); +}); diff --git a/frontend/src/test/outbound-form-adapter.test.ts b/frontend/src/test/outbound-form-adapter.test.ts index 4ffa8b26a..def0e4643 100644 --- a/frontend/src/test/outbound-form-adapter.test.ts +++ b/frontend/src/test/outbound-form-adapter.test.ts @@ -824,19 +824,12 @@ describe('outbound-form-adapter: xhttp xmux toggle', () => { }, }; - it('derives enableXmux from a saved xmux object and backfills missing knobs', () => { + it('derives enableXmux from a saved xmux object without filling missing fields', () => { const form = rawOutboundToFormValues(xmuxWire); const stream = form.streamSettings as Record; const xhttp = stream.xhttpSettings as Record; expect(xhttp.enableXmux).toBe(true); - expect(xhttp.xmux).toMatchObject({ - maxConcurrency: '11', - maxConnections: '1', - hMaxRequestTimes: '1', - hMaxReusableSecs: '1', - cMaxReuseTimes: 0, - hKeepAlivePeriod: 0, - }); + expect(xhttp.xmux).toEqual(xmuxWire.streamSettings.xhttpSettings.xmux); }); it('round-trips xmux on save, strips enableXmux, and enforces xmux exclusivity', () => { @@ -890,7 +883,7 @@ describe('outbound-form-adapter: xhttp xmux toggle', () => { >; const xmux = xhttp.xmux as Record; expect(xmux.maxConcurrency).toBe('1-2'); - expect(xmux.maxConnections).toBe(0); + expect(xmux).not.toHaveProperty('maxConnections'); const back = formValuesToWirePayload(form); const wireXhttp = (back.streamSettings as Record).xhttpSettings as Record< diff --git a/frontend/src/test/stream-wire-normalize.test.ts b/frontend/src/test/stream-wire-normalize.test.ts index e555ae0a4..5dfd4e735 100644 --- a/frontend/src/test/stream-wire-normalize.test.ts +++ b/frontend/src/test/stream-wire-normalize.test.ts @@ -242,9 +242,8 @@ describe('normalizeXhttpForWire stream-one', () => { expect(xmux.maxConnections).toBe('8'); }); - it('bare schema defaults keep only one exclusive xmux strategy non-zero', () => { - expect(XHttpXmuxSchema.parse({}).maxConnections).toBe(0); - expect(XHttpXmuxSchema.parse({}).maxConcurrency).toBe('16-32'); + it('an empty stored XMUX block leaves both connection strategies to core', () => { + expect(XHttpXmuxSchema.parse({})).toEqual({}); }); it('XMUX_FRESH_DEFAULTS seeds the core maxConnections fallback without a competing maxConcurrency', () => { diff --git a/frontend/src/test/stream.test.ts b/frontend/src/test/stream.test.ts index c61b4efd0..801f472e7 100644 --- a/frontend/src/test/stream.test.ts +++ b/frontend/src/test/stream.test.ts @@ -1,6 +1,7 @@ /// import { describe, expect, it } from 'vitest'; +import { xhttpUplinkMethods } from '@/schemas/protocols/stream/xhttp'; import { NetworkSettingsSchema } from '@/schemas/protocols'; const streamFixtures = import.meta.glob('./golden/fixtures/stream/*.json', { @@ -81,3 +82,11 @@ describe('NetworkSettingsSchema xray-core 26.10.21 keys', () => { expect(masque.masqueSettings.xmux).toEqual(xmux); }); }); + +it('offers HEAD only for discrete packet uploads', () => { + for (const mode of ['packet-up', 'stream-up', 'auto', 'stream-one']) { + expect(xhttpUplinkMethods(mode).find(({ value }) => value === 'HEAD')?.disabled).toBe( + mode !== 'packet-up', + ); + } +}); diff --git a/frontend/src/test/xhttp-download-form.test.tsx b/frontend/src/test/xhttp-download-form.test.tsx new file mode 100644 index 000000000..255429b5d --- /dev/null +++ b/frontend/src/test/xhttp-download-form.test.tsx @@ -0,0 +1,100 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { FormProvider, useForm, useWatch } from 'react-hook-form'; +import { describe, expect, it, vi } from 'vitest'; + +import OutboundXhttpForm from '@/pages/xray/outbounds/transport/xhttp'; +import { XhttpDownloadForm } from '@/lib/xray/forms/transport/XhttpDownloadForm'; + +function Harness({ mode, existing }: { mode: string; existing?: object }) { + const form = useForm({ + defaultValues: { + streamSettings: { + xhttpSettings: { + path: '/up', + sessionIDPlacement: 'header', + sessionIDKey: 'X-Session', + downloadSettings: existing, + }, + }, + }, + }); + const values = useWatch({ control: form.control }); + return ( + + + {JSON.stringify(values)} + + ); +} + +describe('separate XHTTP download', () => { + it('creates a download transport and removes it when switched off', () => { + render(); + const toggle = screen.getByRole('switch'); + fireEvent.click(toggle); + expect( + JSON.parse(screen.getByTestId('wire').textContent!).streamSettings.xhttpSettings + .downloadSettings, + ).toMatchObject({ + network: 'xhttp', + xhttpSettings: { path: '/up', sessionIDPlacement: 'header', sessionIDKey: 'X-Session' }, + }); + fireEvent.click(toggle); + expect(screen.getByTestId('wire').textContent).not.toContain('downloadSettings'); + }); + + it('opens a stored transport and preserves its other TLS options when editing the path', () => { + render( + , + ); + fireEvent.change(screen.getByDisplayValue('/original'), { target: { value: '/changed' } }); + const wire = JSON.parse(screen.getByTestId('wire').textContent!); + expect(wire.streamSettings.xhttpSettings.downloadSettings).toMatchObject({ + tlsSettings: { alpn: ['h2'] }, + xhttpSettings: { path: '/changed' }, + }); + }); + + it('disables separate download in stream-one mode', () => { + render(); + expect((screen.getByRole('switch') as HTMLButtonElement).disabled).toBe(true); + }); +}); + +it('blocks malformed outbound chunk ranges and accepts a corrected range', async () => { + const onSave = vi.fn(); + function OutboundHarness() { + const form = useForm({ + defaultValues: { + streamSettings: { + xhttpSettings: { mode: 'packet-up', uplinkDataPlacement: 'header' }, + }, + }, + }); + return ( + +
+ {}} /> + + +
+ ); + } + render(); + const chunk = screen.getByPlaceholderText('512-1024'); + fireEvent.change(chunk, { target: { value: '512-abc' } }); + fireEvent.click(screen.getByText('Save')); + await waitFor(() => expect(chunk.getAttribute('aria-invalid')).toBe('true')); + expect(onSave).not.toHaveBeenCalled(); + fireEvent.change(chunk, { target: { value: '512-1024' } }); + fireEvent.click(screen.getByText('Save')); + await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1)); +}); diff --git a/internal/database/model/model.go b/internal/database/model/model.go index b938a358f..f6561951a 100644 --- a/internal/database/model/model.go +++ b/internal/database/model/model.go @@ -321,6 +321,31 @@ func healVersionField(raw string, path []string) (string, bool) { return string(out), true } +// NormalizeXhttpExtra applies Xray's replacement semantics to a decoded stream. +func NormalizeXhttpExtra(stream map[string]any) bool { + xh, _ := stream["xhttpSettings"].(map[string]any) + raw, wrapped := xh["extra"] + if !wrapped { + return false + } + inner, ok := raw.(map[string]any) + if !ok && raw != nil { + return false + } + flat := make(map[string]any, len(inner)+3) + for k, v := range inner { + flat[k] = v + } + for _, k := range []string{"host", "path", "mode"} { + delete(flat, k) + if v, ok := xh[k]; ok { + flat[k] = v + } + } + stream["xhttpSettings"] = flat + return true +} + // StripInboundXhttpClientFields removes xHTTP knobs that belong on the // client dialer and subscription share-link extras only. xray-core's XHTTP // inbound listener does not consume them; the panel still stores them on @@ -336,8 +361,9 @@ func StripInboundXhttpClientFields(streamSettings string) (string, bool) { if stream["network"] != "xhttp" { return streamSettings, false } + changed := NormalizeXhttpExtra(stream) xhttp, ok := stream["xhttpSettings"].(map[string]any) - if !ok || len(xhttp) == 0 { + if !ok { return streamSettings, false } clientOnly := []string{ @@ -347,7 +373,6 @@ func StripInboundXhttpClientFields(streamSettings string) (string, bool) { "uplinkChunkSize", "noGRPCHeader", } - changed := false for _, key := range clientOnly { if _, has := xhttp[key]; has { delete(xhttp, key) diff --git a/internal/sub/clash_service.go b/internal/sub/clash_service.go index 422eebae8..1921daf83 100644 --- a/internal/sub/clash_service.go +++ b/internal/sub/clash_service.go @@ -952,6 +952,67 @@ func (s *SubClashService) buildAmneziaWGProxy(subReq *SubService, inbound *model // // Returns nil if no non-trivial fields are present. func buildXhttpClashOpts(xhttp map[string]any) map[string]any { + opts := xhttpClashRequestOpts(xhttp) + if down, ok := xhttp["downloadSettings"].(map[string]any); ok { + if opts == nil { + opts = map[string]any{} + } + opts["download-settings"] = xhttpClashDownload(down) + } + return opts +} + +func xhttpClashDownload(down map[string]any) map[string]any { + // Mihomo inherits omitted download values from the upload. Xray builds + // an independent stream, including certificate verification and REALITY. + ds := map[string]any{ + "server": down["address"], "port": down["port"], + "reality-opts": map[string]any{"public-key": ""}, "skip-cert-verify": false, + "fingerprint": "", "servername": "", "client-fingerprint": "", "alpn": []string{}, + "path": "/", "host": "", "headers": map[string]any{}, "reuse-settings": map[string]any{}, + } + nested := maps.Clone(down) + model.NormalizeXhttpExtra(nested) + xh, _ := nested["xhttpSettings"].(map[string]any) + request := xhttpClashRequestOpts(xh) + for _, k := range []string{"path", "host", "headers", "reuse-settings"} { + if v, ok := request[k]; ok { + ds[k] = v + } + } + security, _ := down["security"].(string) + security = strings.ToLower(security) + ds["tls"] = security == "tls" || security == "reality" + sec, _ := down[security+"Settings"].(map[string]any) + for src, dst := range map[string]string{"serverName": "servername", "fingerprint": "client-fingerprint"} { + if v, ok := sec[src].(string); ok { + ds[dst] = v + } + } + if security == "tls" { + if v, ok := sec["allowInsecure"].(bool); ok { + ds["skip-cert-verify"] = v + } + ds["fingerprint"] = mihomoCertFingerprint(sec["pinnedPeerCertSha256"]) + if alpn := clashStringList(sec["alpn"]); len(alpn) > 0 { + ds["alpn"] = alpn + } + } + if security == "reality" { + if ds["client-fingerprint"] == "" { + ds["client-fingerprint"] = "chrome" + } + key, _ := sec["password"].(string) + if key == "" { + key, _ = sec["publicKey"].(string) + } + sid, _ := sec["shortId"].(string) + ds["reality-opts"] = map[string]any{"public-key": key, "short-id": sid, "support-x25519mlkem768": true} + } + return ds +} + +func xhttpClashRequestOpts(xhttp map[string]any) map[string]any { if xhttp == nil { return nil } @@ -981,10 +1042,10 @@ func buildXhttpClashOpts(xhttp map[string]any) map[string]any { stringFields := []xhttpStringField{ {"xPaddingBytes", "x-padding-bytes", ""}, {"uplinkHTTPMethod", "uplink-http-method", ""}, - {"sessionIDPlacement", "session-id-placement", ""}, - {"sessionIDKey", "session-id-key", ""}, - {"sessionIDTable", "session-id-table", ""}, - {"sessionIDLength", "session-id-length", ""}, + {"sessionIDPlacement", "session-placement", ""}, + {"sessionIDKey", "session-key", ""}, + {"sessionIDTable", "session-table", ""}, + {"sessionIDLength", "session-length", ""}, {"seqPlacement", "seq-placement", ""}, {"seqKey", "seq-key", ""}, {"uplinkDataPlacement", "uplink-data-placement", ""}, @@ -1003,8 +1064,8 @@ func buildXhttpClashOpts(xhttp map[string]any) map[string]any { // Fall back to them so not-yet-resaved configs still map. Mirrors the // frontend migration. for _, f := range []xhttpStringField{ - {"sessionPlacement", "session-id-placement", ""}, - {"sessionKey", "session-id-key", ""}, + {"sessionPlacement", "session-placement", ""}, + {"sessionKey", "session-key", ""}, } { if _, exists := opts[f.dst]; exists { continue @@ -1301,8 +1362,7 @@ func (s *SubClashService) applySecurity(proxy map[string]any, security string, s } func (s *SubClashService) streamData(stream string) map[string]any { - var streamSettings map[string]any - _ = json.Unmarshal([]byte(stream), &streamSettings) + streamSettings := unmarshalStreamSettings(stream) security, _ := streamSettings["security"].(string) switch security { case "tls": diff --git a/internal/sub/clash_service_test.go b/internal/sub/clash_service_test.go index ca9430c4a..ae80a7fe8 100644 --- a/internal/sub/clash_service_test.go +++ b/internal/sub/clash_service_test.go @@ -659,17 +659,17 @@ func TestBuildXhttpClashOpts_FullFieldMapping(t *testing.T) { if opts["uplink-http-method"] != "POST" { t.Errorf("uplink-http-method = %v", opts["uplink-http-method"]) } - if opts["session-id-placement"] != "query" { - t.Errorf("session-id-placement = %v", opts["session-id-placement"]) + if opts["session-placement"] != "query" { + t.Errorf("session-placement = %v", opts["session-placement"]) } - if opts["session-id-key"] != "sess" { - t.Errorf("session-id-key = %v", opts["session-id-key"]) + if opts["session-key"] != "sess" { + t.Errorf("session-key = %v", opts["session-key"]) } - if opts["session-id-table"] != "Base62" { - t.Errorf("session-id-table = %v", opts["session-id-table"]) + if opts["session-table"] != "Base62" { + t.Errorf("session-table = %v", opts["session-table"]) } - if opts["session-id-length"] != "16-32" { - t.Errorf("session-id-length = %v", opts["session-id-length"]) + if opts["session-length"] != "16-32" { + t.Errorf("session-length = %v", opts["session-length"]) } if opts["seq-placement"] != "header" { t.Errorf("seq-placement = %v", opts["seq-placement"]) @@ -1734,3 +1734,24 @@ func TestBuildAmneziaWGProxyForClashProjectsKeepAliveRangeToLowerBound(t *testin t.Fatalf("Clash export emitted invalid legacy keepalive: %v", proxy["persistent-keepalive"]) } } + +func TestWrappedXhttpDownloadExports(t *testing.T) { + raw := `{"network":"xhttp","xhttpSettings":{"path":"/up","extra":{"path":"/ignored","downloadSettings":{"network":"xhttp","address":"down.test","port":9443,"security":"reality","realitySettings":{"serverName":"download.test","password":"client-key","shortId":"1234"},"xhttpSettings":{"path":"/down","extra":{"xmux":{"maxConnections":2}}}}}}}` + stream := unmarshalStreamSettings(raw) + xh := stream["xhttpSettings"].(map[string]any) + if xh["path"] != "/up" || xh["downloadSettings"] == nil { + t.Fatalf("subscription stream: %#v", xh) + } + ds := buildXhttpClashOpts(xh)["download-settings"].(map[string]any) + if ds["server"] != "down.test" || ds["port"] != float64(9443) || ds["path"] != "/down" || ds["tls"] != true || ds["servername"] != "download.test" || ds["reality-opts"].(map[string]any)["public-key"] != "client-key" || ds["reuse-settings"].(map[string]any)["max-connections"] != "2" { + t.Fatalf("download-settings: %#v", ds) + } + listener, _ := model.StripInboundXhttpClientFields(raw) + if strings.Contains(listener, "downloadSettings") || strings.Contains(listener, "ignored") { + t.Fatal(listener) + } + null := unmarshalStreamSettings(`{"network":"xhttp","xhttpSettings":{"extra":null,"downloadSettings":{"port":443}}}`) + if null["xhttpSettings"].(map[string]any)["downloadSettings"] != nil { + t.Fatal(null) + } +} diff --git a/internal/sub/json_service.go b/internal/sub/json_service.go index 99a72c269..1cee3ca3a 100644 --- a/internal/sub/json_service.go +++ b/internal/sub/json_service.go @@ -817,8 +817,8 @@ func (s *SubJsonService) getConfig(subReq *SubService, inbound *model.Inbound, c } func (s *SubJsonService) streamData(stream string, clientKey string) map[string]any { - var streamSettings map[string]any - if err := json.Unmarshal([]byte(stream), &streamSettings); err != nil || streamSettings == nil { + streamSettings := unmarshalStreamSettings(stream) + if streamSettings == nil { streamSettings = map[string]any{} } security, _ := streamSettings["security"].(string) diff --git a/internal/sub/service.go b/internal/sub/service.go index a0d79a6f8..e021cf656 100644 --- a/internal/sub/service.go +++ b/internal/sub/service.go @@ -1923,6 +1923,7 @@ func findClientIndex(clients []model.Client, email string) int { func unmarshalStreamSettings(streamSettings string) map[string]any { var stream map[string]any _ = json.Unmarshal([]byte(streamSettings), &stream) + model.NormalizeXhttpExtra(stream) return stream } diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index 519bdfee8..dbe4bc2ae 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -667,6 +667,7 @@ func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) { inbound.StreamSettings = canonicalizeStreamNetworkKey(inbound.StreamSettings) inbound.StreamSettings = canonicalizeLegacyXdnsMasks(inbound.StreamSettings) inbound.StreamSettings = canonicalizeXDriveService(inbound.StreamSettings) + inbound.StreamSettings = syncXhttpDownloadRequestShape(inbound.StreamSettings) } // canonicalizeLegacyXdnsMasks stores an xdns mask posted in a pre-26.10.10 shape in @@ -716,6 +717,9 @@ func canonicalizeStreamNetworkKey(streamSettings string) string { // validateInboundBuildInput refuses what xray-core's in-process build would expand without // bound; certificate paths are checked only where this host is the one opening them. func validateInboundBuildInput(inbound *model.Inbound) error { + if err := validateXhttpDownload(inbound.StreamSettings); err != nil { + return err + } if err := xray.CheckStreamBuildCost([]byte(inbound.StreamSettings)); err != nil { return err } diff --git a/internal/web/service/inbound_xhttp.go b/internal/web/service/inbound_xhttp.go new file mode 100644 index 000000000..6aca52d11 --- /dev/null +++ b/internal/web/service/inbound_xhttp.go @@ -0,0 +1,155 @@ +package service + +import ( + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "reflect" + "strings" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + + xtls "github.com/xtls/xray-core/transport/internet/tls" +) + +// The server config strips downloadSettings, so building the listener cannot +// detect an unusable client leg. Validate it before persisting the inbound. +func validateXhttpDownload(raw string) error { + var stream map[string]any + if json.Unmarshal([]byte(raw), &stream) != nil || stream["network"] != "xhttp" { + return nil + } + model.NormalizeXhttpExtra(stream) + xh, _ := stream["xhttpSettings"].(map[string]any) + if xh["downloadSettings"] == nil { + return nil + } + down, ok := xh["downloadSettings"].(map[string]any) + if !ok { + return errors.New("downloadSettings must be an object") + } + if xh["mode"] == "stream-one" { + return errors.New("downloadSettings is incompatible with stream-one") + } + network, _ := down["network"].(string) + if down["method"] != nil { + network, _ = down["method"].(string) + } + if !strings.EqualFold(network, "xhttp") && !strings.EqualFold(network, "splithttp") { + return errors.New("downloadSettings.network must be xhttp") + } + if address, _ := down["address"].(string); strings.TrimSpace(address) == "" { + return errors.New("downloadSettings.address is required") + } + if port, ok := down["port"].(float64); !ok || port < 1 || port > 65535 || float64(int(port)) != port { + return errors.New("downloadSettings.port must be an integer from 1 to 65535") + } + security, ok := down["security"].(string) + if !ok && down["security"] != nil { + return errors.New("downloadSettings.security must be a string") + } + switch strings.ToLower(security) { + case "", "none": + case "tls": + t, _ := down["tlsSettings"].(map[string]any) + if err := checkXhttpDownloadFingerprint(t, "tlsSettings", true); err != nil { + return err + } + case "reality": + r, _ := down["realitySettings"].(map[string]any) + if err := checkXhttpDownloadFingerprint(r, "realitySettings", false); err != nil { + return err + } + key, _ := r["password"].(string) + if key == "" { + key, _ = r["publicKey"].(string) + } + if decoded, err := base64.RawURLEncoding.DecodeString(key); err != nil || len(decoded) != 32 { + return errors.New("downloadSettings.realitySettings.password or publicKey must encode 32 bytes as unpadded base64url") + } + if v := r["shortId"]; v != nil { + shortID, ok := v.(string) + if !ok || len(shortID) > 16 { + return errors.New("downloadSettings.realitySettings.shortId must encode at most 8 hexadecimal bytes") + } + if _, err := hex.DecodeString(shortID); err != nil { + return errors.New("downloadSettings.realitySettings.shortId must encode at most 8 hexadecimal bytes") + } + } + default: + return errors.New("downloadSettings.security must be none, tls or reality") + } + return nil +} + +// checkXhttpDownloadFingerprint applies the core's client-side rule: an unknown uTLS name, +// or one REALITY refuses, fails the build of every client that imports the link. +func checkXhttpDownloadFingerprint(settings map[string]any, block string, allowUnsafe bool) error { + raw, has := settings["fingerprint"] + if !has || raw == nil { + return nil + } + name, ok := raw.(string) + name = strings.ToLower(name) + insecure := name == "unsafe" || name == "hellogolang" + switch { + case !ok, insecure && !allowUnsafe, name != "unsafe" && xtls.GetFingerprint(name) == nil: + return errors.New("downloadSettings." + block + ".fingerprint is not a uTLS fingerprint this security accepts") + } + return nil +} + +// What the listener reads from every request with its own config, the download GET included. +var xhttpListenerCheckedKeys = []string{ + "sessionIDPlacement", "sessionIDKey", "sessionIDTable", "sessionIDLength", + "seqPlacement", "seqKey", + "xPaddingBytes", "xPaddingObfsMode", "xPaddingKey", "xPaddingHeader", "xPaddingPlacement", "xPaddingMethod", +} + +// syncXhttpDownloadRequestShape makes the download leg carry the inbound's own session and +// padding rules, so an edit of the inbound cannot leave a saved leg the listener rejects. +func syncXhttpDownloadRequestShape(streamSettings string) string { + var stream map[string]any + if json.Unmarshal([]byte(streamSettings), &stream) != nil || stream["network"] != "xhttp" { + return streamSettings + } + upload, _ := stream["xhttpSettings"].(map[string]any) + if extra, ok := upload["extra"].(map[string]any); ok { + upload = extra + } + down, ok := upload["downloadSettings"].(map[string]any) + if !ok { + return streamSettings + } + leg, _ := down["xhttpSettings"].(map[string]any) + if extra, ok := leg["extra"].(map[string]any); ok { + leg = extra + } + if leg == nil { + leg = map[string]any{} + down["xhttpSettings"] = leg + } + changed := false + for _, key := range xhttpListenerCheckedKeys { + want, has := upload[key] + got, had := leg[key] + if has == had && reflect.DeepEqual(want, got) { + continue + } + if has { + leg[key] = want + } else { + delete(leg, key) + } + changed = true + } + if !changed { + return streamSettings + } + out, err := json.MarshalIndent(stream, "", " ") + if err != nil { + return streamSettings + } + return string(out) +} diff --git a/internal/web/service/inbound_xhttp_test.go b/internal/web/service/inbound_xhttp_test.go new file mode 100644 index 000000000..02f20d351 --- /dev/null +++ b/internal/web/service/inbound_xhttp_test.go @@ -0,0 +1,59 @@ +package service + +import ( + "encoding/json" + "reflect" + "strings" + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func TestValidateXhttpDownload(t *testing.T) { + const valid = `{"network":"xhttp","xhttpSettings":{"mode":"packet-up","extra":{"downloadSettings":{"network":"xhttp","address":"down.test","port":443,"security":"reality","realitySettings":{"password":"AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE","shortId":"abcd"}}}}}` + for _, tc := range []struct{ from, to, field string }{ + {"packet-up", "packet-up", ""}, + {"packet-up", "stream-one", "stream-one"}, + {`"network":"xhttp","address"`, `"network":"tcp","address"`, "network"}, + {"AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "abc", "password"}, + {"abcd", "f", "shortId"}, + {`"shortId":"abcd"`, `"shortId":"abcd","fingerprint":"Chrome"`, ""}, + {`"shortId":"abcd"`, `"shortId":"abcd","fingerprint":"chorme"`, "fingerprint"}, + {`"shortId":"abcd"`, `"shortId":"abcd","fingerprint":"unsafe"`, "fingerprint"}, + {`"security":"reality","realitySettings"`, `"security":"tls","tlsSettings":{"fingerprint":"chorme"},"realitySettings"`, "fingerprint"}, + {`"security":"reality","realitySettings"`, `"security":"tls","tlsSettings":{"fingerprint":"firefox"},"realitySettings"`, ""}, + } { + err := validateXhttpDownload(strings.Replace(valid, tc.from, tc.to, 1)) + if tc.field == "" && err != nil || tc.field != "" && (err == nil || !strings.Contains(err.Error(), tc.field)) { + t.Fatalf("%s: %v", tc.to, err) + } + } +} + +// The listener matches a download GET against its own session and padding rules, so a leg +// saved before the inbound's rules changed must not keep the old ones. +func TestNormalizeStreamSettingsSyncsXhttpDownloadRequestShape(t *testing.T) { + inbound := &model.Inbound{Protocol: model.VLESS, StreamSettings: `{"network":"xhttp","xhttpSettings":{ + "path":"/up","sessionIDPlacement":"query","sessionIDKey":"sid","xPaddingBytes":"100-200", + "downloadSettings":{"network":"xhttp","address":"down.test","port":443,"security":"tls", + "xhttpSettings":{"path":"/down","host":"cdn.test","sessionIDPlacement":"path","seqKey":"stale"}}}}`} + (&InboundService{}).normalizeStreamSettings(inbound) + + var stream struct { + XhttpSettings struct { + DownloadSettings struct { + XhttpSettings map[string]any `json:"xhttpSettings"` + } `json:"downloadSettings"` + } `json:"xhttpSettings"` + } + if err := json.Unmarshal([]byte(inbound.StreamSettings), &stream); err != nil { + t.Fatal(err) + } + want := map[string]any{ + "path": "/down", "host": "cdn.test", + "sessionIDPlacement": "query", "sessionIDKey": "sid", "xPaddingBytes": "100-200", + } + if got := stream.XhttpSettings.DownloadSettings.XhttpSettings; !reflect.DeepEqual(got, want) { + t.Fatalf("download leg xhttpSettings = %v, want %v", got, want) + } +} diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index 866e45679..9922dbf56 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -559,6 +559,7 @@ "streamUpServer": "Stream-Up Server", "serverMaxHeaderBytes": "أقصى بايت ترويسة الخادم", "paddingBytes": "بايتات Padding", + "separateDownload": "استخدام قناة تنزيل منفصلة", "uplinkHttpMethod": "Uplink HTTP method", "paddingObfsMode": "وضع تشويش Padding", "paddingKey": "Padding Key", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index ea640c17c..f4780da9b 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -561,6 +561,7 @@ "streamUpServer": "Stream-Up Server", "serverMaxHeaderBytes": "Server Max Header Bytes", "paddingBytes": "Padding Bytes", + "separateDownload": "Use separate download", "uplinkHttpMethod": "Uplink HTTP Method", "paddingObfsMode": "Padding Obfs Mode", "paddingKey": "Padding Key", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index 3fc96bc6a..4b3f1a28c 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -559,6 +559,7 @@ "streamUpServer": "Stream-Up Server", "serverMaxHeaderBytes": "Máx. bytes cabecera servidor", "paddingBytes": "Bytes de Padding", + "separateDownload": "Usar un canal de descarga separado", "uplinkHttpMethod": "Método HTTP Uplink", "paddingObfsMode": "Modo obfs de Padding", "paddingKey": "Padding Key", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index d720b859d..e5540eec4 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -559,6 +559,7 @@ "streamUpServer": "سرور Stream-Up", "serverMaxHeaderBytes": "حداکثر بایت هدر سرور", "paddingBytes": "بایت‌های Padding", + "separateDownload": "استفاده از مسیر دانلود جداگانه", "uplinkHttpMethod": "متد HTTP آپلینک", "paddingObfsMode": "حالت ابهام Padding", "paddingKey": "کلید Padding", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 8c16ea0ed..8289a43e8 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -559,6 +559,7 @@ "streamUpServer": "Stream-Up Server", "serverMaxHeaderBytes": "Maks. byte header server", "paddingBytes": "Byte Padding", + "separateDownload": "Gunakan jalur unduh terpisah", "uplinkHttpMethod": "Metode HTTP Uplink", "paddingObfsMode": "Mode obfs Padding", "paddingKey": "Padding Key", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index cf3eff81f..767414a3d 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -610,6 +610,7 @@ "streamUpServer": "Stream-Up Server", "serverMaxHeaderBytes": "サーバー最大ヘッダーバイト", "paddingBytes": "Padding バイト", + "separateDownload": "ダウンロードに別の経路を使用", "uplinkHttpMethod": "Uplink HTTP メソッド", "paddingObfsMode": "Padding 難読化モード", "paddingKey": "Padding Key", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index d6920b2fa..e16575fac 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -610,6 +610,7 @@ "streamUpServer": "Stream-Up Server", "serverMaxHeaderBytes": "Máx. bytes cabeçalho servidor", "paddingBytes": "Bytes de Padding", + "separateDownload": "Usar canal de download separado", "uplinkHttpMethod": "Método HTTP Uplink", "paddingObfsMode": "Modo obfs de Padding", "paddingKey": "Padding Key", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index c68137941..44be3bb75 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -612,6 +612,7 @@ "streamUpServer": "Stream-Up Server", "serverMaxHeaderBytes": "Server Max Header Bytes", "paddingBytes": "Padding Bytes", + "separateDownload": "Использовать отдельный канал загрузки", "uplinkHttpMethod": "HTTP-метод Uplink", "paddingObfsMode": "Padding Obfs Mode", "paddingKey": "Padding Key", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index b36bc8255..a8cae46ed 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -561,6 +561,7 @@ "streamUpServer": "Server na odosielanie dát", "serverMaxHeaderBytes": "Najväčšia veľkosť hlavičiek servera", "paddingBytes": "Počet bajtov výplne", + "separateDownload": "Použiť samostatný kanál na sťahovanie", "uplinkHttpMethod": "Metóda HTTP pri odosielaní", "paddingObfsMode": "Režim maskovania výplne", "paddingKey": "Kľúč výplne", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index 2b72e6df1..844b7bf81 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -559,6 +559,7 @@ "streamUpServer": "Stream-Up Sunucusu", "serverMaxHeaderBytes": "Sunucu Maks. Başlık Byte'ı", "paddingBytes": "Dolgu (Padding) Byte'ı", + "separateDownload": "Ayrı indirme kanalı kullan", "uplinkHttpMethod": "Uplink HTTP Yöntemi", "paddingObfsMode": "Dolgu (Padding) Obfs Modu", "paddingKey": "Dolgu (Padding) Anahtarı", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index b9b5006ae..46799c19d 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -559,6 +559,7 @@ "streamUpServer": "Stream-Up Server", "serverMaxHeaderBytes": "Server Max Header Bytes", "paddingBytes": "Padding Bytes", + "separateDownload": "Використовувати окремий канал завантаження", "uplinkHttpMethod": "HTTP-метод Uplink", "paddingObfsMode": "Padding Obfs Mode", "paddingKey": "Padding Key", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index b82d63ebf..e1e1ada89 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -610,6 +610,7 @@ "streamUpServer": "Stream-Up Server", "serverMaxHeaderBytes": "Byte header máy chủ tối đa", "paddingBytes": "Byte Padding", + "separateDownload": "Dùng kênh tải xuống riêng", "uplinkHttpMethod": "Uplink HTTP method", "paddingObfsMode": "Chế độ obfs Padding", "paddingKey": "Padding Key", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index 7e32439d1..0b539e421 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -609,6 +609,7 @@ "streamUpServer": "Stream-Up 服务器", "serverMaxHeaderBytes": "服务器最大头字节", "paddingBytes": "Padding 字节", + "separateDownload": "使用独立下载通道", "uplinkHttpMethod": "Uplink HTTP 方法", "paddingObfsMode": "Padding 混淆模式", "paddingKey": "Padding Key", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index 2563d5f4d..f416c5745 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -559,6 +559,7 @@ "streamUpServer": "Stream-Up 伺服器", "serverMaxHeaderBytes": "伺服器最大標頭位元組", "paddingBytes": "Padding 位元組", + "separateDownload": "使用獨立下載通道", "uplinkHttpMethod": "Uplink HTTP 方法", "paddingObfsMode": "Padding 混淆模式", "paddingKey": "Padding Key",