inbound-form-adapter.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. import type {
  2. InboundFormValues,
  3. ShareAddrStrategy,
  4. TrafficReset,
  5. } from '@/schemas/forms/inbound-form';
  6. import type { InboundSettings } from '@/schemas/protocols/inbound';
  7. import {
  8. AmneziawgClientSchema,
  9. HysteriaClientSchema,
  10. MtprotoClientSchema,
  11. ShadowsocksClientSchema,
  12. TrojanClientSchema,
  13. TuicClientSchema,
  14. VlessClientSchema,
  15. VmessClientSchema,
  16. WireguardClientSchema,
  17. } from '@/schemas/protocols/inbound';
  18. import type { StreamSettings } from '@/schemas/api/inbound';
  19. import type { Sniffing } from '@/schemas/primitives';
  20. import type { z } from 'zod';
  21. import {
  22. dropEmptyFinalMask,
  23. normalizeStreamSettingsForWire,
  24. } from '@/lib/xray/stream-wire-normalize';
  25. import { canEnableSniffing } from '@/lib/xray/protocol-capabilities';
  26. import { tlsCertUsesFiles } from '@/schemas/protocols/security/tls';
  27. import { SockoptStreamSettingsSchema } from '@/schemas/protocols/stream/sockopt';
  28. import { XHttpStreamSettingsSchema, XHttpXmuxSchema } from '@/schemas/protocols/stream/xhttp';
  29. const XMUX_DEFAULTS = XHttpXmuxSchema.parse({});
  30. // Plain-data adapter between the panel's stored inbound row shape and
  31. // the typed InboundFormValues that Form.useForm<T> carries inside
  32. // InboundFormModal. No dependency on the legacy Inbound/DBInbound
  33. // classes — the modal hands the raw row in, takes typed values out, and
  34. // on submit calls formValuesToWirePayload() to get a payload ready to
  35. // POST to /panel/api/inbounds/add or /update/:id.
  36. export interface RawInboundRow {
  37. port?: number;
  38. listen?: string;
  39. protocol?: string;
  40. tag?: string;
  41. settings?: unknown;
  42. streamSettings?: unknown;
  43. sniffing?: unknown;
  44. up?: number;
  45. down?: number;
  46. total?: number;
  47. remark?: string;
  48. enable?: boolean;
  49. expiryTime?: number;
  50. trafficReset?: string;
  51. trafficResetDay?: number;
  52. lastTrafficResetTime?: number;
  53. nodeId?: number | null;
  54. shareAddrStrategy?: string;
  55. shareAddr?: string;
  56. subSortIndex?: number;
  57. excludeFromSub?: boolean;
  58. disableFlow?: boolean;
  59. clientStats?: unknown;
  60. }
  61. // The wire payload — settings/streamSettings/sniffing arrive as JSON
  62. // strings, mirroring what the Go endpoints expect (xray-core wants the
  63. // nested config slices as strings to round-trip through its loader).
  64. export interface WireInboundPayload {
  65. up: number;
  66. down: number;
  67. total: number;
  68. remark: string;
  69. enable: boolean;
  70. expiryTime: number;
  71. trafficReset: TrafficReset;
  72. trafficResetDay: number;
  73. lastTrafficResetTime: number;
  74. listen: string;
  75. port: number;
  76. protocol: string;
  77. settings: string;
  78. streamSettings: string;
  79. sniffing: string;
  80. tag: string;
  81. clientStats?: unknown;
  82. nodeId?: number;
  83. shareAddrStrategy: ShareAddrStrategy;
  84. shareAddr: string;
  85. subSortIndex: number;
  86. excludeFromSub: boolean;
  87. disableFlow: boolean;
  88. }
  89. function coerceJsonObject(value: unknown): Record<string, unknown> {
  90. if (value == null) return {};
  91. if (typeof value === 'object' && !Array.isArray(value)) {
  92. return value as Record<string, unknown>;
  93. }
  94. if (typeof value !== 'string') return {};
  95. const trimmed = value.trim();
  96. if (trimmed === '') return {};
  97. try {
  98. const parsed = JSON.parse(trimmed);
  99. return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
  100. ? (parsed as Record<string, unknown>)
  101. : {};
  102. } catch {
  103. return {};
  104. }
  105. }
  106. const TRAFFIC_RESETS: TrafficReset[] = ['never', 'hourly', 'daily', 'weekly', 'monthly'];
  107. const SHARE_ADDR_STRATEGIES: ShareAddrStrategy[] = ['node', 'listen', 'custom'];
  108. function coerceTrafficReset(v: unknown): TrafficReset {
  109. return typeof v === 'string' && (TRAFFIC_RESETS as string[]).includes(v)
  110. ? (v as TrafficReset)
  111. : 'never';
  112. }
  113. function coerceShareAddrStrategy(v: unknown): ShareAddrStrategy {
  114. return typeof v === 'string' && (SHARE_ADDR_STRATEGIES as string[]).includes(v)
  115. ? (v as ShareAddrStrategy)
  116. : 'node';
  117. }
  118. // Network values that map to a required `${network}Settings` key in
  119. // NetworkSettingsSchema. Older saved inbounds may be missing the per-
  120. // network sub-object (the legacy panel sometimes emitted streamSettings
  121. // without it, and an earlier panel-side prune wrongly stripped empty
  122. // `tcpSettings: {}` out of the wire payload). Reseat an empty object
  123. // here so InboundFormSchema.safeParse doesn't blow up at edit time.
  124. const NETWORK_SETTINGS_KEY: Record<string, string> = {
  125. tcp: 'tcpSettings',
  126. kcp: 'kcpSettings',
  127. ws: 'wsSettings',
  128. grpc: 'grpcSettings',
  129. httpupgrade: 'httpupgradeSettings',
  130. xhttp: 'xhttpSettings',
  131. hysteria: 'hysteriaSettings',
  132. };
  133. function healStreamNetworkKey(stream: Record<string, unknown>): void {
  134. if (typeof stream.method === 'string' && stream.method !== '') {
  135. stream.network = stream.method;
  136. }
  137. delete stream.method;
  138. const network = typeof stream.network === 'string' ? stream.network : '';
  139. const key = NETWORK_SETTINGS_KEY[network];
  140. if (!key) return;
  141. if (stream[key] == null || typeof stream[key] !== 'object') {
  142. stream[key] = {};
  143. }
  144. }
  145. function tlsCerts(stream: Record<string, unknown>): Record<string, unknown>[] {
  146. const tls = stream.tlsSettings as { certificates?: unknown } | undefined;
  147. return Array.isArray(tls?.certificates) ? (tls.certificates as Record<string, unknown>[]) : [];
  148. }
  149. function synthesizeTlsCertUseFile(stream: Record<string, unknown>): void {
  150. for (const c of tlsCerts(stream)) c.useFile = tlsCertUsesFiles(c);
  151. }
  152. function stripTlsCertUseFile(stream: Record<string, unknown>): void {
  153. for (const c of tlsCerts(stream)) delete c.useFile;
  154. }
  155. export function rawInboundToFormValues(row: RawInboundRow): InboundFormValues {
  156. const protocol = (row.protocol || 'vless') as InboundSettings['protocol'];
  157. const settings = coerceJsonObject(row.settings) as InboundSettings['settings'];
  158. const rawStream = coerceJsonObject(row.streamSettings);
  159. const streamSettings =
  160. Object.keys(rawStream).length > 0 ? (rawStream as StreamSettings) : undefined;
  161. if (streamSettings) {
  162. healStreamNetworkKey(streamSettings as unknown as Record<string, unknown>);
  163. synthesizeTlsCertUseFile(streamSettings as unknown as Record<string, unknown>);
  164. const streamRecord = streamSettings as unknown as Record<string, unknown>;
  165. const xh = streamRecord.xhttpSettings;
  166. if (xh && typeof xh === 'object' && !Array.isArray(xh)) {
  167. const parsed = XHttpStreamSettingsSchema.safeParse(xh);
  168. const xhttp = (parsed.success ? parsed.data : xh) as Record<string, unknown>;
  169. streamRecord.xhttpSettings = xhttp;
  170. const xmux = xhttp.xmux;
  171. if (xmux && typeof xmux === 'object' && !Array.isArray(xmux)) {
  172. xhttp.enableXmux = true;
  173. xhttp.xmux = { ...XMUX_DEFAULTS, ...(xmux as Record<string, unknown>) };
  174. }
  175. }
  176. const so = streamRecord.sockopt;
  177. if (so && typeof so === 'object' && !Array.isArray(so)) {
  178. const raw = { ...(so as Record<string, unknown>) };
  179. // Imported/API configs may use lowercase v6only; the form key is V6Only.
  180. if ('v6only' in raw) {
  181. if (!('V6Only' in raw)) raw.V6Only = Boolean(raw.v6only);
  182. delete raw.v6only;
  183. }
  184. const parsed = SockoptStreamSettingsSchema.safeParse(raw);
  185. if (parsed.success) {
  186. streamRecord.sockopt = { ...raw, ...parsed.data };
  187. } else {
  188. streamRecord.sockopt = raw;
  189. }
  190. }
  191. }
  192. const sniffing = coerceJsonObject(row.sniffing) as unknown as Sniffing;
  193. return {
  194. remark: row.remark ?? '',
  195. enable: row.enable ?? true,
  196. port: row.port ?? 0,
  197. listen: row.listen ?? '',
  198. tag: row.tag ?? '',
  199. expiryTime: row.expiryTime ?? 0,
  200. sniffing,
  201. streamSettings,
  202. up: row.up ?? 0,
  203. down: row.down ?? 0,
  204. total: row.total ?? 0,
  205. trafficReset: coerceTrafficReset(row.trafficReset),
  206. trafficResetDay: Math.min(31, Math.max(1, row.trafficResetDay ?? 1)),
  207. lastTrafficResetTime: row.lastTrafficResetTime ?? 0,
  208. nodeId: row.nodeId ?? null,
  209. shareAddrStrategy: coerceShareAddrStrategy(row.shareAddrStrategy),
  210. shareAddr: row.shareAddr ?? '',
  211. subSortIndex: row.subSortIndex == null || row.subSortIndex === 0 ? 1 : row.subSortIndex,
  212. excludeFromSub: row.excludeFromSub ?? false,
  213. disableFlow: row.disableFlow ?? false,
  214. protocol,
  215. settings,
  216. } as InboundFormValues;
  217. }
  218. // Recursively strip undefined leaves from the wire payload. Empty arrays
  219. // and empty objects are PRESERVED — legacy XrayCommonClass.toJson() kept
  220. // shells like `tcpSettings: {}` so xray-core picks up its built-in
  221. // defaults, and stripping them led the FE to lose required-but-empty
  222. // arrays (vless clients, wireguard peers, etc.) which the Go side then
  223. // serialized back as `null`. Primitive values (including 0, false, '')
  224. // are kept verbatim.
  225. export function pruneEmpty(value: unknown): unknown {
  226. if (Array.isArray(value)) {
  227. return value.map(pruneEmpty);
  228. }
  229. if (value !== null && typeof value === 'object') {
  230. const out: Record<string, unknown> = {};
  231. for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
  232. const p = pruneEmpty(v);
  233. if (p === undefined) continue;
  234. out[k] = p;
  235. }
  236. return out;
  237. }
  238. return value;
  239. }
  240. // Per-protocol client field whitelist — the Zod schemas in
  241. // schemas/protocols/inbound/<proto>.ts define which keys a given
  242. // protocol's clients accept on the wire. When a global client is created
  243. // the panel may persist cross-protocol fields on the same row (`auth` for
  244. // hysteria, `password` for trojan, `security` for vmess, etc.); rendering
  245. // those inside a vless inbound's settings.clients is confusing and rides
  246. // dead weight in the wire payload. Parsing through the protocol's schema
  247. // gives us the canonical projection.
  248. function clientSchemaForProtocol(protocol: string): z.ZodType | null {
  249. switch (protocol) {
  250. case 'vless':
  251. return VlessClientSchema;
  252. case 'vmess':
  253. return VmessClientSchema;
  254. case 'trojan':
  255. return TrojanClientSchema;
  256. case 'shadowsocks':
  257. return ShadowsocksClientSchema;
  258. case 'hysteria':
  259. return HysteriaClientSchema;
  260. case 'wireguard':
  261. return WireguardClientSchema;
  262. case 'mtproto':
  263. return MtprotoClientSchema;
  264. case 'amneziawg':
  265. return AmneziawgClientSchema;
  266. case 'tuic':
  267. return TuicClientSchema;
  268. default:
  269. return null;
  270. }
  271. }
  272. export function normalizeClients(protocol: string, clients: unknown): unknown {
  273. const schema = clientSchemaForProtocol(protocol);
  274. if (!schema || !Array.isArray(clients)) return clients;
  275. return clients.map((c) => {
  276. const parsed = schema.safeParse(c);
  277. return parsed.success ? parsed.data : c;
  278. });
  279. }
  280. // Sniffing normalizer matching the legacy Sniffing.toJson(): when
  281. // disabled the payload is the bare `{ enabled: false }` regardless of
  282. // what the form holds; when enabled, only non-default fields ride.
  283. export function normalizeSniffing(s: Sniffing | undefined): Record<string, unknown> {
  284. if (!s || !s.enabled) return { enabled: false };
  285. const out: Record<string, unknown> = {
  286. enabled: true,
  287. destOverride: s.destOverride,
  288. };
  289. if (s.metadataOnly) out.metadataOnly = true;
  290. if (s.routeOnly) out.routeOnly = true;
  291. if (s.ipsExcluded?.length) out.ipsExcluded = s.ipsExcluded;
  292. if (s.domainsExcluded?.length) out.domainsExcluded = s.domainsExcluded;
  293. return out;
  294. }
  295. // Drops cosmetic empty-array keys that legacy XrayCommonClass.toJson()
  296. // explicitly skipped (fallbacks/finalmask). Mutates the pruned settings
  297. // objects in place; called AFTER pruneEmpty so we can lean on the
  298. // already-shallow shape.
  299. export function dropLegacyOptionalEmpties(
  300. settings: Record<string, unknown>,
  301. stream: Record<string, unknown> | undefined,
  302. ): void {
  303. // VLESS/Trojan emit `fallbacks` only when non-empty.
  304. const fb = settings.fallbacks;
  305. if (Array.isArray(fb) && fb.length === 0) delete settings.fallbacks;
  306. if (stream) {
  307. dropEmptyFinalMask(stream);
  308. // Hysteria's per-client auth lives in settings.clients[*].auth; the
  309. // streamSettings.hysteriaSettings.auth slot is a holdover from older
  310. // hysteria builds and serves no purpose on the inbound side, so an
  311. // empty value shouldn't ride along in the JSON payload.
  312. const hs = stream.hysteriaSettings as { auth?: string } | undefined;
  313. if (hs && typeof hs === 'object' && (hs.auth === '' || hs.auth == null)) {
  314. delete hs.auth;
  315. }
  316. }
  317. }
  318. // An existing inbound's clients change only through the client endpoints, so
  319. // the edit form neither loads them nor sends them back.
  320. export function withoutClients(values: InboundFormValues): InboundFormValues {
  321. const settings = { ...(values.settings as Record<string, unknown> | undefined) };
  322. delete settings.clients;
  323. return { ...values, settings } as InboundFormValues;
  324. }
  325. export function formValuesToWirePayload(
  326. values: InboundFormValues,
  327. options: { omitClients?: boolean } = {},
  328. ): WireInboundPayload {
  329. const settingsPruned = (pruneEmpty(values.settings ?? {}) ?? {}) as Record<string, unknown>;
  330. if (options.omitClients) {
  331. delete settingsPruned.clients;
  332. } else if (Array.isArray(settingsPruned.clients)) {
  333. settingsPruned.clients = normalizeClients(values.protocol, settingsPruned.clients);
  334. }
  335. let streamPruned = values.streamSettings
  336. ? ((pruneEmpty(values.streamSettings) ?? {}) as Record<string, unknown>)
  337. : undefined;
  338. if (streamPruned) {
  339. streamPruned = normalizeStreamSettingsForWire(streamPruned, { side: 'inbound' });
  340. stripTlsCertUseFile(streamPruned);
  341. }
  342. dropLegacyOptionalEmpties(settingsPruned, streamPruned);
  343. const payload: WireInboundPayload = {
  344. up: values.up,
  345. down: values.down,
  346. total: values.total,
  347. remark: values.remark,
  348. enable: values.enable,
  349. expiryTime: values.expiryTime,
  350. trafficReset: values.trafficReset,
  351. trafficResetDay: values.trafficResetDay,
  352. lastTrafficResetTime: values.lastTrafficResetTime,
  353. listen: values.listen,
  354. port: values.port,
  355. protocol: values.protocol,
  356. settings: JSON.stringify(settingsPruned),
  357. streamSettings: streamPruned ? JSON.stringify(streamPruned) : '',
  358. // mtproto is mtg-served, not Xray, so sniffing never applies — emit empty
  359. // rather than the default { enabled: false } so the row carries no sniffing.
  360. sniffing: canEnableSniffing({ protocol: values.protocol })
  361. ? JSON.stringify(normalizeSniffing(values.sniffing))
  362. : '',
  363. tag: values.tag,
  364. shareAddrStrategy: values.shareAddrStrategy,
  365. shareAddr: values.shareAddr,
  366. subSortIndex: values.subSortIndex,
  367. excludeFromSub: values.excludeFromSub,
  368. disableFlow: values.disableFlow,
  369. };
  370. if (values.nodeId != null) payload.nodeId = values.nodeId;
  371. return payload;
  372. }