InboundFormModal.tsx 38 KB

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