inbound-form-adapter.ts 14 KB

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