1
0

inbound.js 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172
  1. const Protocols = {
  2. VMESS: 'vmess',
  3. VLESS: 'vless',
  4. TROJAN: 'trojan',
  5. SHADOWSOCKS: 'shadowsocks',
  6. WIREGUARD: 'wireguard',
  7. HYSTERIA: 'hysteria',
  8. MIXED: 'mixed',
  9. HTTP: 'http',
  10. TUNNEL: 'tunnel',
  11. TUN: 'tun',
  12. };
  13. const SSMethods = {
  14. CHACHA20_POLY1305: 'chacha20-poly1305',
  15. CHACHA20_IETF_POLY1305: 'chacha20-ietf-poly1305',
  16. XCHACHA20_IETF_POLY1305: 'xchacha20-ietf-poly1305',
  17. BLAKE3_AES_128_GCM: '2022-blake3-aes-128-gcm',
  18. BLAKE3_AES_256_GCM: '2022-blake3-aes-256-gcm',
  19. BLAKE3_CHACHA20_POLY1305: '2022-blake3-chacha20-poly1305',
  20. };
  21. const TLS_FLOW_CONTROL = {
  22. VISION: "xtls-rprx-vision",
  23. VISION_UDP443: "xtls-rprx-vision-udp443",
  24. };
  25. const TLS_VERSION_OPTION = {
  26. TLS10: "1.0",
  27. TLS11: "1.1",
  28. TLS12: "1.2",
  29. TLS13: "1.3",
  30. };
  31. const TLS_CIPHER_OPTION = {
  32. AES_128_GCM: "TLS_AES_128_GCM_SHA256",
  33. AES_256_GCM: "TLS_AES_256_GCM_SHA384",
  34. CHACHA20_POLY1305: "TLS_CHACHA20_POLY1305_SHA256",
  35. ECDHE_ECDSA_AES_128_CBC: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
  36. ECDHE_ECDSA_AES_256_CBC: "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
  37. ECDHE_RSA_AES_128_CBC: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
  38. ECDHE_RSA_AES_256_CBC: "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
  39. ECDHE_ECDSA_AES_128_GCM: "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
  40. ECDHE_ECDSA_AES_256_GCM: "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
  41. ECDHE_RSA_AES_128_GCM: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
  42. ECDHE_RSA_AES_256_GCM: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
  43. ECDHE_ECDSA_CHACHA20_POLY1305: "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
  44. ECDHE_RSA_CHACHA20_POLY1305: "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
  45. };
  46. const UTLS_FINGERPRINT = {
  47. UTLS_CHROME: "chrome",
  48. UTLS_FIREFOX: "firefox",
  49. UTLS_SAFARI: "safari",
  50. UTLS_IOS: "ios",
  51. UTLS_android: "android",
  52. UTLS_EDGE: "edge",
  53. UTLS_360: "360",
  54. UTLS_QQ: "qq",
  55. UTLS_RANDOM: "random",
  56. UTLS_RANDOMIZED: "randomized",
  57. UTLS_RONDOMIZEDNOALPN: "randomizednoalpn",
  58. UTLS_UNSAFE: "unsafe",
  59. };
  60. const ALPN_OPTION = {
  61. H3: "h3",
  62. H2: "h2",
  63. HTTP1: "http/1.1",
  64. };
  65. const SNIFFING_OPTION = {
  66. HTTP: "http",
  67. TLS: "tls",
  68. QUIC: "quic",
  69. FAKEDNS: "fakedns"
  70. };
  71. const USAGE_OPTION = {
  72. ENCIPHERMENT: "encipherment",
  73. VERIFY: "verify",
  74. ISSUE: "issue",
  75. };
  76. const DOMAIN_STRATEGY_OPTION = {
  77. AS_IS: "AsIs",
  78. USE_IP: "UseIP",
  79. USE_IPV6V4: "UseIPv6v4",
  80. USE_IPV6: "UseIPv6",
  81. USE_IPV4V6: "UseIPv4v6",
  82. USE_IPV4: "UseIPv4",
  83. FORCE_IP: "ForceIP",
  84. FORCE_IPV6V4: "ForceIPv6v4",
  85. FORCE_IPV6: "ForceIPv6",
  86. FORCE_IPV4V6: "ForceIPv4v6",
  87. FORCE_IPV4: "ForceIPv4",
  88. };
  89. const TCP_CONGESTION_OPTION = {
  90. BBR: "bbr",
  91. CUBIC: "cubic",
  92. RENO: "reno",
  93. };
  94. const USERS_SECURITY = {
  95. AES_128_GCM: "aes-128-gcm",
  96. CHACHA20_POLY1305: "chacha20-poly1305",
  97. AUTO: "auto",
  98. NONE: "none",
  99. ZERO: "zero",
  100. };
  101. const MODE_OPTION = {
  102. AUTO: "auto",
  103. PACKET_UP: "packet-up",
  104. STREAM_UP: "stream-up",
  105. STREAM_ONE: "stream-one",
  106. };
  107. Object.freeze(Protocols);
  108. Object.freeze(SSMethods);
  109. Object.freeze(TLS_FLOW_CONTROL);
  110. Object.freeze(TLS_VERSION_OPTION);
  111. Object.freeze(TLS_CIPHER_OPTION);
  112. Object.freeze(UTLS_FINGERPRINT);
  113. Object.freeze(ALPN_OPTION);
  114. Object.freeze(SNIFFING_OPTION);
  115. Object.freeze(USAGE_OPTION);
  116. Object.freeze(DOMAIN_STRATEGY_OPTION);
  117. Object.freeze(TCP_CONGESTION_OPTION);
  118. Object.freeze(USERS_SECURITY);
  119. Object.freeze(MODE_OPTION);
  120. class XrayCommonClass {
  121. static toJsonArray(arr) {
  122. return arr.map(obj => obj.toJson());
  123. }
  124. static fromJson() {
  125. return new XrayCommonClass();
  126. }
  127. toJson() {
  128. return this;
  129. }
  130. toString(format = true) {
  131. return format ? JSON.stringify(this.toJson(), null, 2) : JSON.stringify(this.toJson());
  132. }
  133. static toHeaders(v2Headers) {
  134. let newHeaders = [];
  135. if (v2Headers) {
  136. Object.keys(v2Headers).forEach(key => {
  137. let values = v2Headers[key];
  138. if (typeof (values) === 'string') {
  139. newHeaders.push({ name: key, value: values });
  140. } else {
  141. for (let i = 0; i < values.length; ++i) {
  142. newHeaders.push({ name: key, value: values[i] });
  143. }
  144. }
  145. });
  146. }
  147. return newHeaders;
  148. }
  149. static toV2Headers(headers, arr = true) {
  150. let v2Headers = {};
  151. for (let i = 0; i < headers.length; ++i) {
  152. let name = headers[i].name;
  153. let value = headers[i].value;
  154. if (ObjectUtil.isEmpty(name) || ObjectUtil.isEmpty(value)) {
  155. continue;
  156. }
  157. if (!(name in v2Headers)) {
  158. v2Headers[name] = arr ? [value] : value;
  159. } else {
  160. if (arr) {
  161. v2Headers[name].push(value);
  162. } else {
  163. v2Headers[name] = value;
  164. }
  165. }
  166. }
  167. return v2Headers;
  168. }
  169. }
  170. class TcpStreamSettings extends XrayCommonClass {
  171. constructor(
  172. acceptProxyProtocol = false,
  173. type = 'none',
  174. request = new TcpStreamSettings.TcpRequest(),
  175. response = new TcpStreamSettings.TcpResponse(),
  176. ) {
  177. super();
  178. this.acceptProxyProtocol = acceptProxyProtocol;
  179. this.type = type;
  180. this.request = request;
  181. this.response = response;
  182. }
  183. static fromJson(json = {}) {
  184. let header = json.header;
  185. if (!header) {
  186. header = {};
  187. }
  188. return new TcpStreamSettings(json.acceptProxyProtocol,
  189. header.type,
  190. TcpStreamSettings.TcpRequest.fromJson(header.request),
  191. TcpStreamSettings.TcpResponse.fromJson(header.response),
  192. );
  193. }
  194. toJson() {
  195. return {
  196. acceptProxyProtocol: this.acceptProxyProtocol,
  197. header: {
  198. type: this.type,
  199. request: this.type === 'http' ? this.request.toJson() : undefined,
  200. response: this.type === 'http' ? this.response.toJson() : undefined,
  201. },
  202. };
  203. }
  204. }
  205. TcpStreamSettings.TcpRequest = class extends XrayCommonClass {
  206. constructor(
  207. version = '1.1',
  208. method = 'GET',
  209. path = ['/'],
  210. headers = [],
  211. ) {
  212. super();
  213. this.version = version;
  214. this.method = method;
  215. this.path = path.length === 0 ? ['/'] : path;
  216. this.headers = headers;
  217. }
  218. addPath(path) {
  219. this.path.push(path);
  220. }
  221. removePath(index) {
  222. this.path.splice(index, 1);
  223. }
  224. addHeader(name, value) {
  225. this.headers.push({ name: name, value: value });
  226. }
  227. removeHeader(index) {
  228. this.headers.splice(index, 1);
  229. }
  230. static fromJson(json = {}) {
  231. return new TcpStreamSettings.TcpRequest(
  232. json.version,
  233. json.method,
  234. json.path,
  235. XrayCommonClass.toHeaders(json.headers),
  236. );
  237. }
  238. toJson() {
  239. return {
  240. version: this.version,
  241. method: this.method,
  242. path: ObjectUtil.clone(this.path),
  243. headers: XrayCommonClass.toV2Headers(this.headers),
  244. };
  245. }
  246. };
  247. TcpStreamSettings.TcpResponse = class extends XrayCommonClass {
  248. constructor(
  249. version = '1.1',
  250. status = '200',
  251. reason = 'OK',
  252. headers = [],
  253. ) {
  254. super();
  255. this.version = version;
  256. this.status = status;
  257. this.reason = reason;
  258. this.headers = headers;
  259. }
  260. addHeader(name, value) {
  261. this.headers.push({ name: name, value: value });
  262. }
  263. removeHeader(index) {
  264. this.headers.splice(index, 1);
  265. }
  266. static fromJson(json = {}) {
  267. return new TcpStreamSettings.TcpResponse(
  268. json.version,
  269. json.status,
  270. json.reason,
  271. XrayCommonClass.toHeaders(json.headers),
  272. );
  273. }
  274. toJson() {
  275. return {
  276. version: this.version,
  277. status: this.status,
  278. reason: this.reason,
  279. headers: XrayCommonClass.toV2Headers(this.headers),
  280. };
  281. }
  282. };
  283. class KcpStreamSettings extends XrayCommonClass {
  284. constructor(
  285. mtu = 1350,
  286. tti = 20,
  287. uplinkCapacity = 5,
  288. downlinkCapacity = 20,
  289. cwndMultiplier = 1,
  290. maxSendingWindow = 2097152,
  291. ) {
  292. super();
  293. this.mtu = mtu;
  294. this.tti = tti;
  295. this.upCap = uplinkCapacity;
  296. this.downCap = downlinkCapacity;
  297. this.cwndMultiplier = cwndMultiplier;
  298. this.maxSendingWindow = maxSendingWindow;
  299. }
  300. static fromJson(json = {}) {
  301. return new KcpStreamSettings(
  302. json.mtu,
  303. json.tti,
  304. json.uplinkCapacity,
  305. json.downlinkCapacity,
  306. json.cwndMultiplier,
  307. json.maxSendingWindow,
  308. );
  309. }
  310. toJson() {
  311. return {
  312. mtu: this.mtu,
  313. tti: this.tti,
  314. uplinkCapacity: this.upCap,
  315. downlinkCapacity: this.downCap,
  316. cwndMultiplier: this.cwndMultiplier,
  317. maxSendingWindow: this.maxSendingWindow,
  318. };
  319. }
  320. }
  321. class WsStreamSettings extends XrayCommonClass {
  322. constructor(
  323. acceptProxyProtocol = false,
  324. path = '/',
  325. host = '',
  326. headers = [],
  327. heartbeatPeriod = 0,
  328. ) {
  329. super();
  330. this.acceptProxyProtocol = acceptProxyProtocol;
  331. this.path = path;
  332. this.host = host;
  333. this.headers = headers;
  334. this.heartbeatPeriod = heartbeatPeriod;
  335. }
  336. addHeader(name, value) {
  337. this.headers.push({ name: name, value: value });
  338. }
  339. removeHeader(index) {
  340. this.headers.splice(index, 1);
  341. }
  342. static fromJson(json = {}) {
  343. return new WsStreamSettings(
  344. json.acceptProxyProtocol,
  345. json.path,
  346. json.host,
  347. XrayCommonClass.toHeaders(json.headers),
  348. json.heartbeatPeriod,
  349. );
  350. }
  351. toJson() {
  352. return {
  353. acceptProxyProtocol: this.acceptProxyProtocol,
  354. path: this.path,
  355. host: this.host,
  356. headers: XrayCommonClass.toV2Headers(this.headers, false),
  357. heartbeatPeriod: this.heartbeatPeriod,
  358. };
  359. }
  360. }
  361. class GrpcStreamSettings extends XrayCommonClass {
  362. constructor(
  363. serviceName = "",
  364. authority = "",
  365. multiMode = false,
  366. ) {
  367. super();
  368. this.serviceName = serviceName;
  369. this.authority = authority;
  370. this.multiMode = multiMode;
  371. }
  372. static fromJson(json = {}) {
  373. return new GrpcStreamSettings(
  374. json.serviceName,
  375. json.authority,
  376. json.multiMode
  377. );
  378. }
  379. toJson() {
  380. return {
  381. serviceName: this.serviceName,
  382. authority: this.authority,
  383. multiMode: this.multiMode,
  384. }
  385. }
  386. }
  387. class HTTPUpgradeStreamSettings extends XrayCommonClass {
  388. constructor(
  389. acceptProxyProtocol = false,
  390. path = '/',
  391. host = '',
  392. headers = []
  393. ) {
  394. super();
  395. this.acceptProxyProtocol = acceptProxyProtocol;
  396. this.path = path;
  397. this.host = host;
  398. this.headers = headers;
  399. }
  400. addHeader(name, value) {
  401. this.headers.push({ name: name, value: value });
  402. }
  403. removeHeader(index) {
  404. this.headers.splice(index, 1);
  405. }
  406. static fromJson(json = {}) {
  407. return new HTTPUpgradeStreamSettings(
  408. json.acceptProxyProtocol,
  409. json.path,
  410. json.host,
  411. XrayCommonClass.toHeaders(json.headers),
  412. );
  413. }
  414. toJson() {
  415. return {
  416. acceptProxyProtocol: this.acceptProxyProtocol,
  417. path: this.path,
  418. host: this.host,
  419. headers: XrayCommonClass.toV2Headers(this.headers, false),
  420. };
  421. }
  422. }
  423. class xHTTPStreamSettings extends XrayCommonClass {
  424. constructor(
  425. path = '/',
  426. host = '',
  427. headers = [],
  428. scMaxBufferedPosts = 30,
  429. scMaxEachPostBytes = "1000000",
  430. scStreamUpServerSecs = "20-80",
  431. noSSEHeader = false,
  432. xPaddingBytes = "100-1000",
  433. mode = MODE_OPTION.AUTO,
  434. xPaddingObfsMode = false,
  435. xPaddingKey = '',
  436. xPaddingHeader = '',
  437. xPaddingPlacement = '',
  438. xPaddingMethod = '',
  439. uplinkHTTPMethod = '',
  440. sessionPlacement = '',
  441. sessionKey = '',
  442. seqPlacement = '',
  443. seqKey = '',
  444. uplinkDataPlacement = '',
  445. uplinkDataKey = '',
  446. uplinkChunkSize = 0,
  447. ) {
  448. super();
  449. this.path = path;
  450. this.host = host;
  451. this.headers = headers;
  452. this.scMaxBufferedPosts = scMaxBufferedPosts;
  453. this.scMaxEachPostBytes = scMaxEachPostBytes;
  454. this.scStreamUpServerSecs = scStreamUpServerSecs;
  455. this.noSSEHeader = noSSEHeader;
  456. this.xPaddingBytes = xPaddingBytes;
  457. this.mode = mode;
  458. this.xPaddingObfsMode = xPaddingObfsMode;
  459. this.xPaddingKey = xPaddingKey;
  460. this.xPaddingHeader = xPaddingHeader;
  461. this.xPaddingPlacement = xPaddingPlacement;
  462. this.xPaddingMethod = xPaddingMethod;
  463. this.uplinkHTTPMethod = uplinkHTTPMethod;
  464. this.sessionPlacement = sessionPlacement;
  465. this.sessionKey = sessionKey;
  466. this.seqPlacement = seqPlacement;
  467. this.seqKey = seqKey;
  468. this.uplinkDataPlacement = uplinkDataPlacement;
  469. this.uplinkDataKey = uplinkDataKey;
  470. this.uplinkChunkSize = uplinkChunkSize;
  471. }
  472. addHeader(name, value) {
  473. this.headers.push({ name: name, value: value });
  474. }
  475. removeHeader(index) {
  476. this.headers.splice(index, 1);
  477. }
  478. static fromJson(json = {}) {
  479. return new xHTTPStreamSettings(
  480. json.path,
  481. json.host,
  482. XrayCommonClass.toHeaders(json.headers),
  483. json.scMaxBufferedPosts,
  484. json.scMaxEachPostBytes,
  485. json.scStreamUpServerSecs,
  486. json.noSSEHeader,
  487. json.xPaddingBytes,
  488. json.mode,
  489. json.xPaddingObfsMode,
  490. json.xPaddingKey,
  491. json.xPaddingHeader,
  492. json.xPaddingPlacement,
  493. json.xPaddingMethod,
  494. json.uplinkHTTPMethod,
  495. json.sessionPlacement,
  496. json.sessionKey,
  497. json.seqPlacement,
  498. json.seqKey,
  499. json.uplinkDataPlacement,
  500. json.uplinkDataKey,
  501. json.uplinkChunkSize,
  502. );
  503. }
  504. toJson() {
  505. return {
  506. path: this.path,
  507. host: this.host,
  508. headers: XrayCommonClass.toV2Headers(this.headers, false),
  509. scMaxBufferedPosts: this.scMaxBufferedPosts,
  510. scMaxEachPostBytes: this.scMaxEachPostBytes,
  511. scStreamUpServerSecs: this.scStreamUpServerSecs,
  512. noSSEHeader: this.noSSEHeader,
  513. xPaddingBytes: this.xPaddingBytes,
  514. mode: this.mode,
  515. xPaddingObfsMode: this.xPaddingObfsMode,
  516. xPaddingKey: this.xPaddingKey,
  517. xPaddingHeader: this.xPaddingHeader,
  518. xPaddingPlacement: this.xPaddingPlacement,
  519. xPaddingMethod: this.xPaddingMethod,
  520. uplinkHTTPMethod: this.uplinkHTTPMethod,
  521. sessionPlacement: this.sessionPlacement,
  522. sessionKey: this.sessionKey,
  523. seqPlacement: this.seqPlacement,
  524. seqKey: this.seqKey,
  525. uplinkDataPlacement: this.uplinkDataPlacement,
  526. uplinkDataKey: this.uplinkDataKey,
  527. uplinkChunkSize: this.uplinkChunkSize,
  528. };
  529. }
  530. }
  531. class HysteriaStreamSettings extends XrayCommonClass {
  532. constructor(
  533. protocol,
  534. version = 2,
  535. auth = '',
  536. udpIdleTimeout = 60,
  537. masquerade,
  538. ) {
  539. super(protocol);
  540. this.version = version;
  541. this.auth = auth;
  542. this.udpIdleTimeout = udpIdleTimeout;
  543. this.masquerade = masquerade;
  544. }
  545. static fromJson(json = {}) {
  546. return new HysteriaStreamSettings(
  547. json.protocol,
  548. json.version ?? 2,
  549. json.auth ?? '',
  550. json.udpIdleTimeout ?? 60,
  551. json.masquerade ? HysteriaMasquerade.fromJson(json.masquerade) : undefined,
  552. );
  553. }
  554. toJson() {
  555. return {
  556. protocol: this.protocol,
  557. version: this.version,
  558. auth: this.auth,
  559. udpIdleTimeout: this.udpIdleTimeout,
  560. masquerade: this.masqueradeSwitch ? this.masquerade.toJson() : undefined,
  561. };
  562. }
  563. get masqueradeSwitch() {
  564. return this.masquerade != undefined;
  565. }
  566. set masqueradeSwitch(value) {
  567. this.masquerade = value ? new HysteriaMasquerade() : undefined;
  568. }
  569. };
  570. class HysteriaMasquerade extends XrayCommonClass {
  571. constructor(
  572. type = 'proxy',
  573. dir = '',
  574. url = '',
  575. rewriteHost = false,
  576. insecure = false,
  577. content = '',
  578. headers = [],
  579. statusCode = 0,
  580. ) {
  581. super();
  582. this.type = type;
  583. this.dir = dir;
  584. this.url = url;
  585. this.rewriteHost = rewriteHost;
  586. this.insecure = insecure;
  587. this.content = content;
  588. this.headers = headers;
  589. this.statusCode = statusCode;
  590. }
  591. addHeader(name, value) {
  592. this.headers.push({ name: name, value: value });
  593. }
  594. removeHeader(index) {
  595. this.headers.splice(index, 1);
  596. }
  597. static fromJson(json = {}) {
  598. return new HysteriaMasquerade(
  599. json.type,
  600. json.dir,
  601. json.url,
  602. json.rewriteHost,
  603. json.insecure,
  604. json.content,
  605. XrayCommonClass.toHeaders(json.headers),
  606. json.statusCode,
  607. );
  608. }
  609. toJson() {
  610. return {
  611. type: this.type,
  612. dir: this.dir,
  613. url: this.url,
  614. rewriteHost: this.rewriteHost,
  615. insecure: this.insecure,
  616. content: this.content,
  617. headers: XrayCommonClass.toV2Headers(this.headers, false),
  618. statusCode: this.statusCode,
  619. };
  620. }
  621. };
  622. class TlsStreamSettings extends XrayCommonClass {
  623. constructor(
  624. serverName = '',
  625. minVersion = TLS_VERSION_OPTION.TLS12,
  626. maxVersion = TLS_VERSION_OPTION.TLS13,
  627. cipherSuites = '',
  628. rejectUnknownSni = false,
  629. disableSystemRoot = false,
  630. enableSessionResumption = false,
  631. certificates = [new TlsStreamSettings.Cert()],
  632. alpn = [ALPN_OPTION.H2, ALPN_OPTION.HTTP1],
  633. echServerKeys = '',
  634. settings = new TlsStreamSettings.Settings()
  635. ) {
  636. super();
  637. this.sni = serverName;
  638. this.minVersion = minVersion;
  639. this.maxVersion = maxVersion;
  640. this.cipherSuites = cipherSuites;
  641. this.rejectUnknownSni = rejectUnknownSni;
  642. this.disableSystemRoot = disableSystemRoot;
  643. this.enableSessionResumption = enableSessionResumption;
  644. this.certs = certificates;
  645. this.alpn = alpn;
  646. this.echServerKeys = echServerKeys;
  647. this.settings = settings;
  648. }
  649. addCert() {
  650. this.certs.push(new TlsStreamSettings.Cert());
  651. }
  652. removeCert(index) {
  653. this.certs.splice(index, 1);
  654. }
  655. static fromJson(json = {}) {
  656. let certs;
  657. let settings;
  658. if (!ObjectUtil.isEmpty(json.certificates)) {
  659. certs = json.certificates.map(cert => TlsStreamSettings.Cert.fromJson(cert));
  660. }
  661. if (!ObjectUtil.isEmpty(json.settings)) {
  662. settings = new TlsStreamSettings.Settings(json.settings.fingerprint, json.settings.echConfigList);
  663. }
  664. return new TlsStreamSettings(
  665. json.serverName,
  666. json.minVersion,
  667. json.maxVersion,
  668. json.cipherSuites,
  669. json.rejectUnknownSni,
  670. json.disableSystemRoot,
  671. json.enableSessionResumption,
  672. certs,
  673. json.alpn,
  674. json.echServerKeys,
  675. settings,
  676. );
  677. }
  678. toJson() {
  679. return {
  680. serverName: this.sni,
  681. minVersion: this.minVersion,
  682. maxVersion: this.maxVersion,
  683. cipherSuites: this.cipherSuites,
  684. rejectUnknownSni: this.rejectUnknownSni,
  685. disableSystemRoot: this.disableSystemRoot,
  686. enableSessionResumption: this.enableSessionResumption,
  687. certificates: TlsStreamSettings.toJsonArray(this.certs),
  688. alpn: this.alpn,
  689. echServerKeys: this.echServerKeys,
  690. settings: this.settings,
  691. };
  692. }
  693. }
  694. TlsStreamSettings.Cert = class extends XrayCommonClass {
  695. constructor(
  696. useFile = true,
  697. certificateFile = '',
  698. keyFile = '',
  699. certificate = '',
  700. key = '',
  701. oneTimeLoading = false,
  702. usage = USAGE_OPTION.ENCIPHERMENT,
  703. buildChain = false,
  704. ) {
  705. super();
  706. this.useFile = useFile;
  707. this.certFile = certificateFile;
  708. this.keyFile = keyFile;
  709. this.cert = Array.isArray(certificate) ? certificate.join('\n') : certificate;
  710. this.key = Array.isArray(key) ? key.join('\n') : key;
  711. this.oneTimeLoading = oneTimeLoading;
  712. this.usage = usage;
  713. this.buildChain = buildChain
  714. }
  715. static fromJson(json = {}) {
  716. if ('certificateFile' in json && 'keyFile' in json) {
  717. return new TlsStreamSettings.Cert(
  718. true,
  719. json.certificateFile,
  720. json.keyFile, '', '',
  721. json.oneTimeLoading,
  722. json.usage,
  723. json.buildChain,
  724. );
  725. } else {
  726. return new TlsStreamSettings.Cert(
  727. false, '', '',
  728. json.certificate.join('\n'),
  729. json.key.join('\n'),
  730. json.oneTimeLoading,
  731. json.usage,
  732. json.buildChain,
  733. );
  734. }
  735. }
  736. toJson() {
  737. if (this.useFile) {
  738. return {
  739. certificateFile: this.certFile,
  740. keyFile: this.keyFile,
  741. oneTimeLoading: this.oneTimeLoading,
  742. usage: this.usage,
  743. buildChain: this.buildChain,
  744. };
  745. } else {
  746. return {
  747. certificate: this.cert.split('\n'),
  748. key: this.key.split('\n'),
  749. oneTimeLoading: this.oneTimeLoading,
  750. usage: this.usage,
  751. buildChain: this.buildChain,
  752. };
  753. }
  754. }
  755. };
  756. TlsStreamSettings.Settings = class extends XrayCommonClass {
  757. constructor(
  758. fingerprint = UTLS_FINGERPRINT.UTLS_CHROME,
  759. echConfigList = '',
  760. ) {
  761. super();
  762. this.fingerprint = fingerprint;
  763. this.echConfigList = echConfigList;
  764. }
  765. static fromJson(json = {}) {
  766. return new TlsStreamSettings.Settings(
  767. json.fingerprint,
  768. json.echConfigList,
  769. );
  770. }
  771. toJson() {
  772. return {
  773. fingerprint: this.fingerprint,
  774. echConfigList: this.echConfigList
  775. };
  776. }
  777. };
  778. class RealityStreamSettings extends XrayCommonClass {
  779. constructor(
  780. show = false,
  781. xver = 0,
  782. target = '',
  783. serverNames = '',
  784. privateKey = '',
  785. minClientVer = '',
  786. maxClientVer = '',
  787. maxTimediff = 0,
  788. shortIds = RandomUtil.randomShortIds(),
  789. mldsa65Seed = '',
  790. settings = new RealityStreamSettings.Settings()
  791. ) {
  792. super();
  793. // If target/serverNames are not provided, use random values
  794. if (!target && !serverNames) {
  795. const randomTarget = typeof getRandomRealityTarget !== 'undefined'
  796. ? getRandomRealityTarget()
  797. : { target: 'www.apple.com:443', sni: 'www.apple.com,apple.com' };
  798. target = randomTarget.target;
  799. serverNames = randomTarget.sni;
  800. }
  801. this.show = show;
  802. this.xver = xver;
  803. this.target = target;
  804. this.serverNames = Array.isArray(serverNames) ? serverNames.join(",") : serverNames;
  805. this.privateKey = privateKey;
  806. this.minClientVer = minClientVer;
  807. this.maxClientVer = maxClientVer;
  808. this.maxTimediff = maxTimediff;
  809. this.shortIds = Array.isArray(shortIds) ? shortIds.join(",") : shortIds;
  810. this.mldsa65Seed = mldsa65Seed;
  811. this.settings = settings;
  812. }
  813. static fromJson(json = {}) {
  814. let settings;
  815. if (!ObjectUtil.isEmpty(json.settings)) {
  816. settings = new RealityStreamSettings.Settings(
  817. json.settings.publicKey,
  818. json.settings.fingerprint,
  819. json.settings.serverName,
  820. json.settings.spiderX,
  821. json.settings.mldsa65Verify,
  822. );
  823. }
  824. return new RealityStreamSettings(
  825. json.show,
  826. json.xver,
  827. json.target,
  828. json.serverNames,
  829. json.privateKey,
  830. json.minClientVer,
  831. json.maxClientVer,
  832. json.maxTimediff,
  833. json.shortIds,
  834. json.mldsa65Seed,
  835. settings,
  836. );
  837. }
  838. toJson() {
  839. return {
  840. show: this.show,
  841. xver: this.xver,
  842. target: this.target,
  843. serverNames: this.serverNames.split(","),
  844. privateKey: this.privateKey,
  845. minClientVer: this.minClientVer,
  846. maxClientVer: this.maxClientVer,
  847. maxTimediff: this.maxTimediff,
  848. shortIds: this.shortIds.split(","),
  849. mldsa65Seed: this.mldsa65Seed,
  850. settings: this.settings,
  851. };
  852. }
  853. }
  854. RealityStreamSettings.Settings = class extends XrayCommonClass {
  855. constructor(
  856. publicKey = '',
  857. fingerprint = UTLS_FINGERPRINT.UTLS_CHROME,
  858. serverName = '',
  859. spiderX = '/',
  860. mldsa65Verify = ''
  861. ) {
  862. super();
  863. this.publicKey = publicKey;
  864. this.fingerprint = fingerprint;
  865. this.serverName = serverName;
  866. this.spiderX = spiderX;
  867. this.mldsa65Verify = mldsa65Verify;
  868. }
  869. static fromJson(json = {}) {
  870. return new RealityStreamSettings.Settings(
  871. json.publicKey,
  872. json.fingerprint,
  873. json.serverName,
  874. json.spiderX,
  875. json.mldsa65Verify
  876. );
  877. }
  878. toJson() {
  879. return {
  880. publicKey: this.publicKey,
  881. fingerprint: this.fingerprint,
  882. serverName: this.serverName,
  883. spiderX: this.spiderX,
  884. mldsa65Verify: this.mldsa65Verify
  885. };
  886. }
  887. };
  888. class SockoptStreamSettings extends XrayCommonClass {
  889. constructor(
  890. acceptProxyProtocol = false,
  891. tcpFastOpen = false,
  892. mark = 0,
  893. tproxy = "off",
  894. tcpMptcp = false,
  895. penetrate = false,
  896. domainStrategy = DOMAIN_STRATEGY_OPTION.USE_IP,
  897. tcpMaxSeg = 1440,
  898. dialerProxy = "",
  899. tcpKeepAliveInterval = 0,
  900. tcpKeepAliveIdle = 300,
  901. tcpUserTimeout = 10000,
  902. tcpcongestion = TCP_CONGESTION_OPTION.BBR,
  903. V6Only = false,
  904. tcpWindowClamp = 600,
  905. interfaceName = "",
  906. trustedXForwardedFor = [],
  907. ) {
  908. super();
  909. this.acceptProxyProtocol = acceptProxyProtocol;
  910. this.tcpFastOpen = tcpFastOpen;
  911. this.mark = mark;
  912. this.tproxy = tproxy;
  913. this.tcpMptcp = tcpMptcp;
  914. this.penetrate = penetrate;
  915. this.domainStrategy = domainStrategy;
  916. this.tcpMaxSeg = tcpMaxSeg;
  917. this.dialerProxy = dialerProxy;
  918. this.tcpKeepAliveInterval = tcpKeepAliveInterval;
  919. this.tcpKeepAliveIdle = tcpKeepAliveIdle;
  920. this.tcpUserTimeout = tcpUserTimeout;
  921. this.tcpcongestion = tcpcongestion;
  922. this.V6Only = V6Only;
  923. this.tcpWindowClamp = tcpWindowClamp;
  924. this.interfaceName = interfaceName;
  925. this.trustedXForwardedFor = trustedXForwardedFor;
  926. }
  927. static fromJson(json = {}) {
  928. if (Object.keys(json).length === 0) return undefined;
  929. return new SockoptStreamSettings(
  930. json.acceptProxyProtocol,
  931. json.tcpFastOpen,
  932. json.mark,
  933. json.tproxy,
  934. json.tcpMptcp,
  935. json.penetrate,
  936. json.domainStrategy,
  937. json.tcpMaxSeg,
  938. json.dialerProxy,
  939. json.tcpKeepAliveInterval,
  940. json.tcpKeepAliveIdle,
  941. json.tcpUserTimeout,
  942. json.tcpcongestion,
  943. json.V6Only,
  944. json.tcpWindowClamp,
  945. json.interface,
  946. json.trustedXForwardedFor || [],
  947. );
  948. }
  949. toJson() {
  950. const result = {
  951. acceptProxyProtocol: this.acceptProxyProtocol,
  952. tcpFastOpen: this.tcpFastOpen,
  953. mark: this.mark,
  954. tproxy: this.tproxy,
  955. tcpMptcp: this.tcpMptcp,
  956. penetrate: this.penetrate,
  957. domainStrategy: this.domainStrategy,
  958. tcpMaxSeg: this.tcpMaxSeg,
  959. dialerProxy: this.dialerProxy,
  960. tcpKeepAliveInterval: this.tcpKeepAliveInterval,
  961. tcpKeepAliveIdle: this.tcpKeepAliveIdle,
  962. tcpUserTimeout: this.tcpUserTimeout,
  963. tcpcongestion: this.tcpcongestion,
  964. V6Only: this.V6Only,
  965. tcpWindowClamp: this.tcpWindowClamp,
  966. interface: this.interfaceName,
  967. };
  968. if (this.trustedXForwardedFor && this.trustedXForwardedFor.length > 0) {
  969. result.trustedXForwardedFor = this.trustedXForwardedFor;
  970. }
  971. return result;
  972. }
  973. }
  974. class UdpMask extends XrayCommonClass {
  975. constructor(type = 'salamander', settings = {}) {
  976. super();
  977. this.type = type;
  978. this.settings = this._getDefaultSettings(type, settings);
  979. }
  980. _getDefaultSettings(type, settings = {}) {
  981. switch (type) {
  982. case 'salamander':
  983. case 'mkcp-aes128gcm':
  984. return { password: settings.password || '' };
  985. case 'header-dns':
  986. return { domain: settings.domain || '' };
  987. case 'xdns':
  988. return { domains: Array.isArray(settings.domains) ? settings.domains : [] };
  989. case 'xicmp':
  990. return { ip: settings.ip || '', id: settings.id ?? 0 };
  991. case 'mkcp-original':
  992. case 'header-dtls':
  993. case 'header-srtp':
  994. case 'header-utp':
  995. case 'header-wechat':
  996. case 'header-wireguard':
  997. return {};
  998. case 'header-custom':
  999. return {
  1000. client: Array.isArray(settings.client) ? settings.client : [],
  1001. server: Array.isArray(settings.server) ? settings.server : [],
  1002. };
  1003. case 'noise':
  1004. return {
  1005. reset: settings.reset ?? 0,
  1006. noise: Array.isArray(settings.noise) ? settings.noise : [],
  1007. };
  1008. default:
  1009. return settings;
  1010. }
  1011. }
  1012. static fromJson(json = {}) {
  1013. return new UdpMask(
  1014. json.type || 'salamander',
  1015. json.settings || {}
  1016. );
  1017. }
  1018. toJson() {
  1019. const cleanItem = item => {
  1020. const out = { ...item };
  1021. if (out.type === 'array') {
  1022. delete out.packet;
  1023. } else {
  1024. delete out.rand;
  1025. delete out.randRange;
  1026. }
  1027. return out;
  1028. };
  1029. let settings = this.settings;
  1030. if (this.type === 'noise' && settings && Array.isArray(settings.noise)) {
  1031. settings = { ...settings, noise: settings.noise.map(cleanItem) };
  1032. } else if (this.type === 'header-custom' && settings) {
  1033. settings = {
  1034. ...settings,
  1035. client: Array.isArray(settings.client) ? settings.client.map(cleanItem) : settings.client,
  1036. server: Array.isArray(settings.server) ? settings.server.map(cleanItem) : settings.server,
  1037. };
  1038. }
  1039. return {
  1040. type: this.type,
  1041. settings: (settings && Object.keys(settings).length > 0) ? settings : undefined
  1042. };
  1043. }
  1044. }
  1045. class TcpMask extends XrayCommonClass {
  1046. constructor(type = 'fragment', settings = {}) {
  1047. super();
  1048. this.type = type;
  1049. this.settings = this._getDefaultSettings(type, settings);
  1050. }
  1051. _getDefaultSettings(type, settings = {}) {
  1052. switch (type) {
  1053. case 'fragment':
  1054. return {
  1055. packets: settings.packets ?? 'tlshello',
  1056. length: settings.length ?? '',
  1057. delay: settings.delay ?? '',
  1058. maxSplit: settings.maxSplit ?? '',
  1059. };
  1060. case 'sudoku':
  1061. return {
  1062. password: settings.password ?? '',
  1063. ascii: settings.ascii ?? '',
  1064. customTable: settings.customTable ?? '',
  1065. customTables: Array.isArray(settings.customTables) ? settings.customTables : [],
  1066. paddingMin: settings.paddingMin ?? 0,
  1067. paddingMax: settings.paddingMax ?? 0,
  1068. };
  1069. case 'header-custom':
  1070. return {
  1071. clients: Array.isArray(settings.clients) ? settings.clients : [],
  1072. servers: Array.isArray(settings.servers) ? settings.servers : [],
  1073. };
  1074. default:
  1075. return settings;
  1076. }
  1077. }
  1078. static fromJson(json = {}) {
  1079. return new TcpMask(
  1080. json.type || 'fragment',
  1081. json.settings || {}
  1082. );
  1083. }
  1084. toJson() {
  1085. const cleanItem = item => {
  1086. const out = { ...item };
  1087. if (out.type === 'array') {
  1088. delete out.packet;
  1089. } else {
  1090. delete out.rand;
  1091. delete out.randRange;
  1092. }
  1093. return out;
  1094. };
  1095. let settings = this.settings;
  1096. if (this.type === 'header-custom' && settings) {
  1097. const cleanGroup = group => Array.isArray(group) ? group.map(cleanItem) : group;
  1098. settings = {
  1099. ...settings,
  1100. clients: Array.isArray(settings.clients) ? settings.clients.map(cleanGroup) : settings.clients,
  1101. servers: Array.isArray(settings.servers) ? settings.servers.map(cleanGroup) : settings.servers,
  1102. };
  1103. }
  1104. return {
  1105. type: this.type,
  1106. settings: (settings && Object.keys(settings).length > 0) ? settings : undefined
  1107. };
  1108. }
  1109. }
  1110. class QuicParams extends XrayCommonClass {
  1111. constructor(
  1112. congestion = 'bbr',
  1113. debug = false,
  1114. brutalUp = '',
  1115. brutalDown = '',
  1116. udpHop = undefined,
  1117. initStreamReceiveWindow = 8388608,
  1118. maxStreamReceiveWindow = 8388608,
  1119. initConnectionReceiveWindow = 20971520,
  1120. maxConnectionReceiveWindow = 20971520,
  1121. maxIdleTimeout = 30,
  1122. keepAlivePeriod = 0,
  1123. disablePathMTUDiscovery = false,
  1124. maxIncomingStreams = 1024,
  1125. ) {
  1126. super();
  1127. this.congestion = congestion;
  1128. this.debug = debug;
  1129. this.brutalUp = brutalUp;
  1130. this.brutalDown = brutalDown;
  1131. this.udpHop = udpHop;
  1132. this.initStreamReceiveWindow = initStreamReceiveWindow;
  1133. this.maxStreamReceiveWindow = maxStreamReceiveWindow;
  1134. this.initConnectionReceiveWindow = initConnectionReceiveWindow;
  1135. this.maxConnectionReceiveWindow = maxConnectionReceiveWindow;
  1136. this.maxIdleTimeout = maxIdleTimeout;
  1137. this.keepAlivePeriod = keepAlivePeriod;
  1138. this.disablePathMTUDiscovery = disablePathMTUDiscovery;
  1139. this.maxIncomingStreams = maxIncomingStreams;
  1140. }
  1141. get hasUdpHop() {
  1142. return this.udpHop != null;
  1143. }
  1144. set hasUdpHop(value) {
  1145. this.udpHop = value ? (this.udpHop || { ports: '20000-50000', interval: '5-10' }) : undefined;
  1146. }
  1147. static fromJson(json = {}) {
  1148. if (!json || Object.keys(json).length === 0) return undefined;
  1149. return new QuicParams(
  1150. json.congestion,
  1151. json.debug,
  1152. json.brutalUp,
  1153. json.brutalDown,
  1154. json.udpHop ? { ports: json.udpHop.ports, interval: json.udpHop.interval } : undefined,
  1155. json.initStreamReceiveWindow,
  1156. json.maxStreamReceiveWindow,
  1157. json.initConnectionReceiveWindow,
  1158. json.maxConnectionReceiveWindow,
  1159. json.maxIdleTimeout,
  1160. json.keepAlivePeriod,
  1161. json.disablePathMTUDiscovery,
  1162. json.maxIncomingStreams,
  1163. );
  1164. }
  1165. toJson() {
  1166. const result = { congestion: this.congestion };
  1167. if (this.debug) result.debug = this.debug;
  1168. if (this.brutalUp) result.brutalUp = this.brutalUp;
  1169. if (this.brutalDown) result.brutalDown = this.brutalDown;
  1170. if (this.udpHop) result.udpHop = { ports: this.udpHop.ports, interval: this.udpHop.interval };
  1171. if (this.initStreamReceiveWindow > 0) result.initStreamReceiveWindow = this.initStreamReceiveWindow;
  1172. if (this.maxStreamReceiveWindow > 0) result.maxStreamReceiveWindow = this.maxStreamReceiveWindow;
  1173. if (this.initConnectionReceiveWindow > 0) result.initConnectionReceiveWindow = this.initConnectionReceiveWindow;
  1174. if (this.maxConnectionReceiveWindow > 0) result.maxConnectionReceiveWindow = this.maxConnectionReceiveWindow;
  1175. if (this.maxIdleTimeout !== 30 && this.maxIdleTimeout > 0) result.maxIdleTimeout = this.maxIdleTimeout;
  1176. if (this.keepAlivePeriod > 0) result.keepAlivePeriod = this.keepAlivePeriod;
  1177. if (this.disablePathMTUDiscovery) result.disablePathMTUDiscovery = this.disablePathMTUDiscovery;
  1178. if (this.maxIncomingStreams > 0) result.maxIncomingStreams = this.maxIncomingStreams;
  1179. return result;
  1180. }
  1181. }
  1182. class FinalMaskStreamSettings extends XrayCommonClass {
  1183. constructor(tcp = [], udp = [], quicParams = undefined) {
  1184. super();
  1185. this.tcp = Array.isArray(tcp) ? tcp.map(t => t instanceof TcpMask ? t : new TcpMask(t.type, t.settings)) : [];
  1186. this.udp = Array.isArray(udp) ? udp.map(u => new UdpMask(u.type, u.settings)) : [new UdpMask(udp.type, udp.settings)];
  1187. this.quicParams = quicParams instanceof QuicParams ? quicParams : (quicParams ? QuicParams.fromJson(quicParams) : undefined);
  1188. }
  1189. get enableQuicParams() {
  1190. return this.quicParams != null;
  1191. }
  1192. set enableQuicParams(value) {
  1193. this.quicParams = value ? (this.quicParams || new QuicParams()) : undefined;
  1194. }
  1195. static fromJson(json = {}) {
  1196. return new FinalMaskStreamSettings(
  1197. json.tcp || [],
  1198. json.udp || [],
  1199. json.quicParams ? QuicParams.fromJson(json.quicParams) : undefined,
  1200. );
  1201. }
  1202. toJson() {
  1203. const result = {};
  1204. if (this.tcp && this.tcp.length > 0) {
  1205. result.tcp = this.tcp.map(t => t.toJson());
  1206. }
  1207. if (this.udp && this.udp.length > 0) {
  1208. result.udp = this.udp.map(udp => udp.toJson());
  1209. }
  1210. if (this.quicParams) {
  1211. result.quicParams = this.quicParams.toJson();
  1212. }
  1213. return result;
  1214. }
  1215. }
  1216. class StreamSettings extends XrayCommonClass {
  1217. constructor(network = 'tcp',
  1218. security = 'none',
  1219. externalProxy = [],
  1220. tlsSettings = new TlsStreamSettings(),
  1221. realitySettings = new RealityStreamSettings(),
  1222. tcpSettings = new TcpStreamSettings(),
  1223. kcpSettings = new KcpStreamSettings(),
  1224. wsSettings = new WsStreamSettings(),
  1225. grpcSettings = new GrpcStreamSettings(),
  1226. httpupgradeSettings = new HTTPUpgradeStreamSettings(),
  1227. xhttpSettings = new xHTTPStreamSettings(),
  1228. hysteriaSettings = new HysteriaStreamSettings(),
  1229. finalmask = new FinalMaskStreamSettings(),
  1230. sockopt = undefined,
  1231. ) {
  1232. super();
  1233. this.network = network;
  1234. this.security = security;
  1235. this.externalProxy = externalProxy;
  1236. this.tls = tlsSettings;
  1237. this.reality = realitySettings;
  1238. this.tcp = tcpSettings;
  1239. this.kcp = kcpSettings;
  1240. this.ws = wsSettings;
  1241. this.grpc = grpcSettings;
  1242. this.httpupgrade = httpupgradeSettings;
  1243. this.xhttp = xhttpSettings;
  1244. this.hysteria = hysteriaSettings;
  1245. this.finalmask = finalmask;
  1246. this.sockopt = sockopt;
  1247. }
  1248. addTcpMask(type = 'fragment') {
  1249. this.finalmask.tcp.push(new TcpMask(type));
  1250. }
  1251. delTcpMask(index) {
  1252. if (this.finalmask.tcp) {
  1253. this.finalmask.tcp.splice(index, 1);
  1254. }
  1255. }
  1256. addUdpMask(type = 'salamander') {
  1257. this.finalmask.udp.push(new UdpMask(type));
  1258. }
  1259. delUdpMask(index) {
  1260. if (this.finalmask.udp) {
  1261. this.finalmask.udp.splice(index, 1);
  1262. }
  1263. }
  1264. get hasFinalMask() {
  1265. const hasTcp = this.finalmask.tcp && this.finalmask.tcp.length > 0;
  1266. const hasUdp = this.finalmask.udp && this.finalmask.udp.length > 0;
  1267. const hasQuicParams = this.finalmask.quicParams != null;
  1268. return hasTcp || hasUdp || hasQuicParams;
  1269. }
  1270. get isTls() {
  1271. return this.security === "tls";
  1272. }
  1273. set isTls(isTls) {
  1274. if (isTls) {
  1275. this.security = 'tls';
  1276. } else {
  1277. this.security = 'none';
  1278. }
  1279. }
  1280. //for Reality
  1281. get isReality() {
  1282. return this.security === "reality";
  1283. }
  1284. set isReality(isReality) {
  1285. if (isReality) {
  1286. this.security = 'reality';
  1287. } else {
  1288. this.security = 'none';
  1289. }
  1290. }
  1291. get sockoptSwitch() {
  1292. return this.sockopt != undefined;
  1293. }
  1294. set sockoptSwitch(value) {
  1295. this.sockopt = value ? new SockoptStreamSettings() : undefined;
  1296. }
  1297. static fromJson(json = {}) {
  1298. return new StreamSettings(
  1299. json.network,
  1300. json.security,
  1301. json.externalProxy,
  1302. TlsStreamSettings.fromJson(json.tlsSettings),
  1303. RealityStreamSettings.fromJson(json.realitySettings),
  1304. TcpStreamSettings.fromJson(json.tcpSettings),
  1305. KcpStreamSettings.fromJson(json.kcpSettings),
  1306. WsStreamSettings.fromJson(json.wsSettings),
  1307. GrpcStreamSettings.fromJson(json.grpcSettings),
  1308. HTTPUpgradeStreamSettings.fromJson(json.httpupgradeSettings),
  1309. xHTTPStreamSettings.fromJson(json.xhttpSettings),
  1310. HysteriaStreamSettings.fromJson(json.hysteriaSettings),
  1311. FinalMaskStreamSettings.fromJson(json.finalmask),
  1312. SockoptStreamSettings.fromJson(json.sockopt),
  1313. );
  1314. }
  1315. toJson() {
  1316. const network = this.network;
  1317. return {
  1318. network: network,
  1319. security: this.security,
  1320. externalProxy: this.externalProxy,
  1321. tlsSettings: this.isTls ? this.tls.toJson() : undefined,
  1322. realitySettings: this.isReality ? this.reality.toJson() : undefined,
  1323. tcpSettings: network === 'tcp' ? this.tcp.toJson() : undefined,
  1324. kcpSettings: network === 'kcp' ? this.kcp.toJson() : undefined,
  1325. wsSettings: network === 'ws' ? this.ws.toJson() : undefined,
  1326. grpcSettings: network === 'grpc' ? this.grpc.toJson() : undefined,
  1327. httpupgradeSettings: network === 'httpupgrade' ? this.httpupgrade.toJson() : undefined,
  1328. xhttpSettings: network === 'xhttp' ? this.xhttp.toJson() : undefined,
  1329. hysteriaSettings: network === 'hysteria' ? this.hysteria.toJson() : undefined,
  1330. finalmask: this.hasFinalMask ? this.finalmask.toJson() : undefined,
  1331. sockopt: this.sockopt != undefined ? this.sockopt.toJson() : undefined,
  1332. };
  1333. }
  1334. }
  1335. class Sniffing extends XrayCommonClass {
  1336. constructor(
  1337. enabled = false,
  1338. destOverride = ['http', 'tls', 'quic', 'fakedns'],
  1339. metadataOnly = false,
  1340. routeOnly = false,
  1341. ipsExcluded = [],
  1342. domainsExcluded = []) {
  1343. super();
  1344. this.enabled = enabled;
  1345. this.destOverride = Array.isArray(destOverride) && destOverride.length > 0 ? destOverride : ['http', 'tls', 'quic', 'fakedns'];
  1346. this.metadataOnly = metadataOnly;
  1347. this.routeOnly = routeOnly;
  1348. this.ipsExcluded = Array.isArray(ipsExcluded) ? ipsExcluded : [];
  1349. this.domainsExcluded = Array.isArray(domainsExcluded) ? domainsExcluded : [];
  1350. }
  1351. static fromJson(json = {}) {
  1352. let destOverride = ObjectUtil.clone(json.destOverride);
  1353. if (ObjectUtil.isEmpty(destOverride) || ObjectUtil.isArrEmpty(destOverride) || ObjectUtil.isEmpty(destOverride[0])) {
  1354. destOverride = ['http', 'tls', 'quic', 'fakedns'];
  1355. }
  1356. return new Sniffing(
  1357. !!json.enabled,
  1358. destOverride,
  1359. json.metadataOnly,
  1360. json.routeOnly,
  1361. json.ipsExcluded || [],
  1362. json.domainsExcluded || [],
  1363. );
  1364. }
  1365. toJson() {
  1366. return {
  1367. enabled: this.enabled,
  1368. destOverride: this.destOverride,
  1369. metadataOnly: this.metadataOnly,
  1370. routeOnly: this.routeOnly,
  1371. ipsExcluded: this.ipsExcluded.length > 0 ? this.ipsExcluded : undefined,
  1372. domainsExcluded: this.domainsExcluded.length > 0 ? this.domainsExcluded : undefined,
  1373. };
  1374. }
  1375. }
  1376. class Inbound extends XrayCommonClass {
  1377. constructor(
  1378. port = RandomUtil.randomInteger(10000, 60000),
  1379. listen = '',
  1380. protocol = Protocols.VLESS,
  1381. settings = null,
  1382. streamSettings = new StreamSettings(),
  1383. tag = '',
  1384. sniffing = new Sniffing(),
  1385. clientStats = '',
  1386. ) {
  1387. super();
  1388. this.port = port;
  1389. this.listen = listen;
  1390. this._protocol = protocol;
  1391. this.settings = ObjectUtil.isEmpty(settings) ? Inbound.Settings.getSettings(protocol) : settings;
  1392. this.stream = streamSettings;
  1393. this.tag = tag;
  1394. this.sniffing = sniffing;
  1395. this.clientStats = clientStats;
  1396. }
  1397. getClientStats() {
  1398. return this.clientStats;
  1399. }
  1400. // Copy the xPadding* settings into the query-string of a vless/trojan/ss
  1401. // link. Without this, the admin's custom xPaddingBytes range and (in
  1402. // obfs mode) the custom xPaddingKey / xPaddingHeader / placement /
  1403. // method never reach the client — the client keeps xray / sing-box's
  1404. // internal defaults and the server rejects every handshake with
  1405. // `invalid padding (...) length: 0`.
  1406. //
  1407. // Two encodings are emitted so each client family can pick at least
  1408. // one up:
  1409. // - x_padding_bytes=<range> flat, for sing-box-family clients
  1410. // - extra=<url-encoded-json> full blob, for xray-core clients
  1411. //
  1412. // Fields are only included when they actually have a value, so a
  1413. // default inbound yields the same URL it did before this helper.
  1414. static applyXhttpPaddingToParams(xhttp, params) {
  1415. if (!xhttp) return;
  1416. if (typeof xhttp.xPaddingBytes === 'string' && xhttp.xPaddingBytes.length > 0) {
  1417. params.set("x_padding_bytes", xhttp.xPaddingBytes);
  1418. }
  1419. const extra = {};
  1420. if (typeof xhttp.xPaddingBytes === 'string' && xhttp.xPaddingBytes.length > 0) {
  1421. extra.xPaddingBytes = xhttp.xPaddingBytes;
  1422. }
  1423. if (xhttp.xPaddingObfsMode === true) {
  1424. extra.xPaddingObfsMode = true;
  1425. ["xPaddingKey", "xPaddingHeader", "xPaddingPlacement", "xPaddingMethod"].forEach(k => {
  1426. if (typeof xhttp[k] === 'string' && xhttp[k].length > 0) {
  1427. extra[k] = xhttp[k];
  1428. }
  1429. });
  1430. }
  1431. if (Object.keys(extra).length > 0) {
  1432. params.set("extra", JSON.stringify(extra));
  1433. }
  1434. }
  1435. // VMess variant: VMess links are a base64-encoded JSON object, so we
  1436. // copy the padding fields directly into the JSON instead of building
  1437. // a query string.
  1438. static applyXhttpPaddingToObj(xhttp, obj) {
  1439. if (!xhttp || !obj) return;
  1440. if (typeof xhttp.xPaddingBytes === 'string' && xhttp.xPaddingBytes.length > 0) {
  1441. obj.x_padding_bytes = xhttp.xPaddingBytes;
  1442. }
  1443. if (xhttp.xPaddingObfsMode === true) {
  1444. obj.xPaddingObfsMode = true;
  1445. ["xPaddingKey", "xPaddingHeader", "xPaddingPlacement", "xPaddingMethod"].forEach(k => {
  1446. if (typeof xhttp[k] === 'string' && xhttp[k].length > 0) {
  1447. obj[k] = xhttp[k];
  1448. }
  1449. });
  1450. }
  1451. }
  1452. static hasShareableFinalMaskValue(value) {
  1453. if (value == null) {
  1454. return false;
  1455. }
  1456. if (Array.isArray(value)) {
  1457. return value.some(item => Inbound.hasShareableFinalMaskValue(item));
  1458. }
  1459. if (typeof value === 'object') {
  1460. return Object.values(value).some(item => Inbound.hasShareableFinalMaskValue(item));
  1461. }
  1462. if (typeof value === 'string') {
  1463. return value.length > 0;
  1464. }
  1465. return true;
  1466. }
  1467. static serializeFinalMask(finalmask) {
  1468. if (!finalmask) {
  1469. return '';
  1470. }
  1471. const value = typeof finalmask.toJson === 'function' ? finalmask.toJson() : finalmask;
  1472. return Inbound.hasShareableFinalMaskValue(value) ? JSON.stringify(value) : '';
  1473. }
  1474. // Export finalmask with the same compact JSON payload shape that
  1475. // v2rayN-compatible share links use: fm=<json>.
  1476. static applyFinalMaskToParams(finalmask, params) {
  1477. if (!params) return;
  1478. const payload = Inbound.serializeFinalMask(finalmask);
  1479. if (payload.length > 0) {
  1480. params.set("fm", payload);
  1481. }
  1482. }
  1483. // VMess links are a base64 JSON object, so keep the same fm payload
  1484. // under a flat property instead of a URL query string.
  1485. static applyFinalMaskToObj(finalmask, obj) {
  1486. if (!obj) return;
  1487. const payload = Inbound.serializeFinalMask(finalmask);
  1488. if (payload.length > 0) {
  1489. obj.fm = payload;
  1490. }
  1491. }
  1492. get clients() {
  1493. switch (this.protocol) {
  1494. case Protocols.VMESS: return this.settings.vmesses;
  1495. case Protocols.VLESS: return this.settings.vlesses;
  1496. case Protocols.TROJAN: return this.settings.trojans;
  1497. case Protocols.SHADOWSOCKS: return this.isSSMultiUser ? this.settings.shadowsockses : null;
  1498. case Protocols.HYSTERIA: return this.settings.hysterias;
  1499. default: return null;
  1500. }
  1501. }
  1502. get protocol() {
  1503. return this._protocol;
  1504. }
  1505. set protocol(protocol) {
  1506. this._protocol = protocol;
  1507. this.settings = Inbound.Settings.getSettings(protocol);
  1508. this.stream = new StreamSettings();
  1509. if (protocol === Protocols.TROJAN) {
  1510. this.tls = false;
  1511. }
  1512. if (protocol === Protocols.HYSTERIA) {
  1513. this.stream.network = 'hysteria';
  1514. this.stream.security = 'tls';
  1515. // Hysteria runs over QUIC and must not inherit TCP TLS ALPN defaults.
  1516. this.stream.tls.alpn = [ALPN_OPTION.H3];
  1517. }
  1518. }
  1519. get network() {
  1520. return this.stream.network;
  1521. }
  1522. set network(network) {
  1523. this.stream.network = network;
  1524. }
  1525. get isTcp() {
  1526. return this.network === "tcp";
  1527. }
  1528. get isWs() {
  1529. return this.network === "ws";
  1530. }
  1531. get isKcp() {
  1532. return this.network === "kcp";
  1533. }
  1534. get isGrpc() {
  1535. return this.network === "grpc";
  1536. }
  1537. get isHttpupgrade() {
  1538. return this.network === "httpupgrade";
  1539. }
  1540. get isXHTTP() {
  1541. return this.network === "xhttp";
  1542. }
  1543. // Shadowsocks
  1544. get method() {
  1545. switch (this.protocol) {
  1546. case Protocols.SHADOWSOCKS:
  1547. return this.settings.method;
  1548. default:
  1549. return "";
  1550. }
  1551. }
  1552. get isSSMultiUser() {
  1553. return this.method != SSMethods.BLAKE3_CHACHA20_POLY1305;
  1554. }
  1555. get isSS2022() {
  1556. return this.method.substring(0, 4) === "2022";
  1557. }
  1558. get serverName() {
  1559. if (this.stream.isTls) return this.stream.tls.sni;
  1560. if (this.stream.isReality) return this.stream.reality.serverNames;
  1561. return "";
  1562. }
  1563. getHeader(obj, name) {
  1564. for (const header of obj.headers) {
  1565. if (header.name.toLowerCase() === name.toLowerCase()) {
  1566. return header.value;
  1567. }
  1568. }
  1569. return "";
  1570. }
  1571. get host() {
  1572. if (this.isTcp) {
  1573. return this.getHeader(this.stream.tcp.request, 'host');
  1574. } else if (this.isWs) {
  1575. return this.stream.ws.host?.length > 0 ? this.stream.ws.host : this.getHeader(this.stream.ws, 'host');
  1576. } else if (this.isHttpupgrade) {
  1577. return this.stream.httpupgrade.host?.length > 0 ? this.stream.httpupgrade.host : this.getHeader(this.stream.httpupgrade, 'host');
  1578. } else if (this.isXHTTP) {
  1579. return this.stream.xhttp.host?.length > 0 ? this.stream.xhttp.host : this.getHeader(this.stream.xhttp, 'host');
  1580. }
  1581. return null;
  1582. }
  1583. get path() {
  1584. if (this.isTcp) {
  1585. return this.stream.tcp.request.path[0];
  1586. } else if (this.isWs) {
  1587. return this.stream.ws.path;
  1588. } else if (this.isHttpupgrade) {
  1589. return this.stream.httpupgrade.path;
  1590. } else if (this.isXHTTP) {
  1591. return this.stream.xhttp.path;
  1592. }
  1593. return null;
  1594. }
  1595. get serviceName() {
  1596. return this.stream.grpc.serviceName;
  1597. }
  1598. isExpiry(index) {
  1599. let exp = this.clients[index].expiryTime;
  1600. return exp > 0 ? exp < new Date().getTime() : false;
  1601. }
  1602. canEnableTls() {
  1603. if (this.protocol === Protocols.HYSTERIA) return true;
  1604. if (![Protocols.VMESS, Protocols.VLESS, Protocols.TROJAN, Protocols.SHADOWSOCKS].includes(this.protocol)) return false;
  1605. return ["tcp", "ws", "http", "grpc", "httpupgrade", "xhttp"].includes(this.network);
  1606. }
  1607. //this is used for xtls-rprx-vision
  1608. canEnableTlsFlow() {
  1609. if (((this.stream.security === 'tls') || (this.stream.security === 'reality')) && (this.network === "tcp")) {
  1610. return this.protocol === Protocols.VLESS;
  1611. }
  1612. return false;
  1613. }
  1614. // Vision seed applies only when vision flow is selected
  1615. canEnableVisionSeed() {
  1616. if (!this.canEnableTlsFlow()) return false;
  1617. const clients = this.settings?.vlesses;
  1618. if (!Array.isArray(clients)) return false;
  1619. return clients.some(c => c?.flow === TLS_FLOW_CONTROL.VISION || c?.flow === TLS_FLOW_CONTROL.VISION_UDP443);
  1620. }
  1621. canEnableReality() {
  1622. if (![Protocols.VLESS, Protocols.TROJAN].includes(this.protocol)) return false;
  1623. return ["tcp", "http", "grpc", "xhttp"].includes(this.network);
  1624. }
  1625. canEnableStream() {
  1626. return [Protocols.VMESS, Protocols.VLESS, Protocols.TROJAN, Protocols.SHADOWSOCKS, Protocols.HYSTERIA].includes(this.protocol);
  1627. }
  1628. reset() {
  1629. this.port = RandomUtil.randomInteger(10000, 60000);
  1630. this.listen = '';
  1631. this.protocol = Protocols.VMESS;
  1632. this.settings = Inbound.Settings.getSettings(Protocols.VMESS);
  1633. this.stream = new StreamSettings();
  1634. this.tag = '';
  1635. this.sniffing = new Sniffing();
  1636. }
  1637. genVmessLink(address = '', port = this.port, forceTls, remark = '', clientId, security) {
  1638. if (this.protocol !== Protocols.VMESS) {
  1639. return '';
  1640. }
  1641. const tls = forceTls == 'same' ? this.stream.security : forceTls;
  1642. let obj = {
  1643. v: '2',
  1644. ps: remark,
  1645. add: address,
  1646. port: port,
  1647. id: clientId,
  1648. scy: security,
  1649. net: this.stream.network,
  1650. tls: tls,
  1651. };
  1652. const network = this.stream.network;
  1653. if (network === 'tcp') {
  1654. const tcp = this.stream.tcp;
  1655. obj.type = tcp.type;
  1656. if (tcp.type === 'http') {
  1657. const request = tcp.request;
  1658. obj.path = request.path.join(',');
  1659. const host = this.getHeader(request, 'host');
  1660. if (host) obj.host = host;
  1661. }
  1662. } else if (network === 'kcp') {
  1663. const kcp = this.stream.kcp;
  1664. obj.mtu = kcp.mtu;
  1665. obj.tti = kcp.tti;
  1666. } else if (network === 'ws') {
  1667. const ws = this.stream.ws;
  1668. obj.path = ws.path;
  1669. obj.host = ws.host?.length > 0 ? ws.host : this.getHeader(ws, 'host');
  1670. } else if (network === 'grpc') {
  1671. obj.path = this.stream.grpc.serviceName;
  1672. obj.authority = this.stream.grpc.authority;
  1673. if (this.stream.grpc.multiMode) {
  1674. obj.type = 'multi'
  1675. }
  1676. } else if (network === 'httpupgrade') {
  1677. const httpupgrade = this.stream.httpupgrade;
  1678. obj.path = httpupgrade.path;
  1679. obj.host = httpupgrade.host?.length > 0 ? httpupgrade.host : this.getHeader(httpupgrade, 'host');
  1680. } else if (network === 'xhttp') {
  1681. const xhttp = this.stream.xhttp;
  1682. obj.path = xhttp.path;
  1683. obj.host = xhttp.host?.length > 0 ? xhttp.host : this.getHeader(xhttp, 'host');
  1684. obj.type = xhttp.mode;
  1685. Inbound.applyXhttpPaddingToObj(xhttp, obj);
  1686. }
  1687. Inbound.applyFinalMaskToObj(this.stream.finalmask, obj);
  1688. if (tls === 'tls') {
  1689. if (!ObjectUtil.isEmpty(this.stream.tls.sni)) {
  1690. obj.sni = this.stream.tls.sni;
  1691. }
  1692. if (!ObjectUtil.isEmpty(this.stream.tls.settings.fingerprint)) {
  1693. obj.fp = this.stream.tls.settings.fingerprint;
  1694. }
  1695. if (this.stream.tls.alpn.length > 0) {
  1696. obj.alpn = this.stream.tls.alpn.join(',');
  1697. }
  1698. }
  1699. return 'vmess://' + Base64.encode(JSON.stringify(obj, null, 2));
  1700. }
  1701. genVLESSLink(address = '', port = this.port, forceTls, remark = '', clientId, flow) {
  1702. const uuid = clientId;
  1703. const type = this.stream.network;
  1704. const security = forceTls == 'same' ? this.stream.security : forceTls;
  1705. const params = new Map();
  1706. params.set("type", this.stream.network);
  1707. params.set("encryption", this.settings.encryption);
  1708. switch (type) {
  1709. case "tcp":
  1710. const tcp = this.stream.tcp;
  1711. if (tcp.type === 'http') {
  1712. const request = tcp.request;
  1713. params.set("path", request.path.join(','));
  1714. const index = request.headers.findIndex(header => header.name.toLowerCase() === 'host');
  1715. if (index >= 0) {
  1716. const host = request.headers[index].value;
  1717. params.set("host", host);
  1718. }
  1719. params.set("headerType", 'http');
  1720. }
  1721. break;
  1722. case "kcp":
  1723. const kcp = this.stream.kcp;
  1724. params.set("mtu", kcp.mtu);
  1725. params.set("tti", kcp.tti);
  1726. break;
  1727. case "ws":
  1728. const ws = this.stream.ws;
  1729. params.set("path", ws.path);
  1730. params.set("host", ws.host?.length > 0 ? ws.host : this.getHeader(ws, 'host'));
  1731. break;
  1732. case "grpc":
  1733. const grpc = this.stream.grpc;
  1734. params.set("serviceName", grpc.serviceName);
  1735. params.set("authority", grpc.authority);
  1736. if (grpc.multiMode) {
  1737. params.set("mode", "multi");
  1738. }
  1739. break;
  1740. case "httpupgrade":
  1741. const httpupgrade = this.stream.httpupgrade;
  1742. params.set("path", httpupgrade.path);
  1743. params.set("host", httpupgrade.host?.length > 0 ? httpupgrade.host : this.getHeader(httpupgrade, 'host'));
  1744. break;
  1745. case "xhttp":
  1746. const xhttp = this.stream.xhttp;
  1747. params.set("path", xhttp.path);
  1748. params.set("host", xhttp.host?.length > 0 ? xhttp.host : this.getHeader(xhttp, 'host'));
  1749. params.set("mode", xhttp.mode);
  1750. Inbound.applyXhttpPaddingToParams(xhttp, params);
  1751. break;
  1752. }
  1753. Inbound.applyFinalMaskToParams(this.stream.finalmask, params);
  1754. if (security === 'tls') {
  1755. params.set("security", "tls");
  1756. if (this.stream.isTls) {
  1757. params.set("fp", this.stream.tls.settings.fingerprint);
  1758. params.set("alpn", this.stream.tls.alpn);
  1759. if (!ObjectUtil.isEmpty(this.stream.tls.sni)) {
  1760. params.set("sni", this.stream.tls.sni);
  1761. }
  1762. if (this.stream.tls.settings.echConfigList?.length > 0) {
  1763. params.set("ech", this.stream.tls.settings.echConfigList);
  1764. }
  1765. if (type == "tcp" && !ObjectUtil.isEmpty(flow)) {
  1766. params.set("flow", flow);
  1767. }
  1768. }
  1769. }
  1770. else if (security === 'reality') {
  1771. params.set("security", "reality");
  1772. params.set("pbk", this.stream.reality.settings.publicKey);
  1773. params.set("fp", this.stream.reality.settings.fingerprint);
  1774. if (!ObjectUtil.isArrEmpty(this.stream.reality.serverNames)) {
  1775. params.set("sni", this.stream.reality.serverNames.split(",")[0]);
  1776. }
  1777. if (this.stream.reality.shortIds.length > 0) {
  1778. params.set("sid", this.stream.reality.shortIds.split(",")[0]);
  1779. }
  1780. if (!ObjectUtil.isEmpty(this.stream.reality.settings.spiderX)) {
  1781. params.set("spx", this.stream.reality.settings.spiderX);
  1782. }
  1783. if (!ObjectUtil.isEmpty(this.stream.reality.settings.mldsa65Verify)) {
  1784. params.set("pqv", this.stream.reality.settings.mldsa65Verify);
  1785. }
  1786. if (type == 'tcp' && !ObjectUtil.isEmpty(flow)) {
  1787. params.set("flow", flow);
  1788. }
  1789. }
  1790. else {
  1791. params.set("security", "none");
  1792. }
  1793. const link = `vless://${uuid}@${address}:${port}`;
  1794. const url = new URL(link);
  1795. for (const [key, value] of params) {
  1796. url.searchParams.set(key, value)
  1797. }
  1798. url.hash = encodeURIComponent(remark);
  1799. return url.toString();
  1800. }
  1801. genSSLink(address = '', port = this.port, forceTls, remark = '', clientPassword) {
  1802. let settings = this.settings;
  1803. const type = this.stream.network;
  1804. const security = forceTls == 'same' ? this.stream.security : forceTls;
  1805. const params = new Map();
  1806. params.set("type", this.stream.network);
  1807. switch (type) {
  1808. case "tcp":
  1809. const tcp = this.stream.tcp;
  1810. if (tcp.type === 'http') {
  1811. const request = tcp.request;
  1812. params.set("path", request.path.join(','));
  1813. const index = request.headers.findIndex(header => header.name.toLowerCase() === 'host');
  1814. if (index >= 0) {
  1815. const host = request.headers[index].value;
  1816. params.set("host", host);
  1817. }
  1818. params.set("headerType", 'http');
  1819. }
  1820. break;
  1821. case "kcp":
  1822. const kcp = this.stream.kcp;
  1823. params.set("mtu", kcp.mtu);
  1824. params.set("tti", kcp.tti);
  1825. break;
  1826. case "ws":
  1827. const ws = this.stream.ws;
  1828. params.set("path", ws.path);
  1829. params.set("host", ws.host?.length > 0 ? ws.host : this.getHeader(ws, 'host'));
  1830. break;
  1831. case "grpc":
  1832. const grpc = this.stream.grpc;
  1833. params.set("serviceName", grpc.serviceName);
  1834. params.set("authority", grpc.authority);
  1835. if (grpc.multiMode) {
  1836. params.set("mode", "multi");
  1837. }
  1838. break;
  1839. case "httpupgrade":
  1840. const httpupgrade = this.stream.httpupgrade;
  1841. params.set("path", httpupgrade.path);
  1842. params.set("host", httpupgrade.host?.length > 0 ? httpupgrade.host : this.getHeader(httpupgrade, 'host'));
  1843. break;
  1844. case "xhttp":
  1845. const xhttp = this.stream.xhttp;
  1846. params.set("path", xhttp.path);
  1847. params.set("host", xhttp.host?.length > 0 ? xhttp.host : this.getHeader(xhttp, 'host'));
  1848. params.set("mode", xhttp.mode);
  1849. Inbound.applyXhttpPaddingToParams(xhttp, params);
  1850. break;
  1851. }
  1852. Inbound.applyFinalMaskToParams(this.stream.finalmask, params);
  1853. if (security === 'tls') {
  1854. params.set("security", "tls");
  1855. if (this.stream.isTls) {
  1856. params.set("fp", this.stream.tls.settings.fingerprint);
  1857. params.set("alpn", this.stream.tls.alpn);
  1858. if (this.stream.tls.settings.echConfigList?.length > 0) {
  1859. params.set("ech", this.stream.tls.settings.echConfigList);
  1860. }
  1861. if (!ObjectUtil.isEmpty(this.stream.tls.sni)) {
  1862. params.set("sni", this.stream.tls.sni);
  1863. }
  1864. }
  1865. }
  1866. let password = new Array();
  1867. if (this.isSS2022) password.push(settings.password);
  1868. if (this.isSSMultiUser) password.push(clientPassword);
  1869. let link = `ss://${Base64.encode(`${settings.method}:${password.join(':')}`, true)}@${address}:${port}`;
  1870. const url = new URL(link);
  1871. for (const [key, value] of params) {
  1872. url.searchParams.set(key, value)
  1873. }
  1874. url.hash = encodeURIComponent(remark);
  1875. return url.toString();
  1876. }
  1877. genTrojanLink(address = '', port = this.port, forceTls, remark = '', clientPassword) {
  1878. const security = forceTls == 'same' ? this.stream.security : forceTls;
  1879. const type = this.stream.network;
  1880. const params = new Map();
  1881. params.set("type", this.stream.network);
  1882. switch (type) {
  1883. case "tcp":
  1884. const tcp = this.stream.tcp;
  1885. if (tcp.type === 'http') {
  1886. const request = tcp.request;
  1887. params.set("path", request.path.join(','));
  1888. const index = request.headers.findIndex(header => header.name.toLowerCase() === 'host');
  1889. if (index >= 0) {
  1890. const host = request.headers[index].value;
  1891. params.set("host", host);
  1892. }
  1893. params.set("headerType", 'http');
  1894. }
  1895. break;
  1896. case "kcp":
  1897. const kcp = this.stream.kcp;
  1898. params.set("mtu", kcp.mtu);
  1899. params.set("tti", kcp.tti);
  1900. break;
  1901. case "ws":
  1902. const ws = this.stream.ws;
  1903. params.set("path", ws.path);
  1904. params.set("host", ws.host?.length > 0 ? ws.host : this.getHeader(ws, 'host'));
  1905. break;
  1906. case "grpc":
  1907. const grpc = this.stream.grpc;
  1908. params.set("serviceName", grpc.serviceName);
  1909. params.set("authority", grpc.authority);
  1910. if (grpc.multiMode) {
  1911. params.set("mode", "multi");
  1912. }
  1913. break;
  1914. case "httpupgrade":
  1915. const httpupgrade = this.stream.httpupgrade;
  1916. params.set("path", httpupgrade.path);
  1917. params.set("host", httpupgrade.host?.length > 0 ? httpupgrade.host : this.getHeader(httpupgrade, 'host'));
  1918. break;
  1919. case "xhttp":
  1920. const xhttp = this.stream.xhttp;
  1921. params.set("path", xhttp.path);
  1922. params.set("host", xhttp.host?.length > 0 ? xhttp.host : this.getHeader(xhttp, 'host'));
  1923. params.set("mode", xhttp.mode);
  1924. Inbound.applyXhttpPaddingToParams(xhttp, params);
  1925. break;
  1926. }
  1927. Inbound.applyFinalMaskToParams(this.stream.finalmask, params);
  1928. if (security === 'tls') {
  1929. params.set("security", "tls");
  1930. if (this.stream.isTls) {
  1931. params.set("fp", this.stream.tls.settings.fingerprint);
  1932. params.set("alpn", this.stream.tls.alpn);
  1933. if (this.stream.tls.settings.echConfigList?.length > 0) {
  1934. params.set("ech", this.stream.tls.settings.echConfigList);
  1935. }
  1936. if (!ObjectUtil.isEmpty(this.stream.tls.sni)) {
  1937. params.set("sni", this.stream.tls.sni);
  1938. }
  1939. }
  1940. }
  1941. else if (security === 'reality') {
  1942. params.set("security", "reality");
  1943. params.set("pbk", this.stream.reality.settings.publicKey);
  1944. params.set("fp", this.stream.reality.settings.fingerprint);
  1945. if (!ObjectUtil.isArrEmpty(this.stream.reality.serverNames)) {
  1946. params.set("sni", this.stream.reality.serverNames.split(",")[0]);
  1947. }
  1948. if (this.stream.reality.shortIds.length > 0) {
  1949. params.set("sid", this.stream.reality.shortIds.split(",")[0]);
  1950. }
  1951. if (!ObjectUtil.isEmpty(this.stream.reality.settings.spiderX)) {
  1952. params.set("spx", this.stream.reality.settings.spiderX);
  1953. }
  1954. if (!ObjectUtil.isEmpty(this.stream.reality.settings.mldsa65Verify)) {
  1955. params.set("pqv", this.stream.reality.settings.mldsa65Verify);
  1956. }
  1957. }
  1958. else {
  1959. params.set("security", "none");
  1960. }
  1961. const link = `trojan://${clientPassword}@${address}:${port}`;
  1962. const url = new URL(link);
  1963. for (const [key, value] of params) {
  1964. url.searchParams.set(key, value)
  1965. }
  1966. url.hash = encodeURIComponent(remark);
  1967. return url.toString();
  1968. }
  1969. genHysteriaLink(address = '', port = this.port, remark = '', clientAuth) {
  1970. const protocol = this.settings.version == 2 ? "hysteria2" : "hysteria";
  1971. const link = `${protocol}://${clientAuth}@${address}:${port}`;
  1972. const params = new Map();
  1973. params.set("security", "tls");
  1974. if (this.stream.tls.settings.fingerprint?.length > 0) params.set("fp", this.stream.tls.settings.fingerprint);
  1975. if (this.stream.tls.alpn?.length > 0) params.set("alpn", this.stream.tls.alpn);
  1976. if (this.stream.tls.settings.allowInsecure) params.set("insecure", "1");
  1977. if (this.stream.tls.settings.echConfigList?.length > 0) params.set("ech", this.stream.tls.settings.echConfigList);
  1978. if (this.stream.tls.sni?.length > 0) params.set("sni", this.stream.tls.sni);
  1979. const udpMasks = this.stream?.finalmask?.udp;
  1980. if (Array.isArray(udpMasks)) {
  1981. const salamanderMask = udpMasks.find(mask => mask?.type === 'salamander');
  1982. const obfsPassword = salamanderMask?.settings?.password;
  1983. if (typeof obfsPassword === 'string' && obfsPassword.length > 0) {
  1984. params.set("obfs", "salamander");
  1985. params.set("obfs-password", obfsPassword);
  1986. }
  1987. }
  1988. Inbound.applyFinalMaskToParams(this.stream.finalmask, params);
  1989. const url = new URL(link);
  1990. for (const [key, value] of params) {
  1991. url.searchParams.set(key, value);
  1992. }
  1993. url.hash = encodeURIComponent(remark);
  1994. return url.toString();
  1995. }
  1996. getWireguardTxt(address, port, remark, peerId) {
  1997. let txt = `[Interface]\n`
  1998. txt += `PrivateKey = ${this.settings.peers[peerId].privateKey}\n`
  1999. txt += `Address = ${this.settings.peers[peerId].allowedIPs[0]}\n`
  2000. txt += `DNS = 1.1.1.1, 1.0.0.1\n`
  2001. if (this.settings.mtu) {
  2002. txt += `MTU = ${this.settings.mtu}\n`
  2003. }
  2004. txt += `\n# ${remark}\n`
  2005. txt += `[Peer]\n`
  2006. txt += `PublicKey = ${this.settings.pubKey}\n`
  2007. txt += `AllowedIPs = 0.0.0.0/0, ::/0\n`
  2008. txt += `Endpoint = ${address}:${port}`
  2009. if (this.settings.peers[peerId].psk) {
  2010. txt += `\nPresharedKey = ${this.settings.peers[peerId].psk}`
  2011. }
  2012. if (this.settings.peers[peerId].keepAlive) {
  2013. txt += `\nPersistentKeepalive = ${this.settings.peers[peerId].keepAlive}\n`
  2014. }
  2015. return txt;
  2016. }
  2017. getWireguardLink(address, port, remark, peerId) {
  2018. const peer = this.settings?.peers?.[peerId];
  2019. if (!peer) return '';
  2020. const link = `wireguard://${address}:${port}`;
  2021. const url = new URL(link);
  2022. url.username = peer.privateKey || '';
  2023. if (this.settings?.pubKey) {
  2024. url.searchParams.set("publickey", this.settings.pubKey);
  2025. }
  2026. if (Array.isArray(peer.allowedIPs) && peer.allowedIPs.length > 0 && peer.allowedIPs[0]) {
  2027. url.searchParams.set("address", peer.allowedIPs[0]);
  2028. }
  2029. if (this.settings?.mtu) {
  2030. url.searchParams.set("mtu", this.settings.mtu);
  2031. }
  2032. url.hash = encodeURIComponent(remark);
  2033. return url.toString();
  2034. }
  2035. genWireguardLinks(remark = '', remarkModel = '-ieo') {
  2036. const addr = !ObjectUtil.isEmpty(this.listen) && this.listen !== "0.0.0.0" ? this.listen : location.hostname;
  2037. const separationChar = remarkModel.charAt(0);
  2038. let links = [];
  2039. this.settings.peers.forEach((p, index) => {
  2040. links.push(this.getWireguardLink(addr, this.port, remark + separationChar + (index + 1), index));
  2041. });
  2042. return links.join('\r\n');
  2043. }
  2044. genWireguardConfigs(remark = '', remarkModel = '-ieo') {
  2045. const addr = !ObjectUtil.isEmpty(this.listen) && this.listen !== "0.0.0.0" ? this.listen : location.hostname;
  2046. const separationChar = remarkModel.charAt(0);
  2047. let links = [];
  2048. this.settings.peers.forEach((p, index) => {
  2049. links.push(this.getWireguardTxt(addr, this.port, remark + separationChar + (index + 1), index));
  2050. });
  2051. return links.join('\r\n');
  2052. }
  2053. genLink(address = '', port = this.port, forceTls = 'same', remark = '', client) {
  2054. switch (this.protocol) {
  2055. case Protocols.VMESS:
  2056. return this.genVmessLink(address, port, forceTls, remark, client.id, client.security);
  2057. case Protocols.VLESS:
  2058. return this.genVLESSLink(address, port, forceTls, remark, client.id, client.flow);
  2059. case Protocols.SHADOWSOCKS:
  2060. return this.genSSLink(address, port, forceTls, remark, this.isSSMultiUser ? client.password : '');
  2061. case Protocols.TROJAN:
  2062. return this.genTrojanLink(address, port, forceTls, remark, client.password);
  2063. case Protocols.HYSTERIA:
  2064. return this.genHysteriaLink(address, port, remark, client.auth.length > 0 ? client.auth : this.stream.hysteria.auth);
  2065. default: return '';
  2066. }
  2067. }
  2068. genAllLinks(remark = '', remarkModel = '-ieo', client) {
  2069. let result = [];
  2070. let email = client ? client.email : '';
  2071. let addr = !ObjectUtil.isEmpty(this.listen) && this.listen !== "0.0.0.0" ? this.listen : location.hostname;
  2072. let port = this.port;
  2073. const separationChar = remarkModel.charAt(0);
  2074. const orderChars = remarkModel.slice(1);
  2075. let orders = {
  2076. 'i': remark,
  2077. 'e': email,
  2078. 'o': '',
  2079. };
  2080. if (ObjectUtil.isArrEmpty(this.stream.externalProxy)) {
  2081. let r = orderChars.split('').map(char => orders[char]).filter(x => x.length > 0).join(separationChar);
  2082. result.push({
  2083. remark: r,
  2084. link: this.genLink(addr, port, 'same', r, client)
  2085. });
  2086. } else {
  2087. this.stream.externalProxy.forEach((ep) => {
  2088. orders['o'] = ep.remark;
  2089. let r = orderChars.split('').map(char => orders[char]).filter(x => x.length > 0).join(separationChar);
  2090. result.push({
  2091. remark: r,
  2092. link: this.genLink(ep.dest, ep.port, ep.forceTls, r, client)
  2093. });
  2094. });
  2095. }
  2096. return result;
  2097. }
  2098. genInboundLinks(remark = '', remarkModel = '-ieo') {
  2099. let addr = !ObjectUtil.isEmpty(this.listen) && this.listen !== "0.0.0.0" ? this.listen : location.hostname;
  2100. if (this.clients) {
  2101. let links = [];
  2102. this.clients.forEach((client) => {
  2103. this.genAllLinks(remark, remarkModel, client).forEach(l => {
  2104. links.push(l.link);
  2105. })
  2106. });
  2107. return links.join('\r\n');
  2108. } else {
  2109. if (this.protocol == Protocols.SHADOWSOCKS && !this.isSSMultiUser) return this.genSSLink(addr, this.port, 'same', remark);
  2110. if (this.protocol == Protocols.WIREGUARD) {
  2111. return this.genWireguardConfigs(remark, remarkModel);
  2112. }
  2113. return '';
  2114. }
  2115. }
  2116. static fromJson(json = {}) {
  2117. return new Inbound(
  2118. json.port,
  2119. json.listen,
  2120. json.protocol,
  2121. Inbound.Settings.fromJson(json.protocol, json.settings),
  2122. StreamSettings.fromJson(json.streamSettings),
  2123. json.tag,
  2124. Sniffing.fromJson(json.sniffing),
  2125. json.clientStats
  2126. )
  2127. }
  2128. toJson() {
  2129. let streamSettings;
  2130. if (this.canEnableStream() || this.stream?.sockopt) {
  2131. streamSettings = this.stream.toJson();
  2132. }
  2133. return {
  2134. port: this.port,
  2135. listen: this.listen,
  2136. protocol: this.protocol,
  2137. settings: this.settings instanceof XrayCommonClass ? this.settings.toJson() : this.settings,
  2138. streamSettings: streamSettings,
  2139. tag: this.tag,
  2140. sniffing: this.sniffing.toJson(),
  2141. clientStats: this.clientStats
  2142. };
  2143. }
  2144. }
  2145. Inbound.Settings = class extends XrayCommonClass {
  2146. constructor(protocol) {
  2147. super();
  2148. this.protocol = protocol;
  2149. }
  2150. static getSettings(protocol) {
  2151. switch (protocol) {
  2152. case Protocols.VMESS: return new Inbound.VmessSettings(protocol);
  2153. case Protocols.VLESS: return new Inbound.VLESSSettings(protocol);
  2154. case Protocols.TROJAN: return new Inbound.TrojanSettings(protocol);
  2155. case Protocols.SHADOWSOCKS: return new Inbound.ShadowsocksSettings(protocol);
  2156. case Protocols.TUNNEL: return new Inbound.TunnelSettings(protocol);
  2157. case Protocols.MIXED: return new Inbound.MixedSettings(protocol);
  2158. case Protocols.HTTP: return new Inbound.HttpSettings(protocol);
  2159. case Protocols.WIREGUARD: return new Inbound.WireguardSettings(protocol);
  2160. case Protocols.TUN: return new Inbound.TunSettings(protocol);
  2161. case Protocols.HYSTERIA: return new Inbound.HysteriaSettings(protocol);
  2162. default: return null;
  2163. }
  2164. }
  2165. static fromJson(protocol, json) {
  2166. switch (protocol) {
  2167. case Protocols.VMESS: return Inbound.VmessSettings.fromJson(json);
  2168. case Protocols.VLESS: return Inbound.VLESSSettings.fromJson(json);
  2169. case Protocols.TROJAN: return Inbound.TrojanSettings.fromJson(json);
  2170. case Protocols.SHADOWSOCKS: return Inbound.ShadowsocksSettings.fromJson(json);
  2171. case Protocols.TUNNEL: return Inbound.TunnelSettings.fromJson(json);
  2172. case Protocols.MIXED: return Inbound.MixedSettings.fromJson(json);
  2173. case Protocols.HTTP: return Inbound.HttpSettings.fromJson(json);
  2174. case Protocols.WIREGUARD: return Inbound.WireguardSettings.fromJson(json);
  2175. case Protocols.TUN: return Inbound.TunSettings.fromJson(json);
  2176. case Protocols.HYSTERIA: return Inbound.HysteriaSettings.fromJson(json);
  2177. default: return null;
  2178. }
  2179. }
  2180. toJson() {
  2181. return {};
  2182. }
  2183. };
  2184. /** Shared user-quota fields and UI helpers for multi-user protocol clients. */
  2185. Inbound.ClientBase = class extends XrayCommonClass {
  2186. constructor(
  2187. email = RandomUtil.randomLowerAndNum(8),
  2188. limitIp = 0,
  2189. totalGB = 0,
  2190. expiryTime = 0,
  2191. enable = true,
  2192. tgId = '',
  2193. subId = RandomUtil.randomLowerAndNum(16),
  2194. comment = '',
  2195. reset = 0,
  2196. created_at = undefined,
  2197. updated_at = undefined,
  2198. ) {
  2199. super();
  2200. this.email = email;
  2201. this.limitIp = limitIp;
  2202. this.totalGB = totalGB;
  2203. this.expiryTime = expiryTime;
  2204. this.enable = enable;
  2205. this.tgId = tgId;
  2206. this.subId = subId;
  2207. this.comment = comment;
  2208. this.reset = reset;
  2209. this.created_at = created_at;
  2210. this.updated_at = updated_at;
  2211. }
  2212. static commonArgsFromJson(json = {}) {
  2213. return [
  2214. json.email,
  2215. json.limitIp,
  2216. json.totalGB,
  2217. json.expiryTime,
  2218. json.enable,
  2219. json.tgId,
  2220. json.subId,
  2221. json.comment,
  2222. json.reset,
  2223. json.created_at,
  2224. json.updated_at,
  2225. ];
  2226. }
  2227. _clientBaseToJson() {
  2228. return {
  2229. email: this.email,
  2230. limitIp: this.limitIp,
  2231. totalGB: this.totalGB,
  2232. expiryTime: this.expiryTime,
  2233. enable: this.enable,
  2234. tgId: this.tgId,
  2235. subId: this.subId,
  2236. comment: this.comment,
  2237. reset: this.reset,
  2238. created_at: this.created_at,
  2239. updated_at: this.updated_at,
  2240. };
  2241. }
  2242. get _expiryTime() {
  2243. if (this.expiryTime === 0 || this.expiryTime === '') {
  2244. return null;
  2245. }
  2246. if (this.expiryTime < 0) {
  2247. return this.expiryTime / -86400000;
  2248. }
  2249. return moment(this.expiryTime);
  2250. }
  2251. set _expiryTime(t) {
  2252. if (t == null || t === '') {
  2253. this.expiryTime = 0;
  2254. } else {
  2255. this.expiryTime = t.valueOf();
  2256. }
  2257. }
  2258. get _totalGB() {
  2259. return NumberFormatter.toFixed(this.totalGB / SizeFormatter.ONE_GB, 2);
  2260. }
  2261. set _totalGB(gb) {
  2262. this.totalGB = NumberFormatter.toFixed(gb * SizeFormatter.ONE_GB, 0);
  2263. }
  2264. };
  2265. Inbound.VmessSettings = class extends Inbound.Settings {
  2266. constructor(protocol,
  2267. vmesses = [new Inbound.VmessSettings.VMESS()]) {
  2268. super(protocol);
  2269. this.vmesses = vmesses;
  2270. }
  2271. indexOfVmessById(id) {
  2272. return this.vmesses.findIndex(VMESS => VMESS.id === id);
  2273. }
  2274. addVmess(VMESS) {
  2275. if (this.indexOfVmessById(VMESS.id) >= 0) {
  2276. return false;
  2277. }
  2278. this.vmesses.push(VMESS);
  2279. }
  2280. delVmess(VMESS) {
  2281. const i = this.indexOfVmessById(VMESS.id);
  2282. if (i >= 0) {
  2283. this.vmesses.splice(i, 1);
  2284. }
  2285. }
  2286. static fromJson(json = {}) {
  2287. return new Inbound.VmessSettings(
  2288. Protocols.VMESS,
  2289. (json.clients || []).map(client => Inbound.VmessSettings.VMESS.fromJson(client)),
  2290. );
  2291. }
  2292. toJson() {
  2293. return {
  2294. clients: Inbound.VmessSettings.toJsonArray(this.vmesses),
  2295. };
  2296. }
  2297. };
  2298. Inbound.VmessSettings.VMESS = class extends Inbound.ClientBase {
  2299. constructor(
  2300. id = RandomUtil.randomUUID(),
  2301. security = USERS_SECURITY.AUTO,
  2302. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2303. ) {
  2304. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2305. this.id = id;
  2306. this.security = security;
  2307. }
  2308. static fromJson(json = {}) {
  2309. return new Inbound.VmessSettings.VMESS(
  2310. json.id,
  2311. json.security,
  2312. ...Inbound.ClientBase.commonArgsFromJson(json),
  2313. );
  2314. }
  2315. toJson() {
  2316. return {
  2317. id: this.id,
  2318. security: this.security,
  2319. ...this._clientBaseToJson(),
  2320. };
  2321. }
  2322. };
  2323. Inbound.VLESSSettings = class extends Inbound.Settings {
  2324. constructor(
  2325. protocol,
  2326. vlesses = [new Inbound.VLESSSettings.VLESS()],
  2327. decryption = "none",
  2328. encryption = "none",
  2329. fallbacks = [],
  2330. selectedAuth = undefined,
  2331. testseed = [900, 500, 900, 256],
  2332. ) {
  2333. super(protocol);
  2334. this.vlesses = vlesses;
  2335. this.decryption = decryption;
  2336. this.encryption = encryption;
  2337. this.fallbacks = fallbacks;
  2338. this.selectedAuth = selectedAuth;
  2339. this.testseed = testseed;
  2340. }
  2341. addFallback() {
  2342. this.fallbacks.push(new Inbound.VLESSSettings.Fallback());
  2343. }
  2344. delFallback(index) {
  2345. this.fallbacks.splice(index, 1);
  2346. }
  2347. static fromJson(json = {}) {
  2348. // Ensure testseed is always initialized as an array
  2349. let testseed = [900, 500, 900, 256];
  2350. if (json.testseed && Array.isArray(json.testseed) && json.testseed.length >= 4) {
  2351. testseed = json.testseed;
  2352. }
  2353. const obj = new Inbound.VLESSSettings(
  2354. Protocols.VLESS,
  2355. (json.clients || []).map(client => Inbound.VLESSSettings.VLESS.fromJson(client)),
  2356. json.decryption,
  2357. json.encryption,
  2358. Inbound.VLESSSettings.Fallback.fromJson(json.fallbacks || []),
  2359. json.selectedAuth,
  2360. testseed
  2361. );
  2362. return obj;
  2363. }
  2364. toJson() {
  2365. const json = {
  2366. clients: Inbound.VLESSSettings.toJsonArray(this.vlesses),
  2367. };
  2368. if (this.decryption) {
  2369. json.decryption = this.decryption;
  2370. }
  2371. if (this.encryption) {
  2372. json.encryption = this.encryption;
  2373. }
  2374. if (this.fallbacks && this.fallbacks.length > 0) {
  2375. json.fallbacks = Inbound.VLESSSettings.toJsonArray(this.fallbacks);
  2376. }
  2377. if (this.selectedAuth) {
  2378. json.selectedAuth = this.selectedAuth;
  2379. }
  2380. // Only include testseed if at least one client has a flow set
  2381. const hasFlow = this.vlesses && this.vlesses.some(vless => vless.flow && vless.flow !== '');
  2382. if (hasFlow && this.testseed && this.testseed.length >= 4) {
  2383. json.testseed = this.testseed;
  2384. }
  2385. return json;
  2386. }
  2387. };
  2388. Inbound.VLESSSettings.VLESS = class extends Inbound.ClientBase {
  2389. constructor(
  2390. id = RandomUtil.randomUUID(),
  2391. flow = '',
  2392. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2393. ) {
  2394. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2395. this.id = id;
  2396. this.flow = flow;
  2397. }
  2398. static fromJson(json = {}) {
  2399. return new Inbound.VLESSSettings.VLESS(
  2400. json.id,
  2401. json.flow,
  2402. ...Inbound.ClientBase.commonArgsFromJson(json),
  2403. );
  2404. }
  2405. toJson() {
  2406. return {
  2407. id: this.id,
  2408. flow: this.flow,
  2409. ...this._clientBaseToJson(),
  2410. };
  2411. }
  2412. };
  2413. Inbound.VLESSSettings.Fallback = class extends XrayCommonClass {
  2414. constructor(name = "", alpn = '', path = '', dest = '', xver = 0) {
  2415. super();
  2416. this.name = name;
  2417. this.alpn = alpn;
  2418. this.path = path;
  2419. this.dest = dest;
  2420. this.xver = xver;
  2421. }
  2422. toJson() {
  2423. let xver = this.xver;
  2424. if (!Number.isInteger(xver)) {
  2425. xver = 0;
  2426. }
  2427. return {
  2428. name: this.name,
  2429. alpn: this.alpn,
  2430. path: this.path,
  2431. dest: this.dest,
  2432. xver: xver,
  2433. }
  2434. }
  2435. static fromJson(json = []) {
  2436. const fallbacks = [];
  2437. for (let fallback of json) {
  2438. fallbacks.push(new Inbound.VLESSSettings.Fallback(
  2439. fallback.name,
  2440. fallback.alpn,
  2441. fallback.path,
  2442. fallback.dest,
  2443. fallback.xver,
  2444. ))
  2445. }
  2446. return fallbacks;
  2447. }
  2448. };
  2449. Inbound.TrojanSettings = class extends Inbound.Settings {
  2450. constructor(protocol,
  2451. trojans = [new Inbound.TrojanSettings.Trojan()],
  2452. fallbacks = [],) {
  2453. super(protocol);
  2454. this.trojans = trojans;
  2455. this.fallbacks = fallbacks;
  2456. }
  2457. addFallback() {
  2458. this.fallbacks.push(new Inbound.TrojanSettings.Fallback());
  2459. }
  2460. delFallback(index) {
  2461. this.fallbacks.splice(index, 1);
  2462. }
  2463. static fromJson(json = {}) {
  2464. return new Inbound.TrojanSettings(
  2465. Protocols.TROJAN,
  2466. (json.clients || []).map(client => Inbound.TrojanSettings.Trojan.fromJson(client)),
  2467. Inbound.TrojanSettings.Fallback.fromJson(json.fallbacks),);
  2468. }
  2469. toJson() {
  2470. return {
  2471. clients: Inbound.TrojanSettings.toJsonArray(this.trojans),
  2472. fallbacks: Inbound.TrojanSettings.toJsonArray(this.fallbacks)
  2473. };
  2474. }
  2475. };
  2476. Inbound.TrojanSettings.Trojan = class extends Inbound.ClientBase {
  2477. constructor(
  2478. password = RandomUtil.randomSeq(10),
  2479. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2480. ) {
  2481. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2482. this.password = password;
  2483. }
  2484. toJson() {
  2485. return {
  2486. password: this.password,
  2487. ...this._clientBaseToJson(),
  2488. };
  2489. }
  2490. static fromJson(json = {}) {
  2491. return new Inbound.TrojanSettings.Trojan(
  2492. json.password,
  2493. ...Inbound.ClientBase.commonArgsFromJson(json),
  2494. );
  2495. }
  2496. };
  2497. Inbound.TrojanSettings.Fallback = class extends XrayCommonClass {
  2498. constructor(name = "", alpn = '', path = '', dest = '', xver = 0) {
  2499. super();
  2500. this.name = name;
  2501. this.alpn = alpn;
  2502. this.path = path;
  2503. this.dest = dest;
  2504. this.xver = xver;
  2505. }
  2506. toJson() {
  2507. let xver = this.xver;
  2508. if (!Number.isInteger(xver)) {
  2509. xver = 0;
  2510. }
  2511. return {
  2512. name: this.name,
  2513. alpn: this.alpn,
  2514. path: this.path,
  2515. dest: this.dest,
  2516. xver: xver,
  2517. }
  2518. }
  2519. static fromJson(json = []) {
  2520. const fallbacks = [];
  2521. for (let fallback of json) {
  2522. fallbacks.push(new Inbound.TrojanSettings.Fallback(
  2523. fallback.name,
  2524. fallback.alpn,
  2525. fallback.path,
  2526. fallback.dest,
  2527. fallback.xver,
  2528. ))
  2529. }
  2530. return fallbacks;
  2531. }
  2532. };
  2533. Inbound.ShadowsocksSettings = class extends Inbound.Settings {
  2534. constructor(protocol,
  2535. method = SSMethods.BLAKE3_AES_256_GCM,
  2536. password = RandomUtil.randomShadowsocksPassword(),
  2537. network = 'tcp,udp',
  2538. shadowsockses = [new Inbound.ShadowsocksSettings.Shadowsocks()],
  2539. ivCheck = false,
  2540. ) {
  2541. super(protocol);
  2542. this.method = method;
  2543. this.password = password;
  2544. this.network = network;
  2545. this.shadowsockses = shadowsockses;
  2546. this.ivCheck = ivCheck;
  2547. }
  2548. static fromJson(json = {}) {
  2549. return new Inbound.ShadowsocksSettings(
  2550. Protocols.SHADOWSOCKS,
  2551. json.method,
  2552. json.password,
  2553. json.network,
  2554. (json.clients || []).map(client => Inbound.ShadowsocksSettings.Shadowsocks.fromJson(client)),
  2555. json.ivCheck,
  2556. );
  2557. }
  2558. toJson() {
  2559. return {
  2560. method: this.method,
  2561. password: this.password,
  2562. network: this.network,
  2563. clients: Inbound.ShadowsocksSettings.toJsonArray(this.shadowsockses),
  2564. ivCheck: this.ivCheck,
  2565. };
  2566. }
  2567. };
  2568. Inbound.ShadowsocksSettings.Shadowsocks = class extends Inbound.ClientBase {
  2569. constructor(
  2570. method = '',
  2571. password = RandomUtil.randomShadowsocksPassword(),
  2572. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2573. ) {
  2574. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2575. this.method = method;
  2576. this.password = password;
  2577. }
  2578. toJson() {
  2579. return {
  2580. method: this.method,
  2581. password: this.password,
  2582. ...this._clientBaseToJson(),
  2583. };
  2584. }
  2585. static fromJson(json = {}) {
  2586. return new Inbound.ShadowsocksSettings.Shadowsocks(
  2587. json.method,
  2588. json.password,
  2589. ...Inbound.ClientBase.commonArgsFromJson(json),
  2590. );
  2591. }
  2592. };
  2593. Inbound.HysteriaSettings = class extends Inbound.Settings {
  2594. constructor(protocol, version = 2, hysterias = [new Inbound.HysteriaSettings.Hysteria()]) {
  2595. super(protocol);
  2596. this.version = version;
  2597. this.hysterias = hysterias;
  2598. }
  2599. static fromJson(json = {}) {
  2600. return new Inbound.HysteriaSettings(
  2601. Protocols.HYSTERIA,
  2602. json.version ?? 2,
  2603. (json.clients || []).map(client => Inbound.HysteriaSettings.Hysteria.fromJson(client)),
  2604. );
  2605. }
  2606. toJson() {
  2607. return {
  2608. version: this.version,
  2609. clients: Inbound.HysteriaSettings.toJsonArray(this.hysterias),
  2610. };
  2611. }
  2612. };
  2613. Inbound.HysteriaSettings.Hysteria = class extends Inbound.ClientBase {
  2614. constructor(
  2615. auth = RandomUtil.randomSeq(10),
  2616. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2617. ) {
  2618. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2619. this.auth = auth;
  2620. }
  2621. toJson() {
  2622. return {
  2623. auth: this.auth,
  2624. ...this._clientBaseToJson(),
  2625. };
  2626. }
  2627. static fromJson(json = {}) {
  2628. return new Inbound.HysteriaSettings.Hysteria(
  2629. json.auth,
  2630. ...Inbound.ClientBase.commonArgsFromJson(json),
  2631. );
  2632. }
  2633. };
  2634. Inbound.TunnelSettings = class extends Inbound.Settings {
  2635. constructor(
  2636. protocol,
  2637. address,
  2638. port,
  2639. portMap = [],
  2640. network = 'tcp,udp',
  2641. followRedirect = false
  2642. ) {
  2643. super(protocol);
  2644. this.address = address;
  2645. this.port = port;
  2646. this.portMap = portMap;
  2647. this.network = network;
  2648. this.followRedirect = followRedirect;
  2649. }
  2650. static fromJson(json = {}) {
  2651. return new Inbound.TunnelSettings(
  2652. Protocols.TUNNEL,
  2653. json.address,
  2654. json.port,
  2655. XrayCommonClass.toHeaders(json.portMap),
  2656. json.network,
  2657. json.followRedirect,
  2658. );
  2659. }
  2660. toJson() {
  2661. return {
  2662. address: this.address,
  2663. port: this.port,
  2664. portMap: XrayCommonClass.toV2Headers(this.portMap, false),
  2665. network: this.network,
  2666. followRedirect: this.followRedirect,
  2667. };
  2668. }
  2669. };
  2670. Inbound.MixedSettings = class extends Inbound.Settings {
  2671. constructor(protocol, auth = 'password', accounts = [new Inbound.MixedSettings.SocksAccount()], udp = false, ip = '127.0.0.1') {
  2672. super(protocol);
  2673. this.auth = auth;
  2674. this.accounts = accounts;
  2675. this.udp = udp;
  2676. this.ip = ip;
  2677. }
  2678. addAccount(account) {
  2679. this.accounts.push(account);
  2680. }
  2681. delAccount(index) {
  2682. this.accounts.splice(index, 1);
  2683. }
  2684. static fromJson(json = {}) {
  2685. let accounts;
  2686. if (json.auth === 'password') {
  2687. accounts = json.accounts.map(
  2688. account => Inbound.MixedSettings.SocksAccount.fromJson(account)
  2689. )
  2690. }
  2691. return new Inbound.MixedSettings(
  2692. Protocols.MIXED,
  2693. json.auth,
  2694. accounts,
  2695. json.udp,
  2696. json.ip,
  2697. );
  2698. }
  2699. toJson() {
  2700. return {
  2701. auth: this.auth,
  2702. accounts: this.auth === 'password' ? this.accounts.map(account => account.toJson()) : undefined,
  2703. udp: this.udp,
  2704. ip: this.ip,
  2705. };
  2706. }
  2707. };
  2708. Inbound.MixedSettings.SocksAccount = class extends XrayCommonClass {
  2709. constructor(user = RandomUtil.randomSeq(10), pass = RandomUtil.randomSeq(10)) {
  2710. super();
  2711. this.user = user;
  2712. this.pass = pass;
  2713. }
  2714. static fromJson(json = {}) {
  2715. return new Inbound.MixedSettings.SocksAccount(json.user, json.pass);
  2716. }
  2717. };
  2718. Inbound.HttpSettings = class extends Inbound.Settings {
  2719. constructor(
  2720. protocol,
  2721. accounts = [new Inbound.HttpSettings.HttpAccount()],
  2722. allowTransparent = false,
  2723. ) {
  2724. super(protocol);
  2725. this.accounts = accounts;
  2726. this.allowTransparent = allowTransparent;
  2727. }
  2728. addAccount(account) {
  2729. this.accounts.push(account);
  2730. }
  2731. delAccount(index) {
  2732. this.accounts.splice(index, 1);
  2733. }
  2734. static fromJson(json = {}) {
  2735. return new Inbound.HttpSettings(
  2736. Protocols.HTTP,
  2737. json.accounts.map(account => Inbound.HttpSettings.HttpAccount.fromJson(account)),
  2738. json.allowTransparent,
  2739. );
  2740. }
  2741. toJson() {
  2742. return {
  2743. accounts: Inbound.HttpSettings.toJsonArray(this.accounts),
  2744. allowTransparent: this.allowTransparent,
  2745. };
  2746. }
  2747. };
  2748. Inbound.HttpSettings.HttpAccount = class extends XrayCommonClass {
  2749. constructor(user = RandomUtil.randomSeq(10), pass = RandomUtil.randomSeq(10)) {
  2750. super();
  2751. this.user = user;
  2752. this.pass = pass;
  2753. }
  2754. static fromJson(json = {}) {
  2755. return new Inbound.HttpSettings.HttpAccount(json.user, json.pass);
  2756. }
  2757. };
  2758. Inbound.WireguardSettings = class extends XrayCommonClass {
  2759. constructor(
  2760. protocol,
  2761. mtu = 1420,
  2762. secretKey = Wireguard.generateKeypair().privateKey,
  2763. peers = [new Inbound.WireguardSettings.Peer()],
  2764. noKernelTun = false
  2765. ) {
  2766. super(protocol);
  2767. this.mtu = mtu;
  2768. this.secretKey = secretKey;
  2769. this.pubKey = secretKey.length > 0 ? Wireguard.generateKeypair(secretKey).publicKey : '';
  2770. this.peers = peers;
  2771. this.noKernelTun = noKernelTun;
  2772. }
  2773. addPeer() {
  2774. this.peers.push(new Inbound.WireguardSettings.Peer(null, null, '', ['10.0.0.' + (this.peers.length + 2)]));
  2775. }
  2776. delPeer(index) {
  2777. this.peers.splice(index, 1);
  2778. }
  2779. static fromJson(json = {}) {
  2780. return new Inbound.WireguardSettings(
  2781. Protocols.WIREGUARD,
  2782. json.mtu,
  2783. json.secretKey,
  2784. json.peers.map(peer => Inbound.WireguardSettings.Peer.fromJson(peer)),
  2785. json.noKernelTun,
  2786. );
  2787. }
  2788. toJson() {
  2789. return {
  2790. mtu: this.mtu ?? undefined,
  2791. secretKey: this.secretKey,
  2792. peers: Inbound.WireguardSettings.Peer.toJsonArray(this.peers),
  2793. noKernelTun: this.noKernelTun,
  2794. };
  2795. }
  2796. };
  2797. Inbound.WireguardSettings.Peer = class extends XrayCommonClass {
  2798. constructor(privateKey, publicKey, psk = '', allowedIPs = ['10.0.0.2/32'], keepAlive = 0) {
  2799. super();
  2800. this.privateKey = privateKey
  2801. this.publicKey = publicKey;
  2802. if (!this.publicKey) {
  2803. [this.publicKey, this.privateKey] = Object.values(Wireguard.generateKeypair())
  2804. }
  2805. this.psk = psk;
  2806. allowedIPs.forEach((a, index) => {
  2807. if (a.length > 0 && !a.includes('/')) allowedIPs[index] += '/32';
  2808. })
  2809. this.allowedIPs = allowedIPs;
  2810. this.keepAlive = keepAlive;
  2811. }
  2812. static fromJson(json = {}) {
  2813. return new Inbound.WireguardSettings.Peer(
  2814. json.privateKey,
  2815. json.publicKey,
  2816. json.preSharedKey,
  2817. json.allowedIPs,
  2818. json.keepAlive
  2819. );
  2820. }
  2821. toJson() {
  2822. this.allowedIPs.forEach((a, index) => {
  2823. if (a.length > 0 && !a.includes('/')) this.allowedIPs[index] += '/32';
  2824. });
  2825. return {
  2826. privateKey: this.privateKey,
  2827. publicKey: this.publicKey,
  2828. preSharedKey: this.psk.length > 0 ? this.psk : undefined,
  2829. allowedIPs: this.allowedIPs,
  2830. keepAlive: this.keepAlive ?? undefined,
  2831. };
  2832. }
  2833. };
  2834. Inbound.TunSettings = class extends Inbound.Settings {
  2835. constructor(
  2836. protocol,
  2837. name = 'xray0',
  2838. mtu = [1500, 1280],
  2839. gateway = [],
  2840. dns = [],
  2841. userLevel = 0,
  2842. autoSystemRoutingTable = [],
  2843. autoOutboundsInterface = 'auto'
  2844. ) {
  2845. super(protocol);
  2846. this.name = name;
  2847. this.mtu = this._normalizeMtu(mtu);
  2848. this.gateway = Array.isArray(gateway) ? gateway : [];
  2849. this.dns = Array.isArray(dns) ? dns : [];
  2850. this.userLevel = userLevel;
  2851. this.autoSystemRoutingTable = Array.isArray(autoSystemRoutingTable) ? autoSystemRoutingTable : [];
  2852. this.autoOutboundsInterface = autoOutboundsInterface;
  2853. }
  2854. _normalizeMtu(mtu) {
  2855. if (!Array.isArray(mtu)) {
  2856. const single = Number(mtu) || 1500;
  2857. return [single, single];
  2858. }
  2859. if (mtu.length === 0) {
  2860. return [1500, 1280];
  2861. }
  2862. if (mtu.length === 1) {
  2863. const single = Number(mtu[0]) || 1500;
  2864. return [single, single];
  2865. }
  2866. return [Number(mtu[0]) || 1500, Number(mtu[1]) || 1280];
  2867. }
  2868. static fromJson(json = {}) {
  2869. return new Inbound.TunSettings(
  2870. Protocols.TUN,
  2871. json.name ?? 'xray0',
  2872. json.mtu ?? json.MTU ?? [1500, 1280],
  2873. json.gateway ?? json.Gateway ?? [],
  2874. json.dns ?? json.DNS ?? [],
  2875. json.userLevel ?? 0,
  2876. json.autoSystemRoutingTable ?? [],
  2877. Object.prototype.hasOwnProperty.call(json, 'autoOutboundsInterface') ? json.autoOutboundsInterface : 'auto'
  2878. );
  2879. }
  2880. toJson() {
  2881. return {
  2882. name: this.name || 'xray0',
  2883. mtu: this._normalizeMtu(this.mtu),
  2884. gateway: this.gateway,
  2885. dns: this.dns,
  2886. userLevel: this.userLevel || 0,
  2887. autoSystemRoutingTable: this.autoSystemRoutingTable,
  2888. autoOutboundsInterface: this.autoOutboundsInterface,
  2889. };
  2890. }
  2891. };