InboundFormModal.tsx 39 KB

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