InboundFormModal.tsx 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. import { useEffect, useRef, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import dayjs from 'dayjs';
  4. import {
  5. Form,
  6. Input,
  7. InputNumber,
  8. Modal,
  9. Radio,
  10. Select,
  11. Switch,
  12. Tabs,
  13. Tooltip,
  14. message,
  15. } from 'antd';
  16. import { HttpUtil, NumberFormatter, RandomUtil, SizeFormatter, Wireguard } from '@/utils';
  17. import {
  18. rawInboundToFormValues,
  19. formValuesToWirePayload,
  20. } from '@/lib/xray/inbound-form-adapter';
  21. import { createDefaultInboundSettings } from '@/lib/xray/inbound-defaults';
  22. import { composeInboundTag, isAutoInboundTag, type InboundTagInput } from '@/lib/xray/inbound-tag';
  23. import {
  24. canEnableReality,
  25. canEnableStream,
  26. canEnableTls,
  27. isSS2022,
  28. } from '@/lib/xray/protocol-capabilities';
  29. import {
  30. InboundFormBaseSchema,
  31. InboundFormSchema,
  32. type InboundFormValues,
  33. } from '@/schemas/forms/inbound-form';
  34. import { antdRule } from '@/utils/zodForm';
  35. import { Protocols } from '@/schemas/primitives';
  36. import { SockoptStreamSettingsSchema } from '@/schemas/protocols/stream/sockopt';
  37. import { HysteriaStreamSettingsSchema } from '@/schemas/protocols/stream/hysteria';
  38. import { TlsStreamSettingsSchema } from '@/schemas/protocols/security/tls';
  39. import { SniffingSchema } from '@/schemas/primitives/sniffing';
  40. import { TcpStreamSettingsSchema } from '@/schemas/protocols/stream/tcp';
  41. import { KcpStreamSettingsSchema } from '@/schemas/protocols/stream/kcp';
  42. import { WsStreamSettingsSchema } from '@/schemas/protocols/stream/ws';
  43. import { GrpcStreamSettingsSchema } from '@/schemas/protocols/stream/grpc';
  44. import { HttpUpgradeStreamSettingsSchema } from '@/schemas/protocols/stream/httpupgrade';
  45. import { XHttpStreamSettingsSchema } from '@/schemas/protocols/stream/xhttp';
  46. import { DateTimePicker } from '@/components/form';
  47. import { FinalMaskForm } from '@/lib/xray/forms/transport';
  48. import './InboundFormModal.css';
  49. import { AdvancedAllEditor, AdvancedSliceEditor } from './advanced-editors';
  50. import { formatInboundIssue, formatInboundValidation } from './formatValidationError';
  51. import {
  52. HttpFields,
  53. HysteriaFields,
  54. MixedFields,
  55. MtprotoFields,
  56. ShadowsocksFields,
  57. TunFields,
  58. TunnelFields,
  59. VlessFields,
  60. WireguardFields,
  61. } from './protocols';
  62. import {
  63. ExternalProxyForm,
  64. GrpcForm,
  65. HttpUpgradeForm,
  66. KcpForm,
  67. RawForm,
  68. SockoptForm,
  69. WsForm,
  70. XhttpForm,
  71. } from './transport';
  72. import { RealityForm, TlsForm } from './security';
  73. import { useSecurityActions } from './useSecurityActions';
  74. import { useInboundFallbacks } from './useInboundFallbacks';
  75. import FallbacksCard from './FallbacksCard';
  76. import SniffingTab from './SniffingTab';
  77. import type { DBInbound } from '@/models/dbinbound';
  78. import type { NodeRecord } from '@/api/queries/useNodesQuery';
  79. const PROTOCOL_OPTIONS = Object.values(Protocols).map((p) => ({ value: p, label: p }));
  80. const TRAFFIC_RESETS = ['never', 'hourly', 'daily', 'weekly', 'monthly'] as const;
  81. const NODE_ELIGIBLE_PROTOCOLS = new Set<string>([
  82. Protocols.VLESS,
  83. Protocols.VMESS,
  84. Protocols.TROJAN,
  85. Protocols.SHADOWSOCKS,
  86. Protocols.HYSTERIA,
  87. Protocols.WIREGUARD,
  88. ]);
  89. interface InboundFormModalProps {
  90. open: boolean;
  91. onClose: () => void;
  92. onSaved: () => void;
  93. mode: 'add' | 'edit';
  94. dbInbound: DBInbound | null;
  95. dbInbounds: DBInbound[];
  96. availableNodes?: NodeRecord[];
  97. }
  98. function buildAddModeValues(): InboundFormValues {
  99. const settings = createDefaultInboundSettings('vless') ?? undefined;
  100. return rawInboundToFormValues({
  101. protocol: 'vless',
  102. settings,
  103. streamSettings: {
  104. network: 'tcp',
  105. security: 'none',
  106. tcpSettings: TcpStreamSettingsSchema.parse({ header: { type: 'none' } }),
  107. },
  108. sniffing: SniffingSchema.parse({}),
  109. port: RandomUtil.randomInteger(10000, 60000),
  110. listen: '',
  111. tag: '',
  112. enable: true,
  113. trafficReset: 'never',
  114. });
  115. }
  116. export default function InboundFormModal({
  117. open,
  118. onClose,
  119. onSaved,
  120. mode,
  121. dbInbound,
  122. dbInbounds,
  123. availableNodes,
  124. }: InboundFormModalProps) {
  125. const { t } = useTranslation();
  126. const [messageApi, messageContextHolder] = message.useMessage();
  127. const [form] = Form.useForm<InboundFormValues>();
  128. const [saving, setSaving] = useState(false);
  129. const {
  130. fallbacks,
  131. fallbackChildOptions,
  132. loadFallbacks,
  133. saveFallbacks,
  134. addFallback,
  135. updateFallback,
  136. removeFallback,
  137. moveFallback,
  138. addAllFallbacks,
  139. } = useInboundFallbacks(dbInbound, dbInbounds);
  140. const selectableNodes = (availableNodes || []).filter((n) => n.enable);
  141. const protocol = (Form.useWatch('protocol', form) ?? '') as string;
  142. const isNodeEligible = NODE_ELIGIBLE_PROTOCOLS.has(protocol);
  143. const sniffingEnabled = Form.useWatch(['sniffing', 'enabled'], form) ?? false;
  144. const vlessEncryption = Form.useWatch(['settings', 'encryption'], form) ?? '';
  145. const ssMethod = Form.useWatch(['settings', 'method'], form);
  146. const isSSWith2022 = isSS2022({
  147. protocol,
  148. settings: typeof ssMethod === 'string' ? { method: ssMethod } : {},
  149. });
  150. const mixedUdpOn = Form.useWatch(['settings', 'udp'], form) ?? false;
  151. const network = Form.useWatch(['streamSettings', 'network'], form) ?? '';
  152. const security = Form.useWatch(['streamSettings', 'security'], form) ?? 'none';
  153. const streamEnabled = canEnableStream({ protocol });
  154. const wPort = Form.useWatch('port', form);
  155. const wListen = (Form.useWatch('listen', form) ?? '') as string;
  156. const isUdsListen = wListen.startsWith('/');
  157. const wNodeId = Form.useWatch('nodeId', form) ?? null;
  158. const wTag = Form.useWatch('tag', form) ?? '';
  159. const wSsNetwork = Form.useWatch(['settings', 'network'], form);
  160. const wTunnelNetwork = Form.useWatch(['settings', 'allowedNetwork'], form);
  161. const autoTagRef = useRef(true);
  162. const lastWrittenTagRef = useRef('');
  163. const currentTagInput = (): InboundTagInput => ({
  164. port: typeof wPort === 'number' ? wPort : 0,
  165. nodeId: typeof wNodeId === 'number' ? wNodeId : null,
  166. protocol,
  167. streamSettings: { network },
  168. settings: { network: wSsNetwork, allowedNetwork: wTunnelNetwork, udp: mixedUdpOn },
  169. });
  170. const isFallbackHost =
  171. (protocol === Protocols.VLESS || protocol === Protocols.TROJAN)
  172. && network === 'tcp'
  173. && (security === 'tls' || security === 'reality');
  174. const {
  175. genRealityKeypair,
  176. clearRealityKeypair,
  177. genMldsa65,
  178. clearMldsa65,
  179. randomizeRealityTarget,
  180. randomizeShortIds,
  181. getNewEchCert,
  182. clearEchCert,
  183. generateRandomPinHash,
  184. setCertFromPanel,
  185. clearCertFiles,
  186. onSecurityChange,
  187. } = useSecurityActions({ form, setSaving, messageApi, nodeId: typeof wNodeId === 'number' ? wNodeId : null });
  188. const toggleExternalProxy = (on: boolean) => {
  189. if (on) {
  190. const port = (form.getFieldValue('port') as number) ?? 443;
  191. form.setFieldValue(['streamSettings', 'externalProxy'], [{
  192. forceTls: 'same',
  193. dest: typeof window !== 'undefined' ? window.location.hostname : '',
  194. port,
  195. remark: '',
  196. sni: '',
  197. fingerprint: '',
  198. alpn: [],
  199. pinnedPeerCertSha256: [],
  200. }]);
  201. } else {
  202. form.setFieldValue(['streamSettings', 'externalProxy'], []);
  203. }
  204. };
  205. const toggleSockopt = (on: boolean) => {
  206. if (on) {
  207. form.setFieldValue(
  208. ['streamSettings', 'sockopt'],
  209. SockoptStreamSettingsSchema.parse({}),
  210. );
  211. } else {
  212. form.setFieldValue(['streamSettings', 'sockopt'], undefined);
  213. }
  214. };
  215. const wgSecretKey = Form.useWatch(['settings', 'secretKey'], form);
  216. const wgPubKey = typeof wgSecretKey === 'string' && wgSecretKey.length > 0
  217. ? Wireguard.generateKeypair(wgSecretKey).publicKey
  218. : '';
  219. const regenInboundWg = () => {
  220. const kp = Wireguard.generateKeypair();
  221. form.setFieldValue(['settings', 'secretKey'], kp.privateKey);
  222. };
  223. const regenWgPeerKeypair = (peerName: number) => {
  224. const kp = Wireguard.generateKeypair();
  225. form.setFieldValue(['settings', 'peers', peerName, 'privateKey'], kp.privateKey);
  226. form.setFieldValue(['settings', 'peers', peerName, 'publicKey'], kp.publicKey);
  227. };
  228. const matchesVlessAuth = (
  229. block: { id?: string; label?: string } | undefined | null,
  230. authId: string,
  231. ) => {
  232. if (block?.id === authId) return true;
  233. const label = (block?.label || '').toLowerCase().replace(/[-_\s]/g, '');
  234. if (authId === 'mlkem768') return label.includes('mlkem768');
  235. if (authId === 'x25519') return label.includes('x25519');
  236. return false;
  237. };
  238. const getNewVlessEnc = async (authId: string) => {
  239. if (!authId) return;
  240. setSaving(true);
  241. try {
  242. const msg = await HttpUtil.get('/panel/api/server/getNewVlessEnc');
  243. if (!msg?.success) return;
  244. const obj = msg.obj as {
  245. auths?: { decryption: string; encryption: string; label?: string; id?: string }[];
  246. };
  247. const block = (obj.auths || []).find((a) => matchesVlessAuth(a, authId));
  248. if (!block) return;
  249. form.setFieldValue(['settings', 'decryption'], block.decryption);
  250. form.setFieldValue(['settings', 'encryption'], block.encryption);
  251. } finally {
  252. setSaving(false);
  253. }
  254. };
  255. const clearVlessEnc = () => {
  256. form.setFieldValue(['settings', 'decryption'], 'none');
  257. form.setFieldValue(['settings', 'encryption'], 'none');
  258. };
  259. const selectedVlessAuth = (() => {
  260. const enc = typeof vlessEncryption === 'string' ? vlessEncryption : '';
  261. if (!enc || enc === 'none') return 'None';
  262. const parts = enc.split('.').filter(Boolean);
  263. const authKey = parts[parts.length - 1] || '';
  264. if (!authKey) return t('pages.inbounds.vlessAuthCustom');
  265. return authKey.length > 300
  266. ? t('pages.inbounds.vlessAuthMlkem768')
  267. : t('pages.inbounds.vlessAuthX25519');
  268. })();
  269. useEffect(() => {
  270. if (!open) return;
  271. const initial = mode === 'edit' && dbInbound
  272. ? rawInboundToFormValues(dbInbound)
  273. : buildAddModeValues();
  274. form.resetFields();
  275. form.setFieldsValue(initial);
  276. const initialTag = (initial.tag ?? '') as string;
  277. autoTagRef.current = isAutoInboundTag(initialTag, {
  278. port: initial.port ?? 0,
  279. nodeId: initial.nodeId ?? null,
  280. protocol: initial.protocol,
  281. streamSettings: (initial.streamSettings ?? {}) as Record<string, unknown>,
  282. settings: (initial.settings ?? {}) as Record<string, unknown>,
  283. });
  284. lastWrittenTagRef.current = initialTag;
  285. if (
  286. mode === 'edit'
  287. && dbInbound
  288. && (dbInbound.protocol === Protocols.VLESS || dbInbound.protocol === Protocols.TROJAN)
  289. ) {
  290. loadFallbacks(dbInbound.id);
  291. } else {
  292. loadFallbacks(null);
  293. }
  294. // eslint-disable-next-line react-hooks/exhaustive-deps
  295. }, [open, mode, dbInbound, form]);
  296. useEffect(() => {
  297. if (!open) return;
  298. if (wTag === lastWrittenTagRef.current) return;
  299. autoTagRef.current = isAutoInboundTag(wTag, currentTagInput());
  300. // eslint-disable-next-line react-hooks/exhaustive-deps
  301. }, [open, wTag]);
  302. useEffect(() => {
  303. if (!open || !autoTagRef.current) return;
  304. const next = composeInboundTag(currentTagInput());
  305. if (next !== (form.getFieldValue('tag') ?? '')) {
  306. lastWrittenTagRef.current = next;
  307. form.setFieldValue('tag', next);
  308. }
  309. // eslint-disable-next-line react-hooks/exhaustive-deps
  310. }, [open, wPort, wNodeId, protocol, network, mixedUdpOn, wSsNetwork, wTunnelNetwork]);
  311. // Why: protocol picker reset cascades through the form — clearing the
  312. // settings DU branch and dropping a nodeId that no longer applies. The
  313. // legacy modal did this imperatively in onProtocolChange; here we hook
  314. // into AntD's onValuesChange and let setFieldValue keep the rest of
  315. // the form state intact.
  316. const onValuesChange = (changed: Partial<InboundFormValues>) => {
  317. if (mode === 'edit') return;
  318. if ('protocol' in changed && typeof changed.protocol === 'string') {
  319. const next = changed.protocol;
  320. const settings = createDefaultInboundSettings(next) ?? undefined;
  321. form.setFieldValue('settings', settings);
  322. if (!NODE_ELIGIBLE_PROTOCOLS.has(next)) {
  323. form.setFieldValue('nodeId', null);
  324. }
  325. // Hysteria uses its dedicated transport — force the network branch
  326. // so the stream tab renders the hysteria sub-form, not the leftover
  327. // tcpSettings from the previous protocol. When leaving hysteria,
  328. // snap back to TCP so the standard network selector has a valid
  329. // starting point.
  330. if (next === Protocols.HYSTERIA) {
  331. const tls = TlsStreamSettingsSchema.parse({}) as Record<string, unknown>;
  332. tls.certificates = [{
  333. useFile: true,
  334. certificateFile: '',
  335. keyFile: '',
  336. certificate: [],
  337. key: [],
  338. oneTimeLoading: false,
  339. usage: 'encipherment',
  340. buildChain: false,
  341. }];
  342. form.setFieldValue('streamSettings', {
  343. network: 'hysteria',
  344. security: 'tls',
  345. hysteriaSettings: HysteriaStreamSettingsSchema.parse({}),
  346. tlsSettings: tls,
  347. // Hysteria2 needs an obfs wrapper on the FinalMask side; seed
  348. // it with salamander + a random password so the listener boots
  349. // with a usable default. Re-selecting Hysteria from another
  350. // protocol re-runs this and refreshes the password — that's
  351. // intentional, the form was already being reset.
  352. finalmask: {
  353. tcp: [],
  354. udp: [{
  355. type: 'salamander',
  356. settings: { password: RandomUtil.randomLowerAndNum(16) },
  357. }],
  358. },
  359. });
  360. } else {
  361. const current = form.getFieldValue('streamSettings') as { network?: string } | undefined;
  362. if (current?.network === 'hysteria') {
  363. form.setFieldValue('streamSettings', { network: 'tcp', security: 'none', tcpSettings: {} });
  364. }
  365. }
  366. }
  367. };
  368. const submit = async () => {
  369. try {
  370. await form.validateFields();
  371. } catch {
  372. return;
  373. }
  374. // Why getFieldsValue(true) instead of the validateFields return value:
  375. // rc-component/form's validateFields filters its output by REGISTERED
  376. // name paths. settings.clients and settings.fallbacks have no Form.Item
  377. // bound to them (clients are managed via the standalone Client modal,
  378. // not inside this inbound modal) — so validateFields would drop them
  379. // and the update wire payload would silently delete every client on
  380. // every save. getFieldsValue(true) returns the entire form store and
  381. // keeps those sub-trees intact.
  382. const values = form.getFieldsValue(true) as InboundFormValues;
  383. const parsed = InboundFormSchema.safeParse(values);
  384. if (!parsed.success) {
  385. const issues = parsed.error.issues;
  386. messageApi.error(formatInboundValidation(issues, values, t));
  387. console.error(
  388. '[InboundFormModal] schema validation failed:',
  389. issues.map((issue) => formatInboundIssue(issue, values, t)),
  390. );
  391. return;
  392. }
  393. setSaving(true);
  394. try {
  395. const payload = formValuesToWirePayload(parsed.data);
  396. const url = mode === 'edit' && dbInbound
  397. ? `/panel/api/inbounds/update/${dbInbound.id}`
  398. : '/panel/api/inbounds/add';
  399. const msg = await HttpUtil.post(url, payload);
  400. if (msg?.success) {
  401. if (isFallbackHost) {
  402. const obj = msg.obj as { id?: number; Id?: number } | null;
  403. const masterId = mode === 'edit'
  404. ? dbInbound!.id
  405. : (obj?.id ?? obj?.Id ?? 0);
  406. if (masterId) await saveFallbacks(masterId);
  407. }
  408. onSaved();
  409. onClose();
  410. }
  411. } finally {
  412. setSaving(false);
  413. }
  414. };
  415. const title = mode === 'edit'
  416. ? t('pages.inbounds.modifyInbound')
  417. : t('pages.inbounds.addInbound');
  418. const okText = mode === 'edit'
  419. ? t('pages.clients.submitEdit')
  420. : t('create');
  421. const basicTab = (
  422. <>
  423. <Form.Item name="tag" hidden noStyle><Input /></Form.Item>
  424. <Form.Item name="up" hidden noStyle><InputNumber /></Form.Item>
  425. <Form.Item name="down" hidden noStyle><InputNumber /></Form.Item>
  426. <Form.Item name="total" hidden noStyle><InputNumber /></Form.Item>
  427. <Form.Item name="expiryTime" hidden noStyle><InputNumber /></Form.Item>
  428. <Form.Item name="lastTrafficResetTime" hidden noStyle><InputNumber /></Form.Item>
  429. <Form.Item name="clientStats" hidden noStyle><Input /></Form.Item>
  430. <Form.Item name="enable" label={t('enable')} valuePropName="checked">
  431. <Switch />
  432. </Form.Item>
  433. <Form.Item name="remark" label={t('pages.inbounds.remark')}>
  434. <Input />
  435. </Form.Item>
  436. {selectableNodes.length > 0 && isNodeEligible && (
  437. <Form.Item name="nodeId" label={t('pages.inbounds.deployTo')}>
  438. <Select
  439. disabled={mode === 'edit'}
  440. placeholder={t('pages.inbounds.localPanel')}
  441. allowClear
  442. options={selectableNodes.map((n) => ({
  443. value: n.id,
  444. label: `${n.name}${n.status === 'offline' ? ' (offline)' : ''}`,
  445. disabled: n.status === 'offline',
  446. }))}
  447. />
  448. </Form.Item>
  449. )}
  450. <Form.Item name="protocol" label={t('pages.inbounds.protocol')}>
  451. <Select disabled={mode === 'edit'} options={PROTOCOL_OPTIONS} />
  452. </Form.Item>
  453. <Form.Item
  454. name="listen"
  455. label={t('pages.inbounds.address')}
  456. extra={t('pages.inbounds.form.listenHelp')}
  457. >
  458. <Input placeholder={t('pages.inbounds.monitorDesc')} />
  459. </Form.Item>
  460. <Form.Item
  461. name="port"
  462. label={t('pages.inbounds.port')}
  463. rules={[antdRule(InboundFormBaseSchema.shape.port, t)]}
  464. >
  465. <InputNumber min={isUdsListen ? 0 : 1} max={65535} />
  466. </Form.Item>
  467. <Form.Item
  468. label={
  469. <Tooltip title={t('pages.inbounds.meansNoLimit')}>
  470. {t('pages.inbounds.totalFlow')}
  471. </Tooltip>
  472. }
  473. >
  474. <Form.Item
  475. noStyle
  476. shouldUpdate={(prev, curr) => prev.total !== curr.total}
  477. >
  478. {({ getFieldValue, setFieldValue }) => {
  479. const totalBytes = (getFieldValue('total') as number) ?? 0;
  480. const totalGB = totalBytes
  481. ? Math.round((totalBytes / SizeFormatter.ONE_GB) * 100) / 100
  482. : 0;
  483. return (
  484. <InputNumber
  485. value={totalGB}
  486. min={0}
  487. step={1}
  488. onChange={(v) => {
  489. const bytes = NumberFormatter.toFixed(
  490. (Number(v) || 0) * SizeFormatter.ONE_GB,
  491. 0,
  492. );
  493. setFieldValue('total', bytes);
  494. }}
  495. />
  496. );
  497. }}
  498. </Form.Item>
  499. </Form.Item>
  500. <Form.Item name="trafficReset" label={t('pages.inbounds.periodicTrafficResetTitle')}>
  501. <Select
  502. options={TRAFFIC_RESETS.map((r) => ({
  503. value: r,
  504. label: t(`pages.inbounds.periodicTrafficReset.${r}`),
  505. }))}
  506. />
  507. </Form.Item>
  508. <Form.Item
  509. label={
  510. <Tooltip title={t('pages.inbounds.leaveBlankToNeverExpire')}>
  511. {t('pages.inbounds.expireDate')}
  512. </Tooltip>
  513. }
  514. >
  515. <Form.Item
  516. noStyle
  517. shouldUpdate={(prev, curr) => prev.expiryTime !== curr.expiryTime}
  518. >
  519. {({ getFieldValue, setFieldValue }) => {
  520. const expiry = (getFieldValue('expiryTime') as number) ?? 0;
  521. return (
  522. <DateTimePicker
  523. value={expiry > 0 ? dayjs(expiry) : null}
  524. onChange={(d) => setFieldValue('expiryTime', d ? d.valueOf() : 0)}
  525. />
  526. );
  527. }}
  528. </Form.Item>
  529. </Form.Item>
  530. </>
  531. );
  532. const fallbacksCard = (
  533. <FallbacksCard
  534. fallbacks={fallbacks}
  535. fallbackChildOptions={fallbackChildOptions}
  536. addFallback={addFallback}
  537. updateFallback={updateFallback}
  538. removeFallback={removeFallback}
  539. moveFallback={moveFallback}
  540. addAllFallbacks={addAllFallbacks}
  541. />
  542. );
  543. const protocolTab = (
  544. <>
  545. {protocol === Protocols.WIREGUARD && <WireguardFields wgPubKey={wgPubKey} regenInboundWg={regenInboundWg} regenWgPeerKeypair={regenWgPeerKeypair} />}
  546. {protocol === Protocols.TUN && <TunFields />}
  547. {protocol === Protocols.TUNNEL && <TunnelFields />}
  548. {protocol === Protocols.HTTP && <HttpFields />}
  549. {protocol === Protocols.MIXED && <MixedFields mixedUdpOn={mixedUdpOn} />}
  550. {protocol === Protocols.MTPROTO && <MtprotoFields />}
  551. {protocol === Protocols.SHADOWSOCKS && <ShadowsocksFields form={form} isSSWith2022={isSSWith2022} />}
  552. {protocol === Protocols.VLESS && <VlessFields saving={saving} selectedVlessAuth={selectedVlessAuth} network={network} security={security} getNewVlessEnc={getNewVlessEnc} clearVlessEnc={clearVlessEnc} />}
  553. {isFallbackHost && fallbacksCard}
  554. </>
  555. );
  556. // Switching `network` swaps which per-network key (tcpSettings,
  557. // wsSettings, grpcSettings, ...) appears on the wire. Clear the old
  558. // network's blob and seed the new one with the schema defaults so the
  559. // Form.Items inside it have valid initial values (KCP needs MTU=1350
  560. // etc., not empty strings).
  561. // Seed each network's settings blob with its Zod schema defaults so
  562. // every Form.Item inside the network sub-form has a defined starting
  563. // value. XHTTP in particular has ~20 fields (sessionPlacement,
  564. // seqPlacement, xPaddingMethod, uplinkHTTPMethod, ...) whose value
  565. // is the literal "" sentinel meaning "let xray-core pick its
  566. // default". Without seeding "", the Form.Item reads `undefined` and
  567. // the Select shows blank instead of the "Default (path)" option.
  568. const newStreamSlice = (n: string): Record<string, unknown> => {
  569. switch (n) {
  570. case 'tcp': return TcpStreamSettingsSchema.parse({ header: { type: 'none' } });
  571. case 'kcp': return KcpStreamSettingsSchema.parse({});
  572. case 'ws': return WsStreamSettingsSchema.parse({});
  573. case 'grpc': return GrpcStreamSettingsSchema.parse({});
  574. case 'httpupgrade': return HttpUpgradeStreamSettingsSchema.parse({});
  575. case 'xhttp': return XHttpStreamSettingsSchema.parse({});
  576. default: return {};
  577. }
  578. };
  579. const onNetworkChange = (next: string) => {
  580. const ALL = ['tcpSettings', 'kcpSettings', 'wsSettings', 'grpcSettings', 'httpupgradeSettings', 'xhttpSettings'];
  581. const current = (form.getFieldValue('streamSettings') as Record<string, unknown>) ?? {};
  582. const cleaned: Record<string, unknown> = { ...current, network: next };
  583. for (const k of ALL) {
  584. if (k !== `${next}Settings`) delete cleaned[k];
  585. }
  586. cleaned[`${next}Settings`] = newStreamSlice(next);
  587. // mKCP wants a UDP mask wrapper on the FinalMask side; seed it with
  588. // `mkcp-legacy` so the inbound boots with a sensible default
  589. // instead of unobfuscated mKCP traffic. The user can still edit or
  590. // clear the mask via the FinalMask section.
  591. if (next === 'kcp') {
  592. const fm = (cleaned.finalmask as Record<string, unknown> | undefined) ?? {};
  593. const udp = Array.isArray(fm.udp) ? (fm.udp as unknown[]) : [];
  594. const hasMkcp = udp.some((m) => {
  595. const entry = m as { type?: string };
  596. return entry?.type === 'mkcp-legacy';
  597. });
  598. if (!hasMkcp) {
  599. cleaned.finalmask = {
  600. ...fm,
  601. udp: [...udp, { type: 'mkcp-legacy', settings: { header: '', value: '' } }],
  602. };
  603. }
  604. }
  605. form.setFieldValue('streamSettings', cleaned);
  606. };
  607. const streamTab = (
  608. <>
  609. {protocol !== Protocols.HYSTERIA && (
  610. <Form.Item label={t('transmission')} name={['streamSettings', 'network']}>
  611. <Select
  612. style={{ width: '75%' }}
  613. onChange={onNetworkChange}
  614. options={[
  615. { value: 'tcp', label: 'RAW' },
  616. { value: 'kcp', label: 'mKCP' },
  617. { value: 'ws', label: 'WebSocket' },
  618. { value: 'grpc', label: 'gRPC' },
  619. { value: 'httpupgrade', label: 'HTTPUpgrade' },
  620. { value: 'xhttp', label: 'XHTTP' },
  621. ]}
  622. />
  623. </Form.Item>
  624. )}
  625. {/* Inbound Hysteria stream sub-form. The transport for hysteria
  626. isn't user-selectable (always 'hysteria'), so the network
  627. dropdown is hidden above. Fields here mirror the legacy
  628. HysteriaStreamSettings inbound class: version is locked to 2,
  629. auth + udpIdleTimeout are required, masquerade is an optional
  630. sub-object that lets xray-core disguise the listener as an
  631. HTTP server when probed. */}
  632. {protocol === Protocols.HYSTERIA && <HysteriaFields form={form} />}
  633. {network === 'tcp' && <RawForm />}
  634. {network === 'ws' && <WsForm />}
  635. {network === 'grpc' && <GrpcForm />}
  636. {network === 'xhttp' && <XhttpForm form={form} />}
  637. {network === 'httpupgrade' && <HttpUpgradeForm />}
  638. {network === 'kcp' && <KcpForm />}
  639. <ExternalProxyForm toggleExternalProxy={toggleExternalProxy} />
  640. <SockoptForm toggleSockopt={toggleSockopt} />
  641. <FinalMaskForm
  642. name={['streamSettings', 'finalmask']}
  643. network={network as string}
  644. protocol={protocol}
  645. form={form}
  646. />
  647. </>
  648. );
  649. const securityTab = (
  650. <>
  651. <Form.Item name={['streamSettings', 'security']} hidden noStyle>
  652. <Input />
  653. </Form.Item>
  654. <Form.Item label={t('pages.inbounds.securityTab')}>
  655. <Form.Item
  656. noStyle
  657. shouldUpdate={(prev, curr) =>
  658. prev.streamSettings?.security !== curr.streamSettings?.security
  659. || prev.streamSettings?.network !== curr.streamSettings?.network
  660. || prev.protocol !== curr.protocol
  661. }
  662. >
  663. {({ getFieldValue }) => {
  664. const sec = getFieldValue(['streamSettings', 'security']) ?? 'none';
  665. const net = getFieldValue(['streamSettings', 'network']) ?? '';
  666. const proto = getFieldValue('protocol') ?? '';
  667. const tlsOk = canEnableTls({ protocol: proto, streamSettings: { network: net, security: sec } });
  668. const realityOk = canEnableReality({ protocol: proto, streamSettings: { network: net, security: sec } });
  669. const tlsOnly = proto === Protocols.HYSTERIA;
  670. return (
  671. <Radio.Group
  672. value={sec}
  673. buttonStyle="solid"
  674. disabled={!tlsOk}
  675. onChange={(e) => onSecurityChange(e.target.value)}
  676. >
  677. {!tlsOnly && <Radio.Button value="none">{t('none')}</Radio.Button>}
  678. <Radio.Button value="tls">TLS</Radio.Button>
  679. {realityOk && <Radio.Button value="reality">Reality</Radio.Button>}
  680. </Radio.Group>
  681. );
  682. }}
  683. </Form.Item>
  684. </Form.Item>
  685. {security === 'tls' && (
  686. <TlsForm
  687. saving={saving}
  688. setCertFromPanel={setCertFromPanel}
  689. clearCertFiles={clearCertFiles}
  690. generateRandomPinHash={generateRandomPinHash}
  691. getNewEchCert={getNewEchCert}
  692. clearEchCert={clearEchCert}
  693. />
  694. )}
  695. {security === 'reality' && (
  696. <RealityForm
  697. saving={saving}
  698. randomizeRealityTarget={randomizeRealityTarget}
  699. randomizeShortIds={randomizeShortIds}
  700. genRealityKeypair={genRealityKeypair}
  701. clearRealityKeypair={clearRealityKeypair}
  702. genMldsa65={genMldsa65}
  703. clearMldsa65={clearMldsa65}
  704. />
  705. )}
  706. </>
  707. );
  708. const advancedTab = (
  709. <div className="advanced-shell">
  710. <div className="advanced-panel">
  711. <div className="advanced-panel__header">
  712. <div>
  713. <div className="advanced-panel__title">{t('pages.inbounds.advanced.title')}</div>
  714. <div className="advanced-panel__subtitle">{t('pages.inbounds.advanced.subtitle')}</div>
  715. </div>
  716. </div>
  717. <Tabs
  718. className="advanced-inner-tabs"
  719. items={[
  720. {
  721. key: 'all',
  722. label: t('pages.inbounds.advanced.all'),
  723. children: (
  724. <>
  725. <div className="advanced-editor-meta">
  726. {t('pages.inbounds.advanced.allHelp')}
  727. </div>
  728. <AdvancedAllEditor form={form} streamEnabled={streamEnabled} />
  729. </>
  730. ),
  731. },
  732. {
  733. key: 'settings',
  734. label: t('pages.inbounds.advanced.settings'),
  735. children: (
  736. <>
  737. <div className="advanced-editor-meta">
  738. {t('pages.inbounds.advanced.settingsHelp')}{' '}
  739. <code>{'{ settings: { ... } }'}</code>.
  740. </div>
  741. <AdvancedSliceEditor
  742. form={form}
  743. path="settings"
  744. wrapKey="settings"
  745. minHeight="320px"
  746. maxHeight="540px"
  747. />
  748. </>
  749. ),
  750. },
  751. ...(streamEnabled
  752. ? [{
  753. key: 'stream',
  754. label: t('pages.inbounds.advanced.stream'),
  755. children: (
  756. <>
  757. <div className="advanced-editor-meta">
  758. {t('pages.inbounds.advanced.streamHelp')}{' '}
  759. <code>{'{ streamSettings: { ... } }'}</code>.
  760. </div>
  761. <AdvancedSliceEditor
  762. form={form}
  763. path="streamSettings"
  764. wrapKey="streamSettings"
  765. minHeight="320px"
  766. maxHeight="540px"
  767. />
  768. </>
  769. ),
  770. }]
  771. : []),
  772. {
  773. key: 'sniffing',
  774. label: t('pages.inbounds.advanced.sniffing'),
  775. children: (
  776. <>
  777. <div className="advanced-editor-meta">
  778. {t('pages.inbounds.advanced.sniffingHelp')}{' '}
  779. <code>{'{ sniffing: { ... } }'}</code>.
  780. </div>
  781. <AdvancedSliceEditor
  782. form={form}
  783. path="sniffing"
  784. wrapKey="sniffing"
  785. minHeight="240px"
  786. maxHeight="420px"
  787. />
  788. </>
  789. ),
  790. },
  791. ]}
  792. />
  793. </div>
  794. </div>
  795. );
  796. const sniffingTab = <SniffingTab sniffingEnabled={sniffingEnabled} />;
  797. return (
  798. <>
  799. {messageContextHolder}
  800. <Modal
  801. open={open}
  802. title={title}
  803. okText={okText}
  804. cancelText={t('close')}
  805. confirmLoading={saving}
  806. mask={{ closable: false }}
  807. width={780}
  808. onOk={submit}
  809. onCancel={onClose}
  810. destroyOnHidden
  811. >
  812. <Form
  813. form={form}
  814. colon={false}
  815. labelCol={{ sm: { span: 8 } }}
  816. wrapperCol={{ sm: { span: 14 } }}
  817. onValuesChange={onValuesChange}
  818. >
  819. <Tabs items={[
  820. // forceRender on every tab so all Form.Items register at modal
  821. // open, not lazily on first visit. Without it, AntD's items API
  822. // lazy-mounts inactive tabs — their fields don't register, so
  823. // Form.useWatch on a parent path (e.g. 'sniffing') returns the
  824. // partial-view {} until the user touches the tab and the
  825. // inner Form.Item for `sniffing.enabled` registers.
  826. { key: 'basic', label: t('pages.xray.basicTemplate'), children: basicTab, forceRender: true },
  827. ...(([
  828. Protocols.VLESS,
  829. Protocols.SHADOWSOCKS,
  830. Protocols.HTTP,
  831. Protocols.MIXED,
  832. Protocols.TUNNEL,
  833. Protocols.TUN,
  834. Protocols.WIREGUARD,
  835. Protocols.MTPROTO,
  836. ] as string[]).includes(protocol) || isFallbackHost
  837. ? [{ key: 'protocol', label: t('pages.inbounds.protocol'), children: protocolTab, forceRender: true }]
  838. : []),
  839. ...(streamEnabled
  840. ? [
  841. { key: 'stream', label: t('pages.inbounds.streamTab'), children: streamTab, forceRender: true },
  842. { key: 'security', label: t('pages.inbounds.securityTab'), children: securityTab, forceRender: true },
  843. ]
  844. : []),
  845. { key: 'sniffing', label: t('pages.inbounds.sniffingTab'), children: sniffingTab, forceRender: true },
  846. { key: 'advanced', label: t('pages.xray.advancedTemplate'), children: advancedTab, forceRender: true },
  847. ]} />
  848. </Form>
  849. </Modal>
  850. </>
  851. );
  852. }