inbound-form-adapter.test.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. });
  102. }
  103. it('produces values that the InboundFormSchema accepts', () => {
  104. const values = rawInboundToFormValues(vlessRow);
  105. const result = InboundFormSchema.safeParse(values);
  106. expect(result.success).toBe(true);
  107. });
  108. });
  109. // Regression: wireguard (UDP-only) and tunnel (dokodemo-door) have no
  110. // user-selectable transport, so the modal submits streamSettings WITHOUT a
  111. // `network` key — just `security`, plus `sockopt` for tunnel's TProxy. The
  112. // network schema must accept that transportless shape; before the transportless
  113. // union branch landed it failed with "Invalid discriminator value. Expected
  114. // 'tcp' | ..." and blocked every wireguard/tunnel save.
  115. describe('transportless streamSettings (wireguard / tunnel)', () => {
  116. it('accepts wireguard with a network-less streamSettings', () => {
  117. const result = InboundFormSchema.safeParse({
  118. port: 51820,
  119. protocol: 'wireguard',
  120. settings: { secretKey: 'cE9mYWtlLXNlY3JldC1rZXktZm9yLXVuaXQtdGVzdA==', peers: [] },
  121. streamSettings: { security: 'none' },
  122. });
  123. expect(result.success).toBe(true);
  124. });
  125. it('accepts tunnel with sockopt.tproxy and no network', () => {
  126. const result = InboundFormSchema.safeParse({
  127. port: 12345,
  128. protocol: 'tunnel',
  129. settings: { allowedNetwork: 'tcp,udp', followRedirect: true, portMap: {} },
  130. streamSettings: {
  131. security: 'none',
  132. sockopt: SockoptStreamSettingsSchema.parse({ tproxy: 'tproxy' }),
  133. },
  134. });
  135. expect(result.success).toBe(true);
  136. if (result.success) {
  137. const stream = result.data.streamSettings as {
  138. network?: unknown;
  139. sockopt?: { tproxy?: string };
  140. };
  141. expect(stream.network).toBeUndefined();
  142. expect(stream.sockopt?.tproxy).toBe('tproxy');
  143. }
  144. });
  145. it('still rejects a present-but-invalid network value', () => {
  146. const result = InboundFormSchema.safeParse({
  147. port: 12345,
  148. protocol: 'tunnel',
  149. settings: { allowedNetwork: 'tcp,udp', followRedirect: true, portMap: {} },
  150. streamSettings: { network: 'bogus', security: 'none' },
  151. });
  152. expect(result.success).toBe(false);
  153. });
  154. });
  155. describe('formValuesToWirePayload', () => {
  156. it('stringifies settings/streamSettings/sniffing with empty-array/default pruning', () => {
  157. const values = rawInboundToFormValues(vlessRow);
  158. const payload = formValuesToWirePayload(values);
  159. expect(typeof payload.settings).toBe('string');
  160. expect(typeof payload.streamSettings).toBe('string');
  161. expect(typeof payload.sniffing).toBe('string');
  162. // Empty arrays like `fallbacks: []` drop out of the payload to match
  163. // the legacy panel's minimal JSON.
  164. const parsedSettings = JSON.parse(payload.settings);
  165. const { fallbacks: _f, ...expectedSettings } = vlessRow.settings as Record<string, unknown>;
  166. expect(parsedSettings).toEqual(expectedSettings);
  167. expect(JSON.parse(payload.streamSettings)).toEqual(vlessRow.streamSettings);
  168. // Disabled sniffing collapses to the bare `{ enabled: false }`
  169. // regardless of which destOverride/metadataOnly/etc. defaults the
  170. // form carries.
  171. expect(JSON.parse(payload.sniffing)).toEqual({ enabled: false });
  172. });
  173. it('emits empty string for absent streamSettings', () => {
  174. const values = rawInboundToFormValues({ ...vlessRow, streamSettings: '' });
  175. const payload = formValuesToWirePayload(values);
  176. expect(payload.streamSettings).toBe('');
  177. });
  178. it('emits empty sniffing for mtproto (mtg-served, not Xray)', () => {
  179. const values = rawInboundToFormValues({
  180. ...vlessRow,
  181. protocol: 'mtproto',
  182. settings: { fakeTlsDomain: 'www.cloudflare.com', secret: 'ee00' },
  183. });
  184. const payload = formValuesToWirePayload(values);
  185. expect(payload.protocol).toBe('mtproto');
  186. expect(payload.sniffing).toBe('');
  187. });
  188. it('omits nodeId when null', () => {
  189. const values = rawInboundToFormValues({ ...vlessRow, nodeId: null });
  190. const payload = formValuesToWirePayload(values);
  191. expect('nodeId' in payload).toBe(false);
  192. });
  193. it('includes nodeId when set', () => {
  194. const values = rawInboundToFormValues({ ...vlessRow, nodeId: 42 });
  195. const payload = formValuesToWirePayload(values);
  196. expect(payload.nodeId).toBe(42);
  197. });
  198. it('round-trips top-level fields through raw → values → payload → values', () => {
  199. // settings/streamSettings/sniffing don't round-trip byte-equal because
  200. // the wire payload prunes empty arrays and collapses disabled sniffing
  201. // to `{ enabled: false }`. Top-level scalars and the protocol picker
  202. // must still survive the round trip without loss.
  203. const original = rawInboundToFormValues(vlessRow);
  204. const payload = formValuesToWirePayload(original);
  205. const replay = rawInboundToFormValues({
  206. port: payload.port,
  207. listen: payload.listen,
  208. protocol: payload.protocol,
  209. tag: payload.tag,
  210. settings: payload.settings,
  211. streamSettings: payload.streamSettings,
  212. sniffing: payload.sniffing,
  213. up: payload.up,
  214. down: payload.down,
  215. total: payload.total,
  216. remark: payload.remark,
  217. enable: payload.enable,
  218. expiryTime: payload.expiryTime,
  219. trafficReset: payload.trafficReset,
  220. lastTrafficResetTime: payload.lastTrafficResetTime,
  221. nodeId: payload.nodeId ?? null,
  222. });
  223. expect(replay.protocol).toBe(original.protocol);
  224. expect(replay.port).toBe(original.port);
  225. expect(replay.tag).toBe(original.tag);
  226. expect(replay.listen).toBe(original.listen);
  227. expect(replay.up).toBe(original.up);
  228. expect(replay.down).toBe(original.down);
  229. expect(replay.streamSettings).toEqual(original.streamSettings);
  230. });
  231. });