fix(finalmask): hop client UDP through the udphop mask

xray-core 26.9.9 dropped finalmask.quicParams.udpHop for the client-only
"udphop" UDP mask {mode, interval, remoteIPs, remotePorts}. The panel kept
writing the old key, so hysteria/xhttp outbounds and JSON-subscription
clients silently stopped hopping ports.

An inbound keeps quicParams.udpHop: it is panel metadata advertised as the
link's mport, and a udphop mask on a listener fails with "udphop: client
only". The conversion (maskcompat.UpgradeLegacyUDPHop, intervalRemote mode)
runs only where a client config is produced:

- UDPHopClientMaskFix seeder over hosts, sub-JSON finalmask, cached
  outbound-subscription outbounds and template outbounds (never inbounds);
- GetXrayConfig heals template outbounds at build time;
- the JSON subscription upgrades each generated client stream;
- the Go and frontend link importers upgrade a legacy fm= param.

The finalmask editor gains a side prop: the client side lifts the dead key
on mount and offers a udphop mask editor (also for xhttp's HTTP/3 dial);
the inbound side keeps the UDP Hop switch, labelled as advertised.
This commit is contained in:
MHSanaei
2026-10-11 11:20:34 +02:00
parent 00aaef386f
commit ec0a57fc4f
22 changed files with 797 additions and 51 deletions
@@ -10,6 +10,7 @@ interface FinalMaskFieldProps {
network: string;
protocol: string;
showAll?: boolean;
side?: 'server' | 'client';
}
const EMPTY: FinalMaskStreamSettings = { tcp: [], udp: [] };
@@ -20,6 +21,7 @@ export default function FinalMaskField({
network,
protocol,
showAll,
side,
}: FinalMaskFieldProps) {
const [form] = Form.useForm();
const [initial] = useState(() => value ?? EMPTY);
@@ -55,6 +57,7 @@ export default function FinalMaskField({
protocol={protocol}
form={form}
showAll={showAll}
side={side}
/>
</Form>
);
@@ -18,6 +18,7 @@ import type { NamePath } from 'antd/es/form/interface';
import { RandomUtil } from '@/utils';
import { activateOnKey } from '@/utils/a11y';
import { OutboundProtocols, UTLS_FINGERPRINT } from '@/schemas/primitives';
import { upgradeLegacyUdpHop } from '@/lib/xray/udphop-mask';
import { upgradeLegacyXdnsMasks, XDNS_LEGACY_EDNS0 } from '@/lib/xray/xdns-mask';
const UTLS_FINGERPRINT_OPTIONS = Object.values(UTLS_FINGERPRINT).map((value) => ({
@@ -34,6 +35,9 @@ export interface FinalMaskFormProps {
// network/protocol. Used by the global sub-JSON finalmask editor where
// the masks apply to every stream rather than one specific transport.
showAll?: boolean;
// udphop runs only on the dialing side (the core refuses it on a listener), so a server
// keeps the advertised hop range in quicParams.udpHop and a client gets the mask.
side?: 'server' | 'client';
}
const TCP_NETWORKS = ['raw', 'tcp', 'httpupgrade', 'ws', 'grpc', 'xhttp', 'xdrive'];
@@ -194,6 +198,8 @@ function defaultUdpMaskSettings(type: string): Record<string, unknown> {
return { client: [], server: [] };
case 'noise':
return { reset: 0, noise: [] };
case 'udphop':
return { mode: 'intervalRemote', interval: '5-10', remotePorts: '' };
default:
return {};
}
@@ -242,6 +248,7 @@ export default function FinalMaskForm({
protocol,
form,
showAll = false,
side = 'client',
}: FinalMaskFormProps) {
const base = asPath(name);
@@ -273,6 +280,13 @@ export default function FinalMaskForm({
const { next, changed } = upgradeLegacyXdnsMasks(udp);
if (changed) form.setFieldValue([...base, 'udp'], next);
}
if (side === 'client') {
const finalmask = form.getFieldValue(base) as Record<string, unknown> | undefined;
if (finalmask && typeof finalmask === 'object') {
const { next, changed } = upgradeLegacyUdpHop(finalmask);
if (changed) form.setFieldValue(base, next);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
@@ -282,7 +296,13 @@ export default function FinalMaskForm({
// wrap anything even though the leftover network value may be 'tcp'.
const isWireguard = protocol === 'wireguard';
const showTcp = showAll || (!isWireguard && TCP_NETWORKS.includes(network));
const showUdp = showAll || isHysteria || isWireguard || network === 'kcp';
// xhttp's HTTP/3 dial runs the UDP masks too, which is where a client's udphop lives.
const showUdp =
showAll ||
isHysteria ||
isWireguard ||
network === 'kcp' ||
(side === 'client' && network === 'xhttp');
const showQuic = showAll || isHysteria || network === 'xhttp';
const quicParams = Form.useWatch([...base, 'quicParams'], { form, preserve: true });
const hasQuicParams = quicParams != null;
@@ -299,6 +319,7 @@ export default function FinalMaskForm({
isHysteria={isHysteria}
isWireguard={isWireguard}
network={network}
allowUdpHop={side === 'client'}
/>
)}
{showQuic && (
@@ -311,7 +332,13 @@ export default function FinalMaskForm({
}}
/>
</Form.Item>
{hasQuicParams && <QuicParamsForm base={[...base, 'quicParams']} form={form} />}
{hasQuicParams && (
<QuicParamsForm
base={[...base, 'quicParams']}
form={form}
showUdpHop={side === 'server'}
/>
)}
</>
)}
</>
@@ -820,12 +847,14 @@ function UdpMasksList({
isHysteria,
isWireguard,
network,
allowUdpHop,
}: {
base: (string | number)[];
form: FormInstance;
isHysteria: boolean;
isWireguard: boolean;
network: string;
allowUdpHop: boolean;
}) {
const { t } = useTranslation();
return (
@@ -854,6 +883,7 @@ function UdpMasksList({
isHysteria={isHysteria}
isWireguard={isWireguard}
network={network}
allowUdpHop={allowUdpHop}
onRemove={() => remove(field.name)}
/>
))}
@@ -871,6 +901,7 @@ function UdpMaskItem({
isHysteria,
isWireguard,
network,
allowUdpHop,
onRemove,
}: {
fieldName: number;
@@ -880,6 +911,7 @@ function UdpMaskItem({
isHysteria: boolean;
isWireguard: boolean;
network: string;
allowUdpHop: boolean;
onRemove: () => void;
}) {
const absolutePath = [...listPath, fieldName];
@@ -893,8 +925,9 @@ function UdpMaskItem({
}
};
const udpHopOption = allowUdpHop ? [{ value: 'udphop', label: 'UDP Hop' }] : [];
const options = isHysteria
? [{ value: 'salamander', label: 'Salamander (Hysteria2)' }]
? [{ value: 'salamander', label: 'Salamander (Hysteria2)' }, ...udpHopOption]
: [
// Salamander is the mask xray-core's own wireguard finalmask example
// uses; it stays hysteria-only elsewhere to keep legacy parity.
@@ -905,6 +938,7 @@ function UdpMaskItem({
{ value: 'realm', label: 'Realm' },
{ value: 'header-custom', label: 'Header Custom' },
{ value: 'noise', label: 'Noise' },
...udpHopOption,
];
return (
@@ -967,6 +1001,9 @@ function UdpMaskItem({
if (type === 'xdns') {
return <XdnsSettings udpFieldName={fieldName} />;
}
if (type === 'udphop') {
return <UdpHopSettings udpFieldName={fieldName} />;
}
if (type === 'xicmp') {
return (
<>
@@ -1366,6 +1403,66 @@ function XdnsSettings({ udpFieldName }: { udpFieldName: number }) {
);
}
const UDP_HOP_MODES = [
{ value: 'intervalRemote', label: 'Rotate server port (interval)' },
{ value: 'perConnRemote', label: 'Random server port per connection' },
{ value: 'intervalLocal', label: 'Rotate local port (interval)' },
];
// xray-core lowercases each comma-separated mode, so a lowercase one (from an mport
// import) still maps onto its option here.
function udpHopModesFromWire(value: unknown): string[] {
if (typeof value !== 'string') return [];
return value
.split(',')
.map((mode) => mode.trim())
.filter(Boolean)
.map(
(mode) =>
UDP_HOP_MODES.find((m) => m.value.toLowerCase() === mode.toLowerCase())?.value ?? mode,
);
}
function validateUdpHopInterval(_: unknown, value: unknown) {
if (value == null || value === '') return Promise.resolve();
const bounds = String(value)
.split('-')
.map((v) => Number(v.trim()));
const valid = bounds.length <= 2 && bounds.every((v) => Number.isInteger(v) && v >= 5);
return valid ? Promise.resolve() : Promise.reject(new Error('seconds ≥ 5, e.g. 30 or 5-10'));
}
// Client-only hopping (xray-core 26.9.9); every key needs a registered field because the
// finalmask watch drops keys without one.
function UdpHopSettings({ udpFieldName }: { udpFieldName: number }) {
return (
<>
<Form.Item
label="Mode"
name={[udpFieldName, 'settings', 'mode']}
getValueProps={(value) => ({ value: udpHopModesFromWire(value) })}
normalize={(value: string[]) => value.join(',')}
rules={[{ required: true, message: 'pick at least one mode' }]}
>
<Select mode="multiple" options={UDP_HOP_MODES} />
</Form.Item>
<Form.Item
label="Interval (s)"
name={[udpFieldName, 'settings', 'interval']}
rules={[{ validator: validateUdpHopInterval }]}
>
<Input placeholder="30 or 5-10" />
</Form.Item>
<Form.Item label="Remote Ports" name={[udpFieldName, 'settings', 'remotePorts']}>
<Input placeholder="20000-50000" />
</Form.Item>
<Form.Item label="Remote IPs" name={[udpFieldName, 'settings', 'remoteIPs']}>
<Select mode="tags" style={{ width: '100%' }} tokenSeparators={[',', ' ']} />
</Form.Item>
</>
);
}
function NoiseItems({
udpFieldName,
form,
@@ -1542,7 +1639,15 @@ function ItemEditor({
);
}
function QuicParamsForm({ base, form }: { base: (string | number)[]; form: FormInstance }) {
function QuicParamsForm({
base,
form,
showUdpHop,
}: {
base: (string | number)[];
form: FormInstance;
showUdpHop: boolean;
}) {
const congestion = Form.useWatch([...base, 'congestion'], form) as string | undefined;
const udpHop = Form.useWatch([...base, 'udpHop'], { form, preserve: true }) as
| Record<string, unknown>
@@ -1596,22 +1701,31 @@ function QuicParamsForm({ base, form }: { base: (string | number)[]; form: FormI
</>
)}
<Form.Item label="UDP Hop">
<Switch
checked={hasUdpHop}
onChange={(v) => {
form.setFieldValue([...base, 'udpHop'], v ? defaultUdpHop() : undefined);
}}
/>
</Form.Item>
{hasUdpHop && (
{/* Advertised to clients (link mport, JSON-subscription udphop mask); the server
itself listens on its own port. */}
{showUdpHop && (
<>
<Form.Item label="Hop Ports" name={[...base, 'udpHop', 'ports']}>
<Input placeholder="e.g. 20000-50000" />
</Form.Item>
<Form.Item label="Hop Interval (s)" name={[...base, 'udpHop', 'interval']}>
<Input placeholder="e.g. 5-10" />
<Form.Item
label="UDP Hop"
tooltip="Advertised to clients as a hop range; the server listens on its own port only"
>
<Switch
checked={hasUdpHop}
onChange={(v) => {
form.setFieldValue([...base, 'udpHop'], v ? defaultUdpHop() : undefined);
}}
/>
</Form.Item>
{hasUdpHop && (
<>
<Form.Item label="Hop Ports" name={[...base, 'udpHop', 'ports']}>
<Input placeholder="e.g. 20000-50000" />
</Form.Item>
<Form.Item label="Hop Interval (s)" name={[...base, 'udpHop', 'interval']}>
<Input placeholder="e.g. 5-10" />
</Form.Item>
</>
)}
</>
)}
@@ -1,5 +1,6 @@
import { Base64 } from '@/utils';
import { upgradeLegacyUdpHop } from './udphop-mask';
import { upgradeLegacyXdnsMasks } from './xdns-mask';
// Focused share-link parser for the OutboundFormModal's link-import
@@ -272,8 +273,8 @@ const kcpHeaderTypeToMask: Record<string, string> = {
};
// The inbound link emits the entire finalmask object as a JSON-encoded
// `fm` query param. Decode and attach to streamSettings so udpHop /
// quicParams / tcp+udp masks round-trip on outbound import.
// `fm` query param. Decode and attach to streamSettings so quicParams and the
// tcp+udp masks round-trip on outbound import; a legacy udpHop becomes the mask.
function applyFinalMaskParam(stream: Raw, params: URLSearchParams): void {
const fm = params.get('fm');
if (fm) {
@@ -282,7 +283,7 @@ function applyFinalMaskParam(stream: Raw, params: URLSearchParams): void {
if (parsed && typeof parsed === 'object') {
sanitizeFinalMaskQuicParams(parsed);
if (Array.isArray(parsed.udp)) parsed.udp = upgradeLegacyXdnsMasks(parsed.udp).next;
stream.finalmask = parsed;
stream.finalmask = upgradeLegacyUdpHop(parsed).next;
}
} catch {
// malformed fm — leave streamSettings.finalmask absent
+29
View File
@@ -0,0 +1,29 @@
type Raw = Record<string, unknown>;
function isEmptyHopValue(value: unknown): boolean {
return value == null || value === 0 || (typeof value === 'string' && value.trim() === '');
}
// xray-core 26.9.9 hops a client only through the "udphop" UDP mask. Mirrors
// internal/util/maskcompat: quicParams.udpHop becomes an intervalRemote mask.
export function upgradeLegacyUdpHop(finalmask: Raw): { next: Raw; changed: boolean } {
const quicParams = finalmask.quicParams;
if (!quicParams || typeof quicParams !== 'object' || !('udpHop' in quicParams)) {
return { next: finalmask, changed: false };
}
const { udpHop, ...restQuic } = quicParams as Raw;
const next: Raw = { ...finalmask };
if (Object.keys(restQuic).length > 0) next.quicParams = restQuic;
else delete next.quicParams;
const hop = (udpHop && typeof udpHop === 'object' ? udpHop : {}) as Raw;
const udp = Array.isArray(finalmask.udp) ? [...(finalmask.udp as unknown[])] : [];
const hasMask = udp.some((m) => String((m as Raw | null)?.type ?? '').toLowerCase() === 'udphop');
if (!isEmptyHopValue(hop.ports) && !hasMask) {
const settings: Raw = { mode: 'intervalRemote', remotePorts: hop.ports };
if (!isEmptyHopValue(hop.interval)) settings.interval = hop.interval;
udp.push({ type: 'udphop', settings });
next.udp = udp;
}
return { next, changed: true };
}
@@ -998,6 +998,7 @@ export default function InboundFormModal({
onChange={field.onChange}
network={network}
protocol={protocol}
side="server"
/>
)}
/>
@@ -417,6 +417,56 @@ describe('InboundFormModal', () => {
});
});
// xray-core refuses a udphop mask on a listener ("client only"), so an inbound keeps its
// advertised hop range in quicParams.udpHop: the client-side lift must not run here.
it('keeps an inbound hop range in quicParams.udpHop on save', async () => {
const post = vi.mocked(HttpUtil.post);
post.mockClear();
const hysteria = new DBInbound({
id: 43,
port: 443,
listen: '',
protocol: 'hysteria',
remark: 'hy',
enable: true,
settings: { version: 2, clients: [] },
streamSettings: {
network: 'hysteria',
security: 'tls',
hysteriaSettings: { version: 2, auth: '', udpIdleTimeout: 60 },
tlsSettings: {
serverName: 'hy.example.com',
alpn: ['h3'],
certificates: [
{ certificateFile: '/etc/ssl/certs/hy.crt', keyFile: '/etc/ssl/private/hy.key' },
],
},
finalmask: { quicParams: { udpHop: { ports: '20000-30000', interval: '5-10' } } },
},
sniffing: { enabled: false },
nodeId: null,
shareAddrStrategy: 'listen',
shareAddr: '',
});
renderCloneLikeEdit(hysteria);
// Form watches flush in a macrotask; save only once the hop fields have emitted.
await screen.findByDisplayValue('20000-30000');
await act(async () => {
await new Promise((r) => setTimeout(r, 0));
});
fireEvent.click(primaryButton());
const isUpdate = ([url]: unknown[]) => url === '/panel/api/inbounds/update/43';
await waitFor(() => expect(post.mock.calls.some(isUpdate)).toBe(true));
const payload = post.mock.calls.find(isUpdate)![1] as { streamSettings: string };
const finalmask = JSON.parse(payload.streamSettings).finalmask as Record<string, unknown>;
expect(finalmask.quicParams).toMatchObject({
udpHop: { ports: '20000-30000', interval: '5-10' },
});
expect(JSON.stringify(finalmask.udp ?? [])).not.toContain('udphop');
});
// Clients and enable change through their own endpoints; the server keeps the
// stored ones, so the edit form must neither send nor validate its stale copy.
it('edit save neither sends nor validates the clients it loaded', async () => {
@@ -452,3 +452,67 @@ describe('OutboundFormModal MASQUE', () => {
expect(payload.streamSettings.masqueSettings.pass).toBeUndefined();
});
});
describe('OutboundFormModal UDP hop', () => {
// xray-core 26.9.9 ignores quicParams.udpHop; a client hops only through the udphop
// mask, so the editor must lift the dead key and keep every mask field on save.
it('saves a legacy quicParams.udpHop hysteria outbound as a udphop mask', async () => {
const onConfirm = vi.fn();
const queryClient = makeTestQueryClient();
const outbound = {
protocol: 'hysteria',
tag: 'hy-out',
settings: { address: 'hy.example.com', port: 443, version: 2 },
streamSettings: {
network: 'hysteria',
security: 'tls',
hysteriaSettings: { version: 2, auth: 'a', udpIdleTimeout: 60 },
tlsSettings: { serverName: 'hy.example.com', alpn: ['h3'] },
finalmask: {
udp: [{ type: 'salamander', settings: { password: 'p' } }],
quicParams: { congestion: 'bbr', udpHop: { ports: '20000-30000', interval: '5-10' } },
},
},
};
const tree = (open: boolean) => (
<QueryClientProvider client={queryClient}>
<ThemeProvider>
<OutboundFormModal
open={open}
outbound={outbound}
existingTags={[]}
onClose={() => {}}
onConfirm={onConfirm}
/>
</ThemeProvider>
</QueryClientProvider>
);
const { rerender } = render(tree(false));
rerender(tree(true));
await act(async () => {
await new Promise((r) => setTimeout(r, 0));
});
const ok = document.querySelector('.ant-modal-footer .ant-btn-primary') as HTMLElement;
await act(async () => {
fireEvent.click(ok);
});
await act(async () => {
await new Promise((r) => setTimeout(r, 0));
});
expect(onConfirm).toHaveBeenCalledTimes(1);
const payload = onConfirm.mock.calls[0][0] as {
streamSettings: { finalmask: { udp: unknown[]; quicParams?: Record<string, unknown> } };
};
expect(payload.streamSettings.finalmask.udp).toEqual([
{ type: 'salamander', settings: { password: 'p' } },
{
type: 'udphop',
settings: { mode: 'intervalRemote', remotePorts: '20000-30000', interval: '5-10' },
},
]);
expect(payload.streamSettings.finalmask.quicParams?.udpHop).toBeUndefined();
expect(payload.streamSettings.finalmask.quicParams?.congestion).toBe('bbr');
});
});
+27 -2
View File
@@ -488,6 +488,25 @@ describe('parseShadowsocksLink', () => {
});
describe('parseHysteria2Link', () => {
// A panel older than the 26.9.9 core shares its hop range as quicParams.udpHop in fm=,
// which the core ignores; the import must hand it the udphop mask instead.
it('upgrades a legacy fm= quicParams.udpHop to the udphop mask', () => {
const fm = encodeURIComponent(
JSON.stringify({ quicParams: { udpHop: { ports: '20000-30000', interval: '5-10' } } }),
);
const out = parseHysteria2Link(
`hysteria2://auth@hy.example.com:443?sni=hy.example.com&fm=${fm}#hy`,
);
expect((out!.streamSettings as Record<string, unknown>).finalmask).toEqual({
udp: [
{
type: 'udphop',
settings: { mode: 'intervalRemote', remotePorts: '20000-30000', interval: '5-10' },
},
],
});
});
it('parses a hysteria2:// link with sni', () => {
const link = 'hysteria2://auth-secret@srv.example:443?sni=example.com#imported-hy2';
const out = parseHysteria2Link(link);
@@ -822,8 +841,14 @@ describe('parseVlessLink — extra / fm / x_padding_bytes (B20)', () => {
const quicParams = finalmask.quicParams as Record<string, unknown>;
expect(quicParams.congestion).toBe('bbr');
expect(quicParams.maxIdleTimeout).toBe(30);
expect((quicParams.udpHop as Record<string, unknown>).interval).toBe('5-10');
expect((quicParams.udpHop as Record<string, unknown>).ports).toBe('20000-50000');
// xray-core 26.9.9 ignores quicParams.udpHop; the import moves it to the udphop mask.
expect(quicParams.udpHop).toBeUndefined();
expect(finalmask.udp).toEqual([
{
type: 'udphop',
settings: { mode: 'intervalRemote', remotePorts: '20000-50000', interval: '5-10' },
},
]);
});
it('falls back to x_padding_bytes when extra has no xPaddingBytes', () => {