inbound-form-adapter.test.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /// <reference types="vite/client" />
  2. import { describe, expect, it } from 'vitest';
  3. import {
  4. rawInboundToFormValues,
  5. formValuesToWirePayload,
  6. type RawInboundRow,
  7. } from '@/lib/xray/inbound-form-adapter';
  8. import { InboundFormSchema } from '@/schemas/forms/inbound-form';
  9. import { SockoptStreamSettingsSchema } from '@/schemas/protocols/stream/sockopt';
  10. // Round-trip: raw DB row → InboundFormValues → wire payload, asserting
  11. // that the JSON-stringified settings/streamSettings/sniffing in the
  12. // payload deserialize back to the same data the raw row carried.
  13. interface FixtureCase {
  14. name: string;
  15. row: RawInboundRow;
  16. expectedProtocol: string;
  17. }
  18. const vlessRow: RawInboundRow = {
  19. id: 7,
  20. port: 12345,
  21. listen: '0.0.0.0',
  22. protocol: 'vless',
  23. remark: 'edge-1',
  24. enable: true,
  25. up: 1024,
  26. down: 2048,
  27. total: 1_000_000_000,
  28. expiryTime: 0,
  29. trafficReset: 'monthly',
  30. lastTrafficResetTime: 0,
  31. tag: 'inbound-1',
  32. nodeId: null,
  33. settings: {
  34. clients: [{
  35. id: '8c14d6f7-2e3b-4a91-9d24-3f7a6b8c1e02',
  36. email: '[email protected]',
  37. flow: '',
  38. limitIp: 0,
  39. totalGB: 0,
  40. expiryTime: 0,
  41. enable: true,
  42. tgId: 0,
  43. subId: 'abc123def',
  44. comment: '',
  45. reset: 0,
  46. }],
  47. decryption: 'none',
  48. encryption: 'none',
  49. fallbacks: [],
  50. },
  51. streamSettings: {
  52. network: 'tcp',
  53. security: 'none',
  54. tcpSettings: { header: { type: 'none' } },
  55. },
  56. sniffing: {
  57. enabled: false,
  58. destOverride: ['http', 'tls', 'quic', 'fakedns'],
  59. metadataOnly: false,
  60. routeOnly: false,
  61. ipsExcluded: [],
  62. domainsExcluded: [],
  63. },
  64. } as RawInboundRow & { id: number };
  65. const cases: FixtureCase[] = [
  66. { name: 'vless tcp none', row: vlessRow, expectedProtocol: 'vless' },
  67. {
  68. name: 'string-coerced settings',
  69. row: {
  70. ...vlessRow,
  71. settings: JSON.stringify(vlessRow.settings),
  72. streamSettings: JSON.stringify(vlessRow.streamSettings),
  73. sniffing: JSON.stringify(vlessRow.sniffing),
  74. },
  75. expectedProtocol: 'vless',
  76. },
  77. {
  78. name: 'empty stream settings drop to undefined',
  79. row: { ...vlessRow, streamSettings: '' },
  80. expectedProtocol: 'vless',
  81. },
  82. {
  83. name: 'unknown trafficReset coerces to never',
  84. row: { ...vlessRow, trafficReset: 'totally-fabricated' },
  85. expectedProtocol: 'vless',
  86. },
  87. ];
  88. describe('rawInboundToFormValues', () => {
  89. for (const { name, row, expectedProtocol } of cases) {
  90. it(`maps ${name}`, () => {
  91. const values = rawInboundToFormValues(row);
  92. expect(values.protocol).toBe(expectedProtocol);
  93. expect(values.port).toBe(row.port);
  94. expect(values.remark).toBe(row.remark ?? '');
  95. if (name === 'unknown trafficReset coerces to never') {
  96. expect(values.trafficReset).toBe('never');
  97. }
  98. if (name === 'empty stream settings drop to undefined') {
  99. expect(values.streamSettings).toBeUndefined();
  100. }
  101. expect(values.shareAddrStrategy).toBe('node');
  102. expect(values.shareAddr).toBe('');
  103. });
  104. }
  105. it('produces values that the InboundFormSchema accepts', () => {
  106. const values = rawInboundToFormValues(vlessRow);
  107. const result = InboundFormSchema.safeParse(values);
  108. expect(result.success).toBe(true);
  109. });
  110. });
  111. // Regression: wireguard (UDP-only) and tunnel (dokodemo-door) have no
  112. // user-selectable transport, so the modal submits streamSettings WITHOUT a
  113. // `network` key — just `security`, plus `sockopt` for tunnel's TProxy. The
  114. // network schema must accept that transportless shape; before the transportless
  115. // union branch landed it failed with "Invalid discriminator value. Expected
  116. // 'tcp' | ..." and blocked every wireguard/tunnel save.
  117. describe('transportless streamSettings (wireguard / tunnel)', () => {
  118. it('accepts wireguard with a network-less streamSettings', () => {
  119. const result = InboundFormSchema.safeParse({
  120. port: 51820,
  121. protocol: 'wireguard',
  122. settings: { secretKey: 'cE9mYWtlLXNlY3JldC1rZXktZm9yLXVuaXQtdGVzdA==', peers: [] },
  123. streamSettings: { security: 'none' },
  124. });
  125. expect(result.success).toBe(true);
  126. });
  127. it('accepts tunnel with sockopt.tproxy and no network', () => {
  128. const result = InboundFormSchema.safeParse({
  129. port: 12345,
  130. protocol: 'tunnel',
  131. settings: { allowedNetwork: 'tcp,udp', followRedirect: true, portMap: {} },
  132. streamSettings: {
  133. security: 'none',
  134. sockopt: SockoptStreamSettingsSchema.parse({ tproxy: 'tproxy' }),
  135. },
  136. });
  137. expect(result.success).toBe(true);
  138. if (result.success) {
  139. const stream = result.data.streamSettings as {
  140. network?: unknown;
  141. sockopt?: { tproxy?: string };
  142. };
  143. expect(stream.network).toBeUndefined();
  144. expect(stream.sockopt?.tproxy).toBe('tproxy');
  145. }
  146. });
  147. it('still rejects a present-but-invalid network value', () => {
  148. const result = InboundFormSchema.safeParse({
  149. port: 12345,
  150. protocol: 'tunnel',
  151. settings: { allowedNetwork: 'tcp,udp', followRedirect: true, portMap: {} },
  152. streamSettings: { network: 'bogus', security: 'none' },
  153. });
  154. expect(result.success).toBe(false);
  155. });
  156. });
  157. describe('formValuesToWirePayload', () => {
  158. it('stringifies settings/streamSettings/sniffing with empty-array/default pruning', () => {
  159. const values = rawInboundToFormValues(vlessRow);
  160. const payload = formValuesToWirePayload(values);
  161. expect(typeof payload.settings).toBe('string');
  162. expect(typeof payload.streamSettings).toBe('string');
  163. expect(typeof payload.sniffing).toBe('string');
  164. // Empty arrays like `fallbacks: []` drop out of the payload to match
  165. // the legacy panel's minimal JSON.
  166. const parsedSettings = JSON.parse(payload.settings);
  167. const { fallbacks: _f, ...expectedSettings } = vlessRow.settings as Record<string, unknown>;
  168. expect(parsedSettings).toEqual(expectedSettings);
  169. expect(JSON.parse(payload.streamSettings)).toEqual(vlessRow.streamSettings);
  170. // Disabled sniffing collapses to the bare `{ enabled: false }`
  171. // regardless of which destOverride/metadataOnly/etc. defaults the
  172. // form carries.
  173. expect(JSON.parse(payload.sniffing)).toEqual({ enabled: false });
  174. });
  175. it('emits empty string for absent streamSettings', () => {
  176. const values = rawInboundToFormValues({ ...vlessRow, streamSettings: '' });
  177. const payload = formValuesToWirePayload(values);
  178. expect(payload.streamSettings).toBe('');
  179. });
  180. it('emits empty sniffing for mtproto (mtg-served, not Xray)', () => {
  181. const values = rawInboundToFormValues({
  182. ...vlessRow,
  183. protocol: 'mtproto',
  184. settings: { fakeTlsDomain: 'www.cloudflare.com', secret: 'ee00' },
  185. });
  186. const payload = formValuesToWirePayload(values);
  187. expect(payload.protocol).toBe('mtproto');
  188. expect(payload.sniffing).toBe('');
  189. });
  190. it('omits nodeId when null', () => {
  191. const values = rawInboundToFormValues({ ...vlessRow, nodeId: null });
  192. const payload = formValuesToWirePayload(values);
  193. expect('nodeId' in payload).toBe(false);
  194. });
  195. it('includes nodeId when set', () => {
  196. const values = rawInboundToFormValues({ ...vlessRow, nodeId: 42 });
  197. const payload = formValuesToWirePayload(values);
  198. expect(payload.nodeId).toBe(42);
  199. });
  200. it('round-trips share address strategy fields', () => {
  201. const values = rawInboundToFormValues({
  202. ...vlessRow,
  203. shareAddrStrategy: 'custom',
  204. shareAddr: 'edge.example.test',
  205. });
  206. const payload = formValuesToWirePayload(values);
  207. expect(payload.shareAddrStrategy).toBe('custom');
  208. expect(payload.shareAddr).toBe('edge.example.test');
  209. });
  210. it('round-trips top-level fields through raw → values → payload → values', () => {
  211. // settings/streamSettings/sniffing don't round-trip byte-equal because
  212. // the wire payload prunes empty arrays and collapses disabled sniffing
  213. // to `{ enabled: false }`. Top-level scalars and the protocol picker
  214. // must still survive the round trip without loss.
  215. const original = rawInboundToFormValues(vlessRow);
  216. const payload = formValuesToWirePayload(original);
  217. const replay = rawInboundToFormValues({
  218. port: payload.port,
  219. listen: payload.listen,
  220. protocol: payload.protocol,
  221. tag: payload.tag,
  222. settings: payload.settings,
  223. streamSettings: payload.streamSettings,
  224. sniffing: payload.sniffing,
  225. up: payload.up,
  226. down: payload.down,
  227. total: payload.total,
  228. remark: payload.remark,
  229. enable: payload.enable,
  230. expiryTime: payload.expiryTime,
  231. trafficReset: payload.trafficReset,
  232. lastTrafficResetTime: payload.lastTrafficResetTime,
  233. nodeId: payload.nodeId ?? null,
  234. });
  235. expect(replay.protocol).toBe(original.protocol);
  236. expect(replay.port).toBe(original.port);
  237. expect(replay.tag).toBe(original.tag);
  238. expect(replay.listen).toBe(original.listen);
  239. expect(replay.up).toBe(original.up);
  240. expect(replay.down).toBe(original.down);
  241. expect(replay.streamSettings).toEqual(original.streamSettings);
  242. });
  243. });