InboundFormModal.tsx 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  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 { createHysteriaTlsSettingsWithDefaultCert } from '@/lib/xray/inbound-tls-defaults';
  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. form.setFieldValue('streamSettings', {
  332. network: 'hysteria',
  333. security: 'tls',
  334. hysteriaSettings: HysteriaStreamSettingsSchema.parse({}),
  335. tlsSettings: createHysteriaTlsSettingsWithDefaultCert(),
  336. // Hysteria2 needs an obfs wrapper on the FinalMask side; seed
  337. // it with salamander + a random password so the listener boots
  338. // with a usable default. Re-selecting Hysteria from another
  339. // protocol re-runs this and refreshes the password — that's
  340. // intentional, the form was already being reset.
  341. finalmask: {
  342. tcp: [],
  343. udp: [{
  344. type: 'salamander',
  345. settings: { password: RandomUtil.randomLowerAndNum(16) },
  346. }],
  347. },
  348. });
  349. } else {
  350. const current = form.getFieldValue('streamSettings') as { network?: string } | undefined;
  351. if (current?.network === 'hysteria') {
  352. form.setFieldValue('streamSettings', { network: 'tcp', security: 'none', tcpSettings: {} });
  353. }
  354. }
  355. }
  356. };
  357. const submit = async () => {
  358. try {
  359. await form.validateFields();
  360. } catch {
  361. return;
  362. }
  363. // Why getFieldsValue(true) instead of the validateFields return value:
  364. // rc-component/form's validateFields filters its output by REGISTERED
  365. // name paths. settings.clients and settings.fallbacks have no Form.Item
  366. // bound to them (clients are managed via the standalone Client modal,
  367. // not inside this inbound modal) — so validateFields would drop them
  368. // and the update wire payload would silently delete every client on
  369. // every save. getFieldsValue(true) returns the entire form store and
  370. // keeps those sub-trees intact.
  371. const values = form.getFieldsValue(true) as InboundFormValues;
  372. const parsed = InboundFormSchema.safeParse(values);
  373. if (!parsed.success) {
  374. const issues = parsed.error.issues;
  375. messageApi.error(formatInboundValidation(issues, values, t));
  376. console.error(
  377. '[InboundFormModal] schema validation failed:',
  378. issues.map((issue) => formatInboundIssue(issue, values, t)),
  379. );
  380. return;
  381. }
  382. setSaving(true);
  383. try {
  384. const payload = formValuesToWirePayload(parsed.data);
  385. const url = mode === 'edit' && dbInbound
  386. ? `/panel/api/inbounds/update/${dbInbound.id}`
  387. : '/panel/api/inbounds/add';
  388. const msg = await HttpUtil.post(url, payload);
  389. if (msg?.success) {
  390. if (isFallbackHost) {
  391. const obj = msg.obj as { id?: number; Id?: number } | null;
  392. const masterId = mode === 'edit'
  393. ? dbInbound!.id
  394. : (obj?.id ?? obj?.Id ?? 0);
  395. if (masterId) await saveFallbacks(masterId);
  396. }
  397. onSaved();
  398. onClose();
  399. }
  400. } finally {
  401. setSaving(false);
  402. }
  403. };
  404. const title = mode === 'edit'
  405. ? t('pages.inbounds.modifyInbound')
  406. : t('pages.inbounds.addInbound');
  407. const okText = mode === 'edit'
  408. ? t('pages.clients.submitEdit')
  409. : t('create');
  410. const basicTab = (
  411. <>
  412. <Form.Item name="tag" hidden noStyle><Input /></Form.Item>
  413. <Form.Item name="up" hidden noStyle><InputNumber /></Form.Item>
  414. <Form.Item name="down" hidden noStyle><InputNumber /></Form.Item>
  415. <Form.Item name="total" hidden noStyle><InputNumber /></Form.Item>
  416. <Form.Item name="expiryTime" hidden noStyle><InputNumber /></Form.Item>
  417. <Form.Item name="lastTrafficResetTime" hidden noStyle><InputNumber /></Form.Item>
  418. <Form.Item name="clientStats" hidden noStyle><Input /></Form.Item>
  419. <Form.Item name="enable" label={t('enable')} valuePropName="checked">
  420. <Switch />
  421. </Form.Item>
  422. <Form.Item name="remark" label={t('pages.inbounds.remark')}>
  423. <Input />
  424. </Form.Item>
  425. {selectableNodes.length > 0 && isNodeEligible && (
  426. <Form.Item name="nodeId" label={t('pages.inbounds.deployTo')}>
  427. <Select
  428. disabled={mode === 'edit'}
  429. placeholder={t('pages.inbounds.localPanel')}
  430. allowClear
  431. options={selectableNodes.map((n) => ({
  432. value: n.id,
  433. label: `${n.name}${n.status === 'offline' ? ' (offline)' : ''}`,
  434. disabled: n.status === 'offline',
  435. }))}
  436. />
  437. </Form.Item>
  438. )}
  439. <Form.Item name="protocol" label={t('pages.inbounds.protocol')}>
  440. <Select disabled={mode === 'edit'} options={PROTOCOL_OPTIONS} />
  441. </Form.Item>
  442. <Form.Item
  443. name="listen"
  444. label={t('pages.inbounds.address')}
  445. extra={t('pages.inbounds.form.listenHelp')}
  446. >
  447. <Input placeholder={t('pages.inbounds.monitorDesc')} />
  448. </Form.Item>
  449. <Form.Item
  450. name="port"
  451. label={t('pages.inbounds.port')}
  452. rules={[antdRule(InboundFormBaseSchema.shape.port, t)]}
  453. >
  454. <InputNumber min={isUdsListen ? 0 : 1} max={65535} />
  455. </Form.Item>
  456. <Form.Item
  457. label={
  458. <Tooltip title={t('pages.inbounds.meansNoLimit')}>
  459. {t('pages.inbounds.totalFlow')}
  460. </Tooltip>
  461. }
  462. >
  463. <Form.Item
  464. noStyle
  465. shouldUpdate={(prev, curr) => prev.total !== curr.total}
  466. >
  467. {({ getFieldValue, setFieldValue }) => {
  468. const totalBytes = (getFieldValue('total') as number) ?? 0;
  469. const totalGB = totalBytes
  470. ? Math.round((totalBytes / SizeFormatter.ONE_GB) * 100) / 100
  471. : 0;
  472. return (
  473. <InputNumber
  474. value={totalGB}
  475. min={0}
  476. step={1}
  477. onChange={(v) => {
  478. const bytes = NumberFormatter.toFixed(
  479. (Number(v) || 0) * SizeFormatter.ONE_GB,
  480. 0,
  481. );
  482. setFieldValue('total', bytes);
  483. }}
  484. />
  485. );
  486. }}
  487. </Form.Item>
  488. </Form.Item>
  489. <Form.Item name="trafficReset" label={t('pages.inbounds.periodicTrafficResetTitle')}>
  490. <Select
  491. options={TRAFFIC_RESETS.map((r) => ({
  492. value: r,
  493. label: t(`pages.inbounds.periodicTrafficReset.${r}`),
  494. }))}
  495. />
  496. </Form.Item>
  497. <Form.Item
  498. label={
  499. <Tooltip title={t('pages.inbounds.leaveBlankToNeverExpire')}>
  500. {t('pages.inbounds.expireDate')}
  501. </Tooltip>
  502. }
  503. >
  504. <Form.Item
  505. noStyle
  506. shouldUpdate={(prev, curr) => prev.expiryTime !== curr.expiryTime}
  507. >
  508. {({ getFieldValue, setFieldValue }) => {
  509. const expiry = (getFieldValue('expiryTime') as number) ?? 0;
  510. return (
  511. <DateTimePicker
  512. value={expiry > 0 ? dayjs(expiry) : null}
  513. onChange={(d) => setFieldValue('expiryTime', d ? d.valueOf() : 0)}
  514. />
  515. );
  516. }}
  517. </Form.Item>
  518. </Form.Item>
  519. </>
  520. );
  521. const fallbacksCard = (
  522. <FallbacksCard
  523. fallbacks={fallbacks}
  524. fallbackChildOptions={fallbackChildOptions}
  525. addFallback={addFallback}
  526. updateFallback={updateFallback}
  527. removeFallback={removeFallback}
  528. moveFallback={moveFallback}
  529. addAllFallbacks={addAllFallbacks}
  530. />
  531. );
  532. const protocolTab = (
  533. <>
  534. {protocol === Protocols.WIREGUARD && <WireguardFields wgPubKey={wgPubKey} regenInboundWg={regenInboundWg} regenWgPeerKeypair={regenWgPeerKeypair} />}
  535. {protocol === Protocols.TUN && <TunFields />}
  536. {protocol === Protocols.TUNNEL && <TunnelFields />}
  537. {protocol === Protocols.HTTP && <HttpFields />}
  538. {protocol === Protocols.MIXED && <MixedFields mixedUdpOn={mixedUdpOn} />}
  539. {protocol === Protocols.MTPROTO && <MtprotoFields />}
  540. {protocol === Protocols.SHADOWSOCKS && <ShadowsocksFields form={form} isSSWith2022={isSSWith2022} />}
  541. {protocol === Protocols.VLESS && <VlessFields saving={saving} selectedVlessAuth={selectedVlessAuth} network={network} security={security} getNewVlessEnc={getNewVlessEnc} clearVlessEnc={clearVlessEnc} />}
  542. {isFallbackHost && fallbacksCard}
  543. </>
  544. );
  545. // Switching `network` swaps which per-network key (tcpSettings,
  546. // wsSettings, grpcSettings, ...) appears on the wire. Clear the old
  547. // network's blob and seed the new one with the schema defaults so the
  548. // Form.Items inside it have valid initial values (KCP needs MTU=1350
  549. // etc., not empty strings).
  550. // Seed each network's settings blob with its Zod schema defaults so
  551. // every Form.Item inside the network sub-form has a defined starting
  552. // value. XHTTP in particular has ~20 fields (sessionPlacement,
  553. // seqPlacement, xPaddingMethod, uplinkHTTPMethod, ...) whose value
  554. // is the literal "" sentinel meaning "let xray-core pick its
  555. // default". Without seeding "", the Form.Item reads `undefined` and
  556. // the Select shows blank instead of the "Default (path)" option.
  557. const newStreamSlice = (n: string): Record<string, unknown> => {
  558. switch (n) {
  559. case 'tcp': return TcpStreamSettingsSchema.parse({ header: { type: 'none' } });
  560. case 'kcp': return KcpStreamSettingsSchema.parse({});
  561. case 'ws': return WsStreamSettingsSchema.parse({});
  562. case 'grpc': return GrpcStreamSettingsSchema.parse({});
  563. case 'httpupgrade': return HttpUpgradeStreamSettingsSchema.parse({});
  564. case 'xhttp': return XHttpStreamSettingsSchema.parse({});
  565. default: return {};
  566. }
  567. };
  568. const onNetworkChange = (next: string) => {
  569. const ALL = ['tcpSettings', 'kcpSettings', 'wsSettings', 'grpcSettings', 'httpupgradeSettings', 'xhttpSettings'];
  570. const current = (form.getFieldValue('streamSettings') as Record<string, unknown>) ?? {};
  571. const cleaned: Record<string, unknown> = { ...current, network: next };
  572. for (const k of ALL) {
  573. if (k !== `${next}Settings`) delete cleaned[k];
  574. }
  575. cleaned[`${next}Settings`] = newStreamSlice(next);
  576. // mKCP wants a UDP mask wrapper on the FinalMask side; seed it with
  577. // `mkcp-legacy` so the inbound boots with a sensible default
  578. // instead of unobfuscated mKCP traffic. The user can still edit or
  579. // clear the mask via the FinalMask section.
  580. if (next === 'kcp') {
  581. const fm = (cleaned.finalmask as Record<string, unknown> | undefined) ?? {};
  582. const udp = Array.isArray(fm.udp) ? (fm.udp as unknown[]) : [];
  583. const hasMkcp = udp.some((m) => {
  584. const entry = m as { type?: string };
  585. return entry?.type === 'mkcp-legacy';
  586. });
  587. if (!hasMkcp) {
  588. cleaned.finalmask = {
  589. ...fm,
  590. udp: [...udp, { type: 'mkcp-legacy', settings: { header: '', value: '' } }],
  591. };
  592. }
  593. }
  594. form.setFieldValue('streamSettings', cleaned);
  595. };
  596. const streamTab = (
  597. <>
  598. {protocol !== Protocols.HYSTERIA && (
  599. <Form.Item label={t('transmission')} name={['streamSettings', 'network']}>
  600. <Select
  601. style={{ width: '75%' }}
  602. onChange={onNetworkChange}
  603. options={[
  604. { value: 'tcp', label: 'RAW' },
  605. { value: 'kcp', label: 'mKCP' },
  606. { value: 'ws', label: 'WebSocket' },
  607. { value: 'grpc', label: 'gRPC' },
  608. { value: 'httpupgrade', label: 'HTTPUpgrade' },
  609. { value: 'xhttp', label: 'XHTTP' },
  610. ]}
  611. />
  612. </Form.Item>
  613. )}
  614. {/* Inbound Hysteria stream sub-form. The transport for hysteria
  615. isn't user-selectable (always 'hysteria'), so the network
  616. dropdown is hidden above. Fields here mirror the legacy
  617. HysteriaStreamSettings inbound class: version is locked to 2,
  618. auth + udpIdleTimeout are required, masquerade is an optional
  619. sub-object that lets xray-core disguise the listener as an
  620. HTTP server when probed. */}
  621. {protocol === Protocols.HYSTERIA && <HysteriaFields form={form} />}
  622. {network === 'tcp' && <RawForm />}
  623. {network === 'ws' && <WsForm />}
  624. {network === 'grpc' && <GrpcForm />}
  625. {network === 'xhttp' && <XhttpForm form={form} />}
  626. {network === 'httpupgrade' && <HttpUpgradeForm />}
  627. {network === 'kcp' && <KcpForm />}
  628. <ExternalProxyForm toggleExternalProxy={toggleExternalProxy} />
  629. <SockoptForm toggleSockopt={toggleSockopt} />
  630. <FinalMaskForm
  631. name={['streamSettings', 'finalmask']}
  632. network={network as string}
  633. protocol={protocol}
  634. form={form}
  635. />
  636. </>
  637. );
  638. const securityTab = (
  639. <>
  640. <Form.Item name={['streamSettings', 'security']} hidden noStyle>
  641. <Input />
  642. </Form.Item>
  643. <Form.Item label={t('pages.inbounds.securityTab')}>
  644. <Form.Item
  645. noStyle
  646. shouldUpdate={(prev, curr) =>
  647. prev.streamSettings?.security !== curr.streamSettings?.security
  648. || prev.streamSettings?.network !== curr.streamSettings?.network
  649. || prev.protocol !== curr.protocol
  650. }
  651. >
  652. {({ getFieldValue }) => {
  653. const sec = getFieldValue(['streamSettings', 'security']) ?? 'none';
  654. const net = getFieldValue(['streamSettings', 'network']) ?? '';
  655. const proto = getFieldValue('protocol') ?? '';
  656. const tlsOk = canEnableTls({ protocol: proto, streamSettings: { network: net, security: sec } });
  657. const realityOk = canEnableReality({ protocol: proto, streamSettings: { network: net, security: sec } });
  658. const tlsOnly = proto === Protocols.HYSTERIA;
  659. return (
  660. <Radio.Group
  661. value={sec}
  662. buttonStyle="solid"
  663. disabled={!tlsOk}
  664. onChange={(e) => onSecurityChange(e.target.value)}
  665. >
  666. {!tlsOnly && <Radio.Button value="none">{t('none')}</Radio.Button>}
  667. <Radio.Button value="tls">TLS</Radio.Button>
  668. {realityOk && <Radio.Button value="reality">Reality</Radio.Button>}
  669. </Radio.Group>
  670. );
  671. }}
  672. </Form.Item>
  673. </Form.Item>
  674. {security === 'tls' && (
  675. <TlsForm
  676. saving={saving}
  677. setCertFromPanel={setCertFromPanel}
  678. clearCertFiles={clearCertFiles}
  679. generateRandomPinHash={generateRandomPinHash}
  680. getNewEchCert={getNewEchCert}
  681. clearEchCert={clearEchCert}
  682. />
  683. )}
  684. {security === 'reality' && (
  685. <RealityForm
  686. saving={saving}
  687. randomizeRealityTarget={randomizeRealityTarget}
  688. randomizeShortIds={randomizeShortIds}
  689. genRealityKeypair={genRealityKeypair}
  690. clearRealityKeypair={clearRealityKeypair}
  691. genMldsa65={genMldsa65}
  692. clearMldsa65={clearMldsa65}
  693. />
  694. )}
  695. </>
  696. );
  697. const advancedTab = (
  698. <div className="advanced-shell">
  699. <div className="advanced-panel">
  700. <div className="advanced-panel__header">
  701. <div>
  702. <div className="advanced-panel__title">{t('pages.inbounds.advanced.title')}</div>
  703. <div className="advanced-panel__subtitle">{t('pages.inbounds.advanced.subtitle')}</div>
  704. </div>
  705. </div>
  706. <Tabs
  707. className="advanced-inner-tabs"
  708. items={[
  709. {
  710. key: 'all',
  711. label: t('pages.inbounds.advanced.all'),
  712. children: (
  713. <>
  714. <div className="advanced-editor-meta">
  715. {t('pages.inbounds.advanced.allHelp')}
  716. </div>
  717. <AdvancedAllEditor form={form} streamEnabled={streamEnabled} />
  718. </>
  719. ),
  720. },
  721. {
  722. key: 'settings',
  723. label: t('pages.inbounds.advanced.settings'),
  724. children: (
  725. <>
  726. <div className="advanced-editor-meta">
  727. {t('pages.inbounds.advanced.settingsHelp')}{' '}
  728. <code>{'{ settings: { ... } }'}</code>.
  729. </div>
  730. <AdvancedSliceEditor
  731. form={form}
  732. path="settings"
  733. wrapKey="settings"
  734. minHeight="320px"
  735. maxHeight="540px"
  736. />
  737. </>
  738. ),
  739. },
  740. ...(streamEnabled
  741. ? [{
  742. key: 'stream',
  743. label: t('pages.inbounds.advanced.stream'),
  744. children: (
  745. <>
  746. <div className="advanced-editor-meta">
  747. {t('pages.inbounds.advanced.streamHelp')}{' '}
  748. <code>{'{ streamSettings: { ... } }'}</code>.
  749. </div>
  750. <AdvancedSliceEditor
  751. form={form}
  752. path="streamSettings"
  753. wrapKey="streamSettings"
  754. minHeight="320px"
  755. maxHeight="540px"
  756. />
  757. </>
  758. ),
  759. }]
  760. : []),
  761. {
  762. key: 'sniffing',
  763. label: t('pages.inbounds.advanced.sniffing'),
  764. children: (
  765. <>
  766. <div className="advanced-editor-meta">
  767. {t('pages.inbounds.advanced.sniffingHelp')}{' '}
  768. <code>{'{ sniffing: { ... } }'}</code>.
  769. </div>
  770. <AdvancedSliceEditor
  771. form={form}
  772. path="sniffing"
  773. wrapKey="sniffing"
  774. minHeight="240px"
  775. maxHeight="420px"
  776. />
  777. </>
  778. ),
  779. },
  780. ]}
  781. />
  782. </div>
  783. </div>
  784. );
  785. const sniffingTab = <SniffingTab sniffingEnabled={sniffingEnabled} />;
  786. return (
  787. <>
  788. {messageContextHolder}
  789. <Modal
  790. open={open}
  791. title={title}
  792. okText={okText}
  793. cancelText={t('close')}
  794. confirmLoading={saving}
  795. mask={{ closable: false }}
  796. width={780}
  797. onOk={submit}
  798. onCancel={onClose}
  799. destroyOnHidden
  800. >
  801. <Form
  802. form={form}
  803. colon={false}
  804. labelCol={{ sm: { span: 8 } }}
  805. wrapperCol={{ sm: { span: 14 } }}
  806. labelWrap
  807. onValuesChange={onValuesChange}
  808. >
  809. <Tabs items={[
  810. // forceRender on every tab so all Form.Items register at modal
  811. // open, not lazily on first visit. Without it, AntD's items API
  812. // lazy-mounts inactive tabs — their fields don't register, so
  813. // Form.useWatch on a parent path (e.g. 'sniffing') returns the
  814. // partial-view {} until the user touches the tab and the
  815. // inner Form.Item for `sniffing.enabled` registers.
  816. { key: 'basic', label: t('pages.xray.basicTemplate'), children: basicTab, forceRender: true },
  817. ...(([
  818. Protocols.VLESS,
  819. Protocols.SHADOWSOCKS,
  820. Protocols.HTTP,
  821. Protocols.MIXED,
  822. Protocols.TUNNEL,
  823. Protocols.TUN,
  824. Protocols.WIREGUARD,
  825. Protocols.MTPROTO,
  826. ] as string[]).includes(protocol) || isFallbackHost
  827. ? [{ key: 'protocol', label: t('pages.inbounds.protocol'), children: protocolTab, forceRender: true }]
  828. : []),
  829. ...(streamEnabled
  830. ? [
  831. { key: 'stream', label: t('pages.inbounds.streamTab'), children: streamTab, forceRender: true },
  832. { key: 'security', label: t('pages.inbounds.securityTab'), children: securityTab, forceRender: true },
  833. ]
  834. : []),
  835. { key: 'sniffing', label: t('pages.inbounds.sniffingTab'), children: sniffingTab, forceRender: true },
  836. { key: 'advanced', label: t('pages.xray.advancedTemplate'), children: advancedTab, forceRender: true },
  837. ]} />
  838. </Form>
  839. </Modal>
  840. </>
  841. );
  842. }