inbound.js 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256
  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. // Mirrors the inbound (server-side) view of Xray-core's SplitHTTPConfig
  424. // (infra/conf/transport_internet.go). Only fields the server actually
  425. // reads at runtime, plus the bidirectional fields the server enforces,
  426. // live here. Client-only fields (uplinkHTTPMethod, uplinkChunkSize,
  427. // noGRPCHeader, scMinPostsIntervalMs, xmux, downloadSettings) belong on
  428. // the outbound class instead.
  429. //
  430. // `headers` is technically client-only at runtime (xray's listener
  431. // doesn't read it) but we keep it here so the admin can set request
  432. // headers that get embedded into the share link's `extra` blob — the
  433. // client picks them up from there.
  434. class xHTTPStreamSettings extends XrayCommonClass {
  435. constructor(
  436. // Bidirectional — must match between client and server
  437. path = '/',
  438. host = '',
  439. mode = MODE_OPTION.AUTO,
  440. xPaddingBytes = "100-1000",
  441. xPaddingObfsMode = false,
  442. xPaddingKey = '',
  443. xPaddingHeader = '',
  444. xPaddingPlacement = '',
  445. xPaddingMethod = '',
  446. sessionPlacement = '',
  447. sessionKey = '',
  448. seqPlacement = '',
  449. seqKey = '',
  450. uplinkDataPlacement = '',
  451. uplinkDataKey = '',
  452. scMaxEachPostBytes = "1000000",
  453. // Server-side only
  454. noSSEHeader = false,
  455. scMaxBufferedPosts = 30,
  456. scStreamUpServerSecs = "20-80",
  457. serverMaxHeaderBytes = 0,
  458. // URL-share only — embedded in the link's `extra` blob so clients
  459. // pick them up; xray's listener ignores them at runtime.
  460. headers = [],
  461. ) {
  462. super();
  463. this.path = path;
  464. this.host = host;
  465. this.mode = mode;
  466. this.xPaddingBytes = xPaddingBytes;
  467. this.xPaddingObfsMode = xPaddingObfsMode;
  468. this.xPaddingKey = xPaddingKey;
  469. this.xPaddingHeader = xPaddingHeader;
  470. this.xPaddingPlacement = xPaddingPlacement;
  471. this.xPaddingMethod = xPaddingMethod;
  472. this.sessionPlacement = sessionPlacement;
  473. this.sessionKey = sessionKey;
  474. this.seqPlacement = seqPlacement;
  475. this.seqKey = seqKey;
  476. this.uplinkDataPlacement = uplinkDataPlacement;
  477. this.uplinkDataKey = uplinkDataKey;
  478. this.scMaxEachPostBytes = scMaxEachPostBytes;
  479. this.noSSEHeader = noSSEHeader;
  480. this.scMaxBufferedPosts = scMaxBufferedPosts;
  481. this.scStreamUpServerSecs = scStreamUpServerSecs;
  482. this.serverMaxHeaderBytes = serverMaxHeaderBytes;
  483. this.headers = headers;
  484. }
  485. addHeader(name, value) {
  486. this.headers.push({ name: name, value: value });
  487. }
  488. removeHeader(index) {
  489. this.headers.splice(index, 1);
  490. }
  491. static fromJson(json = {}) {
  492. return new xHTTPStreamSettings(
  493. json.path,
  494. json.host,
  495. json.mode,
  496. json.xPaddingBytes,
  497. json.xPaddingObfsMode,
  498. json.xPaddingKey,
  499. json.xPaddingHeader,
  500. json.xPaddingPlacement,
  501. json.xPaddingMethod,
  502. json.sessionPlacement,
  503. json.sessionKey,
  504. json.seqPlacement,
  505. json.seqKey,
  506. json.uplinkDataPlacement,
  507. json.uplinkDataKey,
  508. json.scMaxEachPostBytes,
  509. json.noSSEHeader,
  510. json.scMaxBufferedPosts,
  511. json.scStreamUpServerSecs,
  512. json.serverMaxHeaderBytes,
  513. XrayCommonClass.toHeaders(json.headers),
  514. );
  515. }
  516. toJson() {
  517. return {
  518. path: this.path,
  519. host: this.host,
  520. mode: this.mode,
  521. xPaddingBytes: this.xPaddingBytes,
  522. xPaddingObfsMode: this.xPaddingObfsMode,
  523. xPaddingKey: this.xPaddingKey,
  524. xPaddingHeader: this.xPaddingHeader,
  525. xPaddingPlacement: this.xPaddingPlacement,
  526. xPaddingMethod: this.xPaddingMethod,
  527. sessionPlacement: this.sessionPlacement,
  528. sessionKey: this.sessionKey,
  529. seqPlacement: this.seqPlacement,
  530. seqKey: this.seqKey,
  531. uplinkDataPlacement: this.uplinkDataPlacement,
  532. uplinkDataKey: this.uplinkDataKey,
  533. scMaxEachPostBytes: this.scMaxEachPostBytes,
  534. noSSEHeader: this.noSSEHeader,
  535. scMaxBufferedPosts: this.scMaxBufferedPosts,
  536. scStreamUpServerSecs: this.scStreamUpServerSecs,
  537. serverMaxHeaderBytes: this.serverMaxHeaderBytes,
  538. headers: XrayCommonClass.toV2Headers(this.headers, false),
  539. };
  540. }
  541. }
  542. class HysteriaStreamSettings extends XrayCommonClass {
  543. constructor(
  544. protocol,
  545. version = 2,
  546. auth = '',
  547. udpIdleTimeout = 60,
  548. masquerade,
  549. ) {
  550. super(protocol);
  551. this.version = version;
  552. this.auth = auth;
  553. this.udpIdleTimeout = udpIdleTimeout;
  554. this.masquerade = masquerade;
  555. }
  556. static fromJson(json = {}) {
  557. return new HysteriaStreamSettings(
  558. json.protocol,
  559. json.version ?? 2,
  560. json.auth ?? '',
  561. json.udpIdleTimeout ?? 60,
  562. json.masquerade ? HysteriaMasquerade.fromJson(json.masquerade) : undefined,
  563. );
  564. }
  565. toJson() {
  566. return {
  567. protocol: this.protocol,
  568. version: this.version,
  569. auth: this.auth,
  570. udpIdleTimeout: this.udpIdleTimeout,
  571. masquerade: this.masqueradeSwitch ? this.masquerade.toJson() : undefined,
  572. };
  573. }
  574. get masqueradeSwitch() {
  575. return this.masquerade != undefined;
  576. }
  577. set masqueradeSwitch(value) {
  578. this.masquerade = value ? new HysteriaMasquerade() : undefined;
  579. }
  580. };
  581. class HysteriaMasquerade extends XrayCommonClass {
  582. constructor(
  583. type = 'proxy',
  584. dir = '',
  585. url = '',
  586. rewriteHost = false,
  587. insecure = false,
  588. content = '',
  589. headers = [],
  590. statusCode = 0,
  591. ) {
  592. super();
  593. this.type = type;
  594. this.dir = dir;
  595. this.url = url;
  596. this.rewriteHost = rewriteHost;
  597. this.insecure = insecure;
  598. this.content = content;
  599. this.headers = headers;
  600. this.statusCode = statusCode;
  601. }
  602. addHeader(name, value) {
  603. this.headers.push({ name: name, value: value });
  604. }
  605. removeHeader(index) {
  606. this.headers.splice(index, 1);
  607. }
  608. static fromJson(json = {}) {
  609. return new HysteriaMasquerade(
  610. json.type,
  611. json.dir,
  612. json.url,
  613. json.rewriteHost,
  614. json.insecure,
  615. json.content,
  616. XrayCommonClass.toHeaders(json.headers),
  617. json.statusCode,
  618. );
  619. }
  620. toJson() {
  621. return {
  622. type: this.type,
  623. dir: this.dir,
  624. url: this.url,
  625. rewriteHost: this.rewriteHost,
  626. insecure: this.insecure,
  627. content: this.content,
  628. headers: XrayCommonClass.toV2Headers(this.headers, false),
  629. statusCode: this.statusCode,
  630. };
  631. }
  632. };
  633. class TlsStreamSettings extends XrayCommonClass {
  634. constructor(
  635. serverName = '',
  636. minVersion = TLS_VERSION_OPTION.TLS12,
  637. maxVersion = TLS_VERSION_OPTION.TLS13,
  638. cipherSuites = '',
  639. rejectUnknownSni = false,
  640. disableSystemRoot = false,
  641. enableSessionResumption = false,
  642. certificates = [new TlsStreamSettings.Cert()],
  643. alpn = [ALPN_OPTION.H2, ALPN_OPTION.HTTP1],
  644. echServerKeys = '',
  645. settings = new TlsStreamSettings.Settings()
  646. ) {
  647. super();
  648. this.sni = serverName;
  649. this.minVersion = minVersion;
  650. this.maxVersion = maxVersion;
  651. this.cipherSuites = cipherSuites;
  652. this.rejectUnknownSni = rejectUnknownSni;
  653. this.disableSystemRoot = disableSystemRoot;
  654. this.enableSessionResumption = enableSessionResumption;
  655. this.certs = certificates;
  656. this.alpn = alpn;
  657. this.echServerKeys = echServerKeys;
  658. this.settings = settings;
  659. }
  660. addCert() {
  661. this.certs.push(new TlsStreamSettings.Cert());
  662. }
  663. removeCert(index) {
  664. this.certs.splice(index, 1);
  665. }
  666. static fromJson(json = {}) {
  667. let certs;
  668. let settings;
  669. if (!ObjectUtil.isEmpty(json.certificates)) {
  670. certs = json.certificates.map(cert => TlsStreamSettings.Cert.fromJson(cert));
  671. }
  672. if (!ObjectUtil.isEmpty(json.settings)) {
  673. settings = new TlsStreamSettings.Settings(json.settings.fingerprint, json.settings.echConfigList);
  674. }
  675. return new TlsStreamSettings(
  676. json.serverName,
  677. json.minVersion,
  678. json.maxVersion,
  679. json.cipherSuites,
  680. json.rejectUnknownSni,
  681. json.disableSystemRoot,
  682. json.enableSessionResumption,
  683. certs,
  684. json.alpn,
  685. json.echServerKeys,
  686. settings,
  687. );
  688. }
  689. toJson() {
  690. return {
  691. serverName: this.sni,
  692. minVersion: this.minVersion,
  693. maxVersion: this.maxVersion,
  694. cipherSuites: this.cipherSuites,
  695. rejectUnknownSni: this.rejectUnknownSni,
  696. disableSystemRoot: this.disableSystemRoot,
  697. enableSessionResumption: this.enableSessionResumption,
  698. certificates: TlsStreamSettings.toJsonArray(this.certs),
  699. alpn: this.alpn,
  700. echServerKeys: this.echServerKeys,
  701. settings: this.settings,
  702. };
  703. }
  704. }
  705. TlsStreamSettings.Cert = class extends XrayCommonClass {
  706. constructor(
  707. useFile = true,
  708. certificateFile = '',
  709. keyFile = '',
  710. certificate = '',
  711. key = '',
  712. oneTimeLoading = false,
  713. usage = USAGE_OPTION.ENCIPHERMENT,
  714. buildChain = false,
  715. ) {
  716. super();
  717. this.useFile = useFile;
  718. this.certFile = certificateFile;
  719. this.keyFile = keyFile;
  720. this.cert = Array.isArray(certificate) ? certificate.join('\n') : certificate;
  721. this.key = Array.isArray(key) ? key.join('\n') : key;
  722. this.oneTimeLoading = oneTimeLoading;
  723. this.usage = usage;
  724. this.buildChain = buildChain
  725. }
  726. static fromJson(json = {}) {
  727. if ('certificateFile' in json && 'keyFile' in json) {
  728. return new TlsStreamSettings.Cert(
  729. true,
  730. json.certificateFile,
  731. json.keyFile, '', '',
  732. json.oneTimeLoading,
  733. json.usage,
  734. json.buildChain,
  735. );
  736. } else {
  737. return new TlsStreamSettings.Cert(
  738. false, '', '',
  739. json.certificate.join('\n'),
  740. json.key.join('\n'),
  741. json.oneTimeLoading,
  742. json.usage,
  743. json.buildChain,
  744. );
  745. }
  746. }
  747. toJson() {
  748. if (this.useFile) {
  749. return {
  750. certificateFile: this.certFile,
  751. keyFile: this.keyFile,
  752. oneTimeLoading: this.oneTimeLoading,
  753. usage: this.usage,
  754. buildChain: this.buildChain,
  755. };
  756. } else {
  757. return {
  758. certificate: this.cert.split('\n'),
  759. key: this.key.split('\n'),
  760. oneTimeLoading: this.oneTimeLoading,
  761. usage: this.usage,
  762. buildChain: this.buildChain,
  763. };
  764. }
  765. }
  766. };
  767. TlsStreamSettings.Settings = class extends XrayCommonClass {
  768. constructor(
  769. fingerprint = UTLS_FINGERPRINT.UTLS_CHROME,
  770. echConfigList = '',
  771. ) {
  772. super();
  773. this.fingerprint = fingerprint;
  774. this.echConfigList = echConfigList;
  775. }
  776. static fromJson(json = {}) {
  777. return new TlsStreamSettings.Settings(
  778. json.fingerprint,
  779. json.echConfigList,
  780. );
  781. }
  782. toJson() {
  783. return {
  784. fingerprint: this.fingerprint,
  785. echConfigList: this.echConfigList
  786. };
  787. }
  788. };
  789. class RealityStreamSettings extends XrayCommonClass {
  790. constructor(
  791. show = false,
  792. xver = 0,
  793. target = '',
  794. serverNames = '',
  795. privateKey = '',
  796. minClientVer = '',
  797. maxClientVer = '',
  798. maxTimediff = 0,
  799. shortIds = RandomUtil.randomShortIds(),
  800. mldsa65Seed = '',
  801. settings = new RealityStreamSettings.Settings()
  802. ) {
  803. super();
  804. // If target/serverNames are not provided, use random values
  805. if (!target && !serverNames) {
  806. const randomTarget = typeof getRandomRealityTarget !== 'undefined'
  807. ? getRandomRealityTarget()
  808. : { target: 'www.amazon.com:443', sni: 'www.amazon.com,amazon.com' };
  809. target = randomTarget.target;
  810. serverNames = randomTarget.sni;
  811. }
  812. this.show = show;
  813. this.xver = xver;
  814. this.target = target;
  815. this.serverNames = Array.isArray(serverNames) ? serverNames.join(",") : serverNames;
  816. this.privateKey = privateKey;
  817. this.minClientVer = minClientVer;
  818. this.maxClientVer = maxClientVer;
  819. this.maxTimediff = maxTimediff;
  820. this.shortIds = Array.isArray(shortIds) ? shortIds.join(",") : shortIds;
  821. this.mldsa65Seed = mldsa65Seed;
  822. this.settings = settings;
  823. }
  824. static fromJson(json = {}) {
  825. let settings;
  826. if (!ObjectUtil.isEmpty(json.settings)) {
  827. settings = new RealityStreamSettings.Settings(
  828. json.settings.publicKey,
  829. json.settings.fingerprint,
  830. json.settings.serverName,
  831. json.settings.spiderX,
  832. json.settings.mldsa65Verify,
  833. );
  834. }
  835. return new RealityStreamSettings(
  836. json.show,
  837. json.xver,
  838. json.target,
  839. json.serverNames,
  840. json.privateKey,
  841. json.minClientVer,
  842. json.maxClientVer,
  843. json.maxTimediff,
  844. json.shortIds,
  845. json.mldsa65Seed,
  846. settings,
  847. );
  848. }
  849. toJson() {
  850. return {
  851. show: this.show,
  852. xver: this.xver,
  853. target: this.target,
  854. serverNames: this.serverNames.split(","),
  855. privateKey: this.privateKey,
  856. minClientVer: this.minClientVer,
  857. maxClientVer: this.maxClientVer,
  858. maxTimediff: this.maxTimediff,
  859. shortIds: this.shortIds.split(","),
  860. mldsa65Seed: this.mldsa65Seed,
  861. settings: this.settings,
  862. };
  863. }
  864. }
  865. RealityStreamSettings.Settings = class extends XrayCommonClass {
  866. constructor(
  867. publicKey = '',
  868. fingerprint = UTLS_FINGERPRINT.UTLS_CHROME,
  869. serverName = '',
  870. spiderX = '/',
  871. mldsa65Verify = ''
  872. ) {
  873. super();
  874. this.publicKey = publicKey;
  875. this.fingerprint = fingerprint;
  876. this.serverName = serverName;
  877. this.spiderX = spiderX;
  878. this.mldsa65Verify = mldsa65Verify;
  879. }
  880. static fromJson(json = {}) {
  881. return new RealityStreamSettings.Settings(
  882. json.publicKey,
  883. json.fingerprint,
  884. json.serverName,
  885. json.spiderX,
  886. json.mldsa65Verify
  887. );
  888. }
  889. toJson() {
  890. return {
  891. publicKey: this.publicKey,
  892. fingerprint: this.fingerprint,
  893. serverName: this.serverName,
  894. spiderX: this.spiderX,
  895. mldsa65Verify: this.mldsa65Verify
  896. };
  897. }
  898. };
  899. class SockoptStreamSettings extends XrayCommonClass {
  900. constructor(
  901. acceptProxyProtocol = false,
  902. tcpFastOpen = false,
  903. mark = 0,
  904. tproxy = "off",
  905. tcpMptcp = false,
  906. penetrate = false,
  907. domainStrategy = DOMAIN_STRATEGY_OPTION.USE_IP,
  908. tcpMaxSeg = 1440,
  909. dialerProxy = "",
  910. tcpKeepAliveInterval = 0,
  911. tcpKeepAliveIdle = 300,
  912. tcpUserTimeout = 10000,
  913. tcpcongestion = TCP_CONGESTION_OPTION.BBR,
  914. V6Only = false,
  915. tcpWindowClamp = 600,
  916. interfaceName = "",
  917. trustedXForwardedFor = [],
  918. ) {
  919. super();
  920. this.acceptProxyProtocol = acceptProxyProtocol;
  921. this.tcpFastOpen = tcpFastOpen;
  922. this.mark = mark;
  923. this.tproxy = tproxy;
  924. this.tcpMptcp = tcpMptcp;
  925. this.penetrate = penetrate;
  926. this.domainStrategy = domainStrategy;
  927. this.tcpMaxSeg = tcpMaxSeg;
  928. this.dialerProxy = dialerProxy;
  929. this.tcpKeepAliveInterval = tcpKeepAliveInterval;
  930. this.tcpKeepAliveIdle = tcpKeepAliveIdle;
  931. this.tcpUserTimeout = tcpUserTimeout;
  932. this.tcpcongestion = tcpcongestion;
  933. this.V6Only = V6Only;
  934. this.tcpWindowClamp = tcpWindowClamp;
  935. this.interfaceName = interfaceName;
  936. this.trustedXForwardedFor = trustedXForwardedFor;
  937. }
  938. static fromJson(json = {}) {
  939. if (Object.keys(json).length === 0) return undefined;
  940. return new SockoptStreamSettings(
  941. json.acceptProxyProtocol,
  942. json.tcpFastOpen,
  943. json.mark,
  944. json.tproxy,
  945. json.tcpMptcp,
  946. json.penetrate,
  947. json.domainStrategy,
  948. json.tcpMaxSeg,
  949. json.dialerProxy,
  950. json.tcpKeepAliveInterval,
  951. json.tcpKeepAliveIdle,
  952. json.tcpUserTimeout,
  953. json.tcpcongestion,
  954. json.V6Only,
  955. json.tcpWindowClamp,
  956. json.interface,
  957. json.trustedXForwardedFor || [],
  958. );
  959. }
  960. toJson() {
  961. const result = {
  962. acceptProxyProtocol: this.acceptProxyProtocol,
  963. tcpFastOpen: this.tcpFastOpen,
  964. mark: this.mark,
  965. tproxy: this.tproxy,
  966. tcpMptcp: this.tcpMptcp,
  967. penetrate: this.penetrate,
  968. domainStrategy: this.domainStrategy,
  969. tcpMaxSeg: this.tcpMaxSeg,
  970. dialerProxy: this.dialerProxy,
  971. tcpKeepAliveInterval: this.tcpKeepAliveInterval,
  972. tcpKeepAliveIdle: this.tcpKeepAliveIdle,
  973. tcpUserTimeout: this.tcpUserTimeout,
  974. tcpcongestion: this.tcpcongestion,
  975. V6Only: this.V6Only,
  976. tcpWindowClamp: this.tcpWindowClamp,
  977. interface: this.interfaceName,
  978. };
  979. if (this.trustedXForwardedFor && this.trustedXForwardedFor.length > 0) {
  980. result.trustedXForwardedFor = this.trustedXForwardedFor;
  981. }
  982. return result;
  983. }
  984. }
  985. class UdpMask extends XrayCommonClass {
  986. constructor(type = 'salamander', settings = {}) {
  987. super();
  988. this.type = type;
  989. this.settings = this._getDefaultSettings(type, settings);
  990. }
  991. _getDefaultSettings(type, settings = {}) {
  992. switch (type) {
  993. case 'salamander':
  994. case 'mkcp-aes128gcm':
  995. return { password: settings.password || '' };
  996. case 'header-dns':
  997. return { domain: settings.domain || '' };
  998. case 'xdns':
  999. return { domains: Array.isArray(settings.domains) ? settings.domains : [] };
  1000. case 'xicmp':
  1001. return { ip: settings.ip || '', id: settings.id ?? 0 };
  1002. case 'mkcp-original':
  1003. case 'header-dtls':
  1004. case 'header-srtp':
  1005. case 'header-utp':
  1006. case 'header-wechat':
  1007. case 'header-wireguard':
  1008. return {};
  1009. case 'header-custom':
  1010. return {
  1011. client: Array.isArray(settings.client) ? settings.client : [],
  1012. server: Array.isArray(settings.server) ? settings.server : [],
  1013. };
  1014. case 'noise':
  1015. return {
  1016. reset: settings.reset ?? 0,
  1017. noise: Array.isArray(settings.noise) ? settings.noise : [],
  1018. };
  1019. default:
  1020. return settings;
  1021. }
  1022. }
  1023. static fromJson(json = {}) {
  1024. return new UdpMask(
  1025. json.type || 'salamander',
  1026. json.settings || {}
  1027. );
  1028. }
  1029. toJson() {
  1030. const cleanItem = item => {
  1031. const out = { ...item };
  1032. if (out.type === 'array') {
  1033. delete out.packet;
  1034. } else {
  1035. delete out.rand;
  1036. delete out.randRange;
  1037. }
  1038. return out;
  1039. };
  1040. let settings = this.settings;
  1041. if (this.type === 'noise' && settings && Array.isArray(settings.noise)) {
  1042. settings = { ...settings, noise: settings.noise.map(cleanItem) };
  1043. } else if (this.type === 'header-custom' && settings) {
  1044. settings = {
  1045. ...settings,
  1046. client: Array.isArray(settings.client) ? settings.client.map(cleanItem) : settings.client,
  1047. server: Array.isArray(settings.server) ? settings.server.map(cleanItem) : settings.server,
  1048. };
  1049. }
  1050. return {
  1051. type: this.type,
  1052. settings: (settings && Object.keys(settings).length > 0) ? settings : undefined
  1053. };
  1054. }
  1055. }
  1056. class TcpMask extends XrayCommonClass {
  1057. constructor(type = 'fragment', settings = {}) {
  1058. super();
  1059. this.type = type;
  1060. this.settings = this._getDefaultSettings(type, settings);
  1061. }
  1062. _getDefaultSettings(type, settings = {}) {
  1063. switch (type) {
  1064. case 'fragment':
  1065. return {
  1066. packets: settings.packets ?? 'tlshello',
  1067. length: settings.length ?? '',
  1068. delay: settings.delay ?? '',
  1069. maxSplit: settings.maxSplit ?? '',
  1070. };
  1071. case 'sudoku':
  1072. return {
  1073. password: settings.password ?? '',
  1074. ascii: settings.ascii ?? '',
  1075. customTable: settings.customTable ?? '',
  1076. customTables: Array.isArray(settings.customTables) ? settings.customTables : [],
  1077. paddingMin: settings.paddingMin ?? 0,
  1078. paddingMax: settings.paddingMax ?? 0,
  1079. };
  1080. case 'header-custom':
  1081. return {
  1082. clients: Array.isArray(settings.clients) ? settings.clients : [],
  1083. servers: Array.isArray(settings.servers) ? settings.servers : [],
  1084. };
  1085. default:
  1086. return settings;
  1087. }
  1088. }
  1089. static fromJson(json = {}) {
  1090. return new TcpMask(
  1091. json.type || 'fragment',
  1092. json.settings || {}
  1093. );
  1094. }
  1095. toJson() {
  1096. const cleanItem = item => {
  1097. const out = { ...item };
  1098. if (out.type === 'array') {
  1099. delete out.packet;
  1100. } else {
  1101. delete out.rand;
  1102. delete out.randRange;
  1103. }
  1104. return out;
  1105. };
  1106. let settings = this.settings;
  1107. if (this.type === 'header-custom' && settings) {
  1108. const cleanGroup = group => Array.isArray(group) ? group.map(cleanItem) : group;
  1109. settings = {
  1110. ...settings,
  1111. clients: Array.isArray(settings.clients) ? settings.clients.map(cleanGroup) : settings.clients,
  1112. servers: Array.isArray(settings.servers) ? settings.servers.map(cleanGroup) : settings.servers,
  1113. };
  1114. }
  1115. return {
  1116. type: this.type,
  1117. settings: (settings && Object.keys(settings).length > 0) ? settings : undefined
  1118. };
  1119. }
  1120. }
  1121. class QuicParams extends XrayCommonClass {
  1122. constructor(
  1123. congestion = 'bbr',
  1124. debug = false,
  1125. brutalUp = 65537,
  1126. brutalDown = 65537,
  1127. udpHop = undefined,
  1128. initStreamReceiveWindow = 8388608,
  1129. maxStreamReceiveWindow = 8388608,
  1130. initConnectionReceiveWindow = 20971520,
  1131. maxConnectionReceiveWindow = 20971520,
  1132. maxIdleTimeout = 30,
  1133. keepAlivePeriod = 5,
  1134. disablePathMTUDiscovery = false,
  1135. maxIncomingStreams = 1024,
  1136. ) {
  1137. super();
  1138. this.congestion = congestion;
  1139. this.debug = debug;
  1140. this.brutalUp = brutalUp;
  1141. this.brutalDown = brutalDown;
  1142. this.udpHop = udpHop;
  1143. this.initStreamReceiveWindow = initStreamReceiveWindow;
  1144. this.maxStreamReceiveWindow = maxStreamReceiveWindow;
  1145. this.initConnectionReceiveWindow = initConnectionReceiveWindow;
  1146. this.maxConnectionReceiveWindow = maxConnectionReceiveWindow;
  1147. this.maxIdleTimeout = maxIdleTimeout;
  1148. this.keepAlivePeriod = keepAlivePeriod;
  1149. this.disablePathMTUDiscovery = disablePathMTUDiscovery;
  1150. this.maxIncomingStreams = maxIncomingStreams;
  1151. }
  1152. get hasUdpHop() {
  1153. return this.udpHop != null;
  1154. }
  1155. set hasUdpHop(value) {
  1156. this.udpHop = value ? (this.udpHop || { ports: '20000-50000', interval: '5-10' }) : undefined;
  1157. }
  1158. static fromJson(json = {}) {
  1159. if (!json || Object.keys(json).length === 0) return undefined;
  1160. return new QuicParams(
  1161. json.congestion,
  1162. json.debug,
  1163. json.brutalUp,
  1164. json.brutalDown,
  1165. json.udpHop ? { ports: json.udpHop.ports, interval: json.udpHop.interval } : undefined,
  1166. json.initStreamReceiveWindow,
  1167. json.maxStreamReceiveWindow,
  1168. json.initConnectionReceiveWindow,
  1169. json.maxConnectionReceiveWindow,
  1170. json.maxIdleTimeout,
  1171. json.keepAlivePeriod,
  1172. json.disablePathMTUDiscovery,
  1173. json.maxIncomingStreams,
  1174. );
  1175. }
  1176. toJson() {
  1177. const result = { congestion: this.congestion };
  1178. if (this.debug) result.debug = this.debug;
  1179. if (['brutal', 'force-brutal'].includes(this.congestion)) {
  1180. if (this.brutalUp) result.brutalUp = this.brutalUp;
  1181. if (this.brutalDown) result.brutalDown = this.brutalDown;
  1182. }
  1183. if (this.udpHop) result.udpHop = { ports: this.udpHop.ports, interval: this.udpHop.interval };
  1184. if (this.initStreamReceiveWindow > 0) result.initStreamReceiveWindow = this.initStreamReceiveWindow;
  1185. if (this.maxStreamReceiveWindow > 0) result.maxStreamReceiveWindow = this.maxStreamReceiveWindow;
  1186. if (this.initConnectionReceiveWindow > 0) result.initConnectionReceiveWindow = this.initConnectionReceiveWindow;
  1187. if (this.maxConnectionReceiveWindow > 0) result.maxConnectionReceiveWindow = this.maxConnectionReceiveWindow;
  1188. if (this.maxIdleTimeout !== 30 && this.maxIdleTimeout > 0) result.maxIdleTimeout = this.maxIdleTimeout;
  1189. if (this.keepAlivePeriod > 0) result.keepAlivePeriod = this.keepAlivePeriod;
  1190. if (this.disablePathMTUDiscovery) result.disablePathMTUDiscovery = this.disablePathMTUDiscovery;
  1191. if (this.maxIncomingStreams > 0) result.maxIncomingStreams = this.maxIncomingStreams;
  1192. return result;
  1193. }
  1194. }
  1195. class FinalMaskStreamSettings extends XrayCommonClass {
  1196. constructor(tcp = [], udp = [], quicParams = undefined) {
  1197. super();
  1198. this.tcp = Array.isArray(tcp) ? tcp.map(t => t instanceof TcpMask ? t : new TcpMask(t.type, t.settings)) : [];
  1199. this.udp = Array.isArray(udp) ? udp.map(u => new UdpMask(u.type, u.settings)) : [new UdpMask(udp.type, udp.settings)];
  1200. this.quicParams = quicParams instanceof QuicParams ? quicParams : (quicParams ? QuicParams.fromJson(quicParams) : undefined);
  1201. }
  1202. get enableQuicParams() {
  1203. return this.quicParams != null;
  1204. }
  1205. set enableQuicParams(value) {
  1206. this.quicParams = value ? (this.quicParams || new QuicParams()) : undefined;
  1207. }
  1208. static fromJson(json = {}) {
  1209. return new FinalMaskStreamSettings(
  1210. json.tcp || [],
  1211. json.udp || [],
  1212. json.quicParams ? QuicParams.fromJson(json.quicParams) : undefined,
  1213. );
  1214. }
  1215. toJson() {
  1216. const result = {};
  1217. if (this.tcp && this.tcp.length > 0) {
  1218. result.tcp = this.tcp.map(t => t.toJson());
  1219. }
  1220. if (this.udp && this.udp.length > 0) {
  1221. result.udp = this.udp.map(udp => udp.toJson());
  1222. }
  1223. if (this.quicParams) {
  1224. result.quicParams = this.quicParams.toJson();
  1225. }
  1226. return result;
  1227. }
  1228. }
  1229. class StreamSettings extends XrayCommonClass {
  1230. constructor(network = 'tcp',
  1231. security = 'none',
  1232. externalProxy = [],
  1233. tlsSettings = new TlsStreamSettings(),
  1234. realitySettings = new RealityStreamSettings(),
  1235. tcpSettings = new TcpStreamSettings(),
  1236. kcpSettings = new KcpStreamSettings(),
  1237. wsSettings = new WsStreamSettings(),
  1238. grpcSettings = new GrpcStreamSettings(),
  1239. httpupgradeSettings = new HTTPUpgradeStreamSettings(),
  1240. xhttpSettings = new xHTTPStreamSettings(),
  1241. hysteriaSettings = new HysteriaStreamSettings(),
  1242. finalmask = new FinalMaskStreamSettings(),
  1243. sockopt = undefined,
  1244. ) {
  1245. super();
  1246. this.network = network;
  1247. this.security = security;
  1248. this.externalProxy = externalProxy;
  1249. this.tls = tlsSettings;
  1250. this.reality = realitySettings;
  1251. this.tcp = tcpSettings;
  1252. this.kcp = kcpSettings;
  1253. this.ws = wsSettings;
  1254. this.grpc = grpcSettings;
  1255. this.httpupgrade = httpupgradeSettings;
  1256. this.xhttp = xhttpSettings;
  1257. this.hysteria = hysteriaSettings;
  1258. this.finalmask = finalmask;
  1259. this.sockopt = sockopt;
  1260. }
  1261. addTcpMask(type = 'fragment') {
  1262. this.finalmask.tcp.push(new TcpMask(type));
  1263. }
  1264. delTcpMask(index) {
  1265. if (this.finalmask.tcp) {
  1266. this.finalmask.tcp.splice(index, 1);
  1267. }
  1268. }
  1269. addUdpMask(type = 'salamander') {
  1270. this.finalmask.udp.push(new UdpMask(type));
  1271. }
  1272. delUdpMask(index) {
  1273. if (this.finalmask.udp) {
  1274. this.finalmask.udp.splice(index, 1);
  1275. }
  1276. }
  1277. get hasFinalMask() {
  1278. const hasTcp = this.finalmask.tcp && this.finalmask.tcp.length > 0;
  1279. const hasUdp = this.finalmask.udp && this.finalmask.udp.length > 0;
  1280. const hasQuicParams = this.finalmask.quicParams != null;
  1281. return hasTcp || hasUdp || hasQuicParams;
  1282. }
  1283. get isTls() {
  1284. return this.security === "tls";
  1285. }
  1286. set isTls(isTls) {
  1287. if (isTls) {
  1288. this.security = 'tls';
  1289. } else {
  1290. this.security = 'none';
  1291. }
  1292. }
  1293. //for Reality
  1294. get isReality() {
  1295. return this.security === "reality";
  1296. }
  1297. set isReality(isReality) {
  1298. if (isReality) {
  1299. this.security = 'reality';
  1300. } else {
  1301. this.security = 'none';
  1302. }
  1303. }
  1304. get sockoptSwitch() {
  1305. return this.sockopt != undefined;
  1306. }
  1307. set sockoptSwitch(value) {
  1308. this.sockopt = value ? new SockoptStreamSettings() : undefined;
  1309. }
  1310. static fromJson(json = {}) {
  1311. return new StreamSettings(
  1312. json.network,
  1313. json.security,
  1314. json.externalProxy,
  1315. TlsStreamSettings.fromJson(json.tlsSettings),
  1316. RealityStreamSettings.fromJson(json.realitySettings),
  1317. TcpStreamSettings.fromJson(json.tcpSettings),
  1318. KcpStreamSettings.fromJson(json.kcpSettings),
  1319. WsStreamSettings.fromJson(json.wsSettings),
  1320. GrpcStreamSettings.fromJson(json.grpcSettings),
  1321. HTTPUpgradeStreamSettings.fromJson(json.httpupgradeSettings),
  1322. xHTTPStreamSettings.fromJson(json.xhttpSettings),
  1323. HysteriaStreamSettings.fromJson(json.hysteriaSettings),
  1324. FinalMaskStreamSettings.fromJson(json.finalmask),
  1325. SockoptStreamSettings.fromJson(json.sockopt),
  1326. );
  1327. }
  1328. toJson() {
  1329. const network = this.network;
  1330. return {
  1331. network: network,
  1332. security: this.security,
  1333. externalProxy: this.externalProxy,
  1334. tlsSettings: this.isTls ? this.tls.toJson() : undefined,
  1335. realitySettings: this.isReality ? this.reality.toJson() : undefined,
  1336. tcpSettings: network === 'tcp' ? this.tcp.toJson() : undefined,
  1337. kcpSettings: network === 'kcp' ? this.kcp.toJson() : undefined,
  1338. wsSettings: network === 'ws' ? this.ws.toJson() : undefined,
  1339. grpcSettings: network === 'grpc' ? this.grpc.toJson() : undefined,
  1340. httpupgradeSettings: network === 'httpupgrade' ? this.httpupgrade.toJson() : undefined,
  1341. xhttpSettings: network === 'xhttp' ? this.xhttp.toJson() : undefined,
  1342. hysteriaSettings: network === 'hysteria' ? this.hysteria.toJson() : undefined,
  1343. finalmask: this.hasFinalMask ? this.finalmask.toJson() : undefined,
  1344. sockopt: this.sockopt != undefined ? this.sockopt.toJson() : undefined,
  1345. };
  1346. }
  1347. }
  1348. class Sniffing extends XrayCommonClass {
  1349. constructor(
  1350. enabled = false,
  1351. destOverride = ['http', 'tls', 'quic', 'fakedns'],
  1352. metadataOnly = false,
  1353. routeOnly = false,
  1354. ipsExcluded = [],
  1355. domainsExcluded = []) {
  1356. super();
  1357. this.enabled = enabled;
  1358. this.destOverride = Array.isArray(destOverride) && destOverride.length > 0 ? destOverride : ['http', 'tls', 'quic', 'fakedns'];
  1359. this.metadataOnly = metadataOnly;
  1360. this.routeOnly = routeOnly;
  1361. this.ipsExcluded = Array.isArray(ipsExcluded) ? ipsExcluded : [];
  1362. this.domainsExcluded = Array.isArray(domainsExcluded) ? domainsExcluded : [];
  1363. }
  1364. static fromJson(json = {}) {
  1365. let destOverride = ObjectUtil.clone(json.destOverride);
  1366. if (ObjectUtil.isEmpty(destOverride) || ObjectUtil.isArrEmpty(destOverride) || ObjectUtil.isEmpty(destOverride[0])) {
  1367. destOverride = ['http', 'tls', 'quic', 'fakedns'];
  1368. }
  1369. return new Sniffing(
  1370. !!json.enabled,
  1371. destOverride,
  1372. json.metadataOnly,
  1373. json.routeOnly,
  1374. json.ipsExcluded || [],
  1375. json.domainsExcluded || [],
  1376. );
  1377. }
  1378. toJson() {
  1379. return {
  1380. enabled: this.enabled,
  1381. destOverride: this.destOverride,
  1382. metadataOnly: this.metadataOnly,
  1383. routeOnly: this.routeOnly,
  1384. ipsExcluded: this.ipsExcluded.length > 0 ? this.ipsExcluded : undefined,
  1385. domainsExcluded: this.domainsExcluded.length > 0 ? this.domainsExcluded : undefined,
  1386. };
  1387. }
  1388. }
  1389. class Inbound extends XrayCommonClass {
  1390. constructor(
  1391. port = RandomUtil.randomInteger(10000, 60000),
  1392. listen = '',
  1393. protocol = Protocols.VLESS,
  1394. settings = null,
  1395. streamSettings = new StreamSettings(),
  1396. tag = '',
  1397. sniffing = new Sniffing(),
  1398. clientStats = '',
  1399. ) {
  1400. super();
  1401. this.port = port;
  1402. this.listen = listen;
  1403. this._protocol = protocol;
  1404. this.settings = ObjectUtil.isEmpty(settings) ? Inbound.Settings.getSettings(protocol) : settings;
  1405. this.stream = streamSettings;
  1406. this.tag = tag;
  1407. this.sniffing = sniffing;
  1408. this.clientStats = clientStats;
  1409. }
  1410. getClientStats() {
  1411. return this.clientStats;
  1412. }
  1413. // Looks for a "host"-named entry in xhttp.headers and returns its value,
  1414. // or '' if not found. Used as a fallback when xhttp.host is empty so the
  1415. // share URL still carries a usable Host hint.
  1416. static xhttpHostFallback(xhttp) {
  1417. if (!xhttp || !Array.isArray(xhttp.headers)) return '';
  1418. for (const h of xhttp.headers) {
  1419. if (h && typeof h.name === 'string' && h.name.toLowerCase() === 'host') {
  1420. return h.value || '';
  1421. }
  1422. }
  1423. return '';
  1424. }
  1425. // Build the JSON blob that goes into the URL's `extra` param (or, for
  1426. // VMess, into the base64-encoded link object). Carries ONLY the
  1427. // bidirectional fields from xray-core's SplitHTTPConfig — i.e. the
  1428. // ones the server enforces and the client must match. Strictly
  1429. // one-sided fields are excluded:
  1430. //
  1431. // - server-only (noSSEHeader, scMaxBufferedPosts,
  1432. // scStreamUpServerSecs, serverMaxHeaderBytes) — client wouldn't
  1433. // read them, so emitting them just bloats the URL.
  1434. // - client-only (headers, uplinkHTTPMethod, uplinkChunkSize,
  1435. // noGRPCHeader, scMinPostsIntervalMs, xmux, downloadSettings) —
  1436. // not on the inbound class at all; the client configures them
  1437. // locally.
  1438. //
  1439. // Truthy-only guards keep default inbounds emitting the same compact
  1440. // URL they did before this helper grew.
  1441. static buildXhttpExtra(xhttp) {
  1442. if (!xhttp) return null;
  1443. const extra = {};
  1444. if (typeof xhttp.xPaddingBytes === 'string' && xhttp.xPaddingBytes.length > 0) {
  1445. extra.xPaddingBytes = xhttp.xPaddingBytes;
  1446. }
  1447. if (xhttp.xPaddingObfsMode === true) {
  1448. extra.xPaddingObfsMode = true;
  1449. ["xPaddingKey", "xPaddingHeader", "xPaddingPlacement", "xPaddingMethod"].forEach(k => {
  1450. if (typeof xhttp[k] === 'string' && xhttp[k].length > 0) {
  1451. extra[k] = xhttp[k];
  1452. }
  1453. });
  1454. }
  1455. const stringFields = [
  1456. "sessionPlacement", "sessionKey",
  1457. "seqPlacement", "seqKey",
  1458. "uplinkDataPlacement", "uplinkDataKey",
  1459. "scMaxEachPostBytes",
  1460. ];
  1461. for (const k of stringFields) {
  1462. const v = xhttp[k];
  1463. if (typeof v === 'string' && v.length > 0) extra[k] = v;
  1464. }
  1465. // Headers — emitted as the {name: value} map upstream's struct
  1466. // expects. The server runtime ignores this field, but the client
  1467. // (consuming the share link) honors it.
  1468. if (Array.isArray(xhttp.headers) && xhttp.headers.length > 0) {
  1469. const headersMap = {};
  1470. for (const h of xhttp.headers) {
  1471. if (h && h.name && h.name.toLowerCase() !== 'host') {
  1472. headersMap[h.name] = h.value || '';
  1473. }
  1474. }
  1475. if (Object.keys(headersMap).length > 0) extra.headers = headersMap;
  1476. }
  1477. return Object.keys(extra).length > 0 ? extra : null;
  1478. }
  1479. // Inject the inbound-side xhttp config into URL query params for
  1480. // vless/trojan/ss links. Sets path/host/mode at top level (xray's
  1481. // Build() always lets these win over `extra`) and packs the
  1482. // bidirectional fields into a JSON `extra` param. Also writes the
  1483. // flat `x_padding_bytes` param sing-box-family clients understand.
  1484. //
  1485. // Without this, the admin's custom xPaddingBytes / sessionKey / etc.
  1486. // never reach the client and handshakes are silently rejected with
  1487. // `invalid padding (...) length: 0`.
  1488. static applyXhttpExtraToParams(xhttp, params) {
  1489. if (!xhttp) return;
  1490. params.set("path", xhttp.path);
  1491. const host = xhttp.host?.length > 0 ? xhttp.host : Inbound.xhttpHostFallback(xhttp);
  1492. params.set("host", host);
  1493. params.set("mode", xhttp.mode);
  1494. // Flat fallback for sing-box-family clients that don't read `extra`.
  1495. if (typeof xhttp.xPaddingBytes === 'string' && xhttp.xPaddingBytes.length > 0) {
  1496. params.set("x_padding_bytes", xhttp.xPaddingBytes);
  1497. }
  1498. const extra = Inbound.buildXhttpExtra(xhttp);
  1499. if (extra) params.set("extra", JSON.stringify(extra));
  1500. }
  1501. // VMess variant: VMess links are a base64-encoded JSON object, so we
  1502. // copy the same bidirectional fields directly into the JSON instead
  1503. // of building a query string. (The base VMess link generator already
  1504. // sets net/type/path/host, so we only contribute the SplitHTTPConfig
  1505. // extra side here.)
  1506. static applyXhttpExtraToObj(xhttp, obj) {
  1507. if (!xhttp || !obj) return;
  1508. if (typeof xhttp.xPaddingBytes === 'string' && xhttp.xPaddingBytes.length > 0) {
  1509. obj.x_padding_bytes = xhttp.xPaddingBytes;
  1510. }
  1511. const extra = Inbound.buildXhttpExtra(xhttp);
  1512. if (!extra) return;
  1513. for (const [k, v] of Object.entries(extra)) {
  1514. obj[k] = v;
  1515. }
  1516. }
  1517. static hasShareableFinalMaskValue(value) {
  1518. if (value == null) {
  1519. return false;
  1520. }
  1521. if (Array.isArray(value)) {
  1522. return value.some(item => Inbound.hasShareableFinalMaskValue(item));
  1523. }
  1524. if (typeof value === 'object') {
  1525. return Object.values(value).some(item => Inbound.hasShareableFinalMaskValue(item));
  1526. }
  1527. if (typeof value === 'string') {
  1528. return value.length > 0;
  1529. }
  1530. return true;
  1531. }
  1532. static serializeFinalMask(finalmask) {
  1533. if (!finalmask) {
  1534. return '';
  1535. }
  1536. const value = typeof finalmask.toJson === 'function' ? finalmask.toJson() : finalmask;
  1537. return Inbound.hasShareableFinalMaskValue(value) ? JSON.stringify(value) : '';
  1538. }
  1539. // Export finalmask with the same compact JSON payload shape that
  1540. // v2rayN-compatible share links use: fm=<json>.
  1541. static applyFinalMaskToParams(finalmask, params) {
  1542. if (!params) return;
  1543. const payload = Inbound.serializeFinalMask(finalmask);
  1544. if (payload.length > 0) {
  1545. params.set("fm", payload);
  1546. }
  1547. }
  1548. // VMess links are a base64 JSON object, so keep the same fm payload
  1549. // under a flat property instead of a URL query string.
  1550. static applyFinalMaskToObj(finalmask, obj) {
  1551. if (!obj) return;
  1552. const payload = Inbound.serializeFinalMask(finalmask);
  1553. if (payload.length > 0) {
  1554. obj.fm = payload;
  1555. }
  1556. }
  1557. get clients() {
  1558. switch (this.protocol) {
  1559. case Protocols.VMESS: return this.settings.vmesses;
  1560. case Protocols.VLESS: return this.settings.vlesses;
  1561. case Protocols.TROJAN: return this.settings.trojans;
  1562. case Protocols.SHADOWSOCKS: return this.isSSMultiUser ? this.settings.shadowsockses : null;
  1563. case Protocols.HYSTERIA: return this.settings.hysterias;
  1564. default: return null;
  1565. }
  1566. }
  1567. get protocol() {
  1568. return this._protocol;
  1569. }
  1570. set protocol(protocol) {
  1571. this._protocol = protocol;
  1572. this.settings = Inbound.Settings.getSettings(protocol);
  1573. this.stream = new StreamSettings();
  1574. if (protocol === Protocols.TROJAN) {
  1575. this.tls = false;
  1576. }
  1577. if (protocol === Protocols.HYSTERIA) {
  1578. this.stream.network = 'hysteria';
  1579. this.stream.security = 'tls';
  1580. // Hysteria runs over QUIC and must not inherit TCP TLS ALPN defaults.
  1581. this.stream.tls.alpn = [ALPN_OPTION.H3];
  1582. }
  1583. }
  1584. get network() {
  1585. return this.stream.network;
  1586. }
  1587. set network(network) {
  1588. this.stream.network = network;
  1589. }
  1590. get isTcp() {
  1591. return this.network === "tcp";
  1592. }
  1593. get isWs() {
  1594. return this.network === "ws";
  1595. }
  1596. get isKcp() {
  1597. return this.network === "kcp";
  1598. }
  1599. get isGrpc() {
  1600. return this.network === "grpc";
  1601. }
  1602. get isHttpupgrade() {
  1603. return this.network === "httpupgrade";
  1604. }
  1605. get isXHTTP() {
  1606. return this.network === "xhttp";
  1607. }
  1608. // Shadowsocks
  1609. get method() {
  1610. switch (this.protocol) {
  1611. case Protocols.SHADOWSOCKS:
  1612. return this.settings.method;
  1613. default:
  1614. return "";
  1615. }
  1616. }
  1617. get isSSMultiUser() {
  1618. return this.method != SSMethods.BLAKE3_CHACHA20_POLY1305;
  1619. }
  1620. get isSS2022() {
  1621. return this.method.substring(0, 4) === "2022";
  1622. }
  1623. get serverName() {
  1624. if (this.stream.isTls) return this.stream.tls.sni;
  1625. if (this.stream.isReality) return this.stream.reality.serverNames;
  1626. return "";
  1627. }
  1628. getHeader(obj, name) {
  1629. for (const header of obj.headers) {
  1630. if (header.name.toLowerCase() === name.toLowerCase()) {
  1631. return header.value;
  1632. }
  1633. }
  1634. return "";
  1635. }
  1636. get host() {
  1637. if (this.isTcp) {
  1638. return this.getHeader(this.stream.tcp.request, 'host');
  1639. } else if (this.isWs) {
  1640. return this.stream.ws.host?.length > 0 ? this.stream.ws.host : this.getHeader(this.stream.ws, 'host');
  1641. } else if (this.isHttpupgrade) {
  1642. return this.stream.httpupgrade.host?.length > 0 ? this.stream.httpupgrade.host : this.getHeader(this.stream.httpupgrade, 'host');
  1643. } else if (this.isXHTTP) {
  1644. return this.stream.xhttp.host?.length > 0 ? this.stream.xhttp.host : this.getHeader(this.stream.xhttp, 'host');
  1645. }
  1646. return null;
  1647. }
  1648. get path() {
  1649. if (this.isTcp) {
  1650. return this.stream.tcp.request.path[0];
  1651. } else if (this.isWs) {
  1652. return this.stream.ws.path;
  1653. } else if (this.isHttpupgrade) {
  1654. return this.stream.httpupgrade.path;
  1655. } else if (this.isXHTTP) {
  1656. return this.stream.xhttp.path;
  1657. }
  1658. return null;
  1659. }
  1660. get serviceName() {
  1661. return this.stream.grpc.serviceName;
  1662. }
  1663. isExpiry(index) {
  1664. let exp = this.clients[index].expiryTime;
  1665. return exp > 0 ? exp < new Date().getTime() : false;
  1666. }
  1667. canEnableTls() {
  1668. if (this.protocol === Protocols.HYSTERIA) return true;
  1669. if (![Protocols.VMESS, Protocols.VLESS, Protocols.TROJAN, Protocols.SHADOWSOCKS].includes(this.protocol)) return false;
  1670. return ["tcp", "ws", "http", "grpc", "httpupgrade", "xhttp"].includes(this.network);
  1671. }
  1672. //this is used for xtls-rprx-vision
  1673. canEnableTlsFlow() {
  1674. if (((this.stream.security === 'tls') || (this.stream.security === 'reality')) && (this.network === "tcp")) {
  1675. return this.protocol === Protocols.VLESS;
  1676. }
  1677. return false;
  1678. }
  1679. // Vision seed applies only when the XTLS Vision (TCP/TLS) flow is selected.
  1680. // Excludes the UDP variant per spec.
  1681. canEnableVisionSeed() {
  1682. if (!this.canEnableTlsFlow()) return false;
  1683. const clients = this.settings?.vlesses;
  1684. if (!Array.isArray(clients)) return false;
  1685. return clients.some(c => c?.flow === TLS_FLOW_CONTROL.VISION);
  1686. }
  1687. canEnableReality() {
  1688. if (![Protocols.VLESS, Protocols.TROJAN].includes(this.protocol)) return false;
  1689. return ["tcp", "http", "grpc", "xhttp"].includes(this.network);
  1690. }
  1691. canEnableStream() {
  1692. return [Protocols.VMESS, Protocols.VLESS, Protocols.TROJAN, Protocols.SHADOWSOCKS, Protocols.HYSTERIA].includes(this.protocol);
  1693. }
  1694. reset() {
  1695. this.port = RandomUtil.randomInteger(10000, 60000);
  1696. this.listen = '';
  1697. this.protocol = Protocols.VMESS;
  1698. this.settings = Inbound.Settings.getSettings(Protocols.VMESS);
  1699. this.stream = new StreamSettings();
  1700. this.tag = '';
  1701. this.sniffing = new Sniffing();
  1702. }
  1703. genVmessLink(address = '', port = this.port, forceTls, remark = '', clientId, security) {
  1704. if (this.protocol !== Protocols.VMESS) {
  1705. return '';
  1706. }
  1707. const tls = forceTls == 'same' ? this.stream.security : forceTls;
  1708. let obj = {
  1709. v: '2',
  1710. ps: remark,
  1711. add: address,
  1712. port: port,
  1713. id: clientId,
  1714. scy: security,
  1715. net: this.stream.network,
  1716. tls: tls,
  1717. };
  1718. const network = this.stream.network;
  1719. if (network === 'tcp') {
  1720. const tcp = this.stream.tcp;
  1721. obj.type = tcp.type;
  1722. if (tcp.type === 'http') {
  1723. const request = tcp.request;
  1724. obj.path = request.path.join(',');
  1725. const host = this.getHeader(request, 'host');
  1726. if (host) obj.host = host;
  1727. }
  1728. } else if (network === 'kcp') {
  1729. const kcp = this.stream.kcp;
  1730. obj.mtu = kcp.mtu;
  1731. obj.tti = kcp.tti;
  1732. } else if (network === 'ws') {
  1733. const ws = this.stream.ws;
  1734. obj.path = ws.path;
  1735. obj.host = ws.host?.length > 0 ? ws.host : this.getHeader(ws, 'host');
  1736. } else if (network === 'grpc') {
  1737. obj.path = this.stream.grpc.serviceName;
  1738. obj.authority = this.stream.grpc.authority;
  1739. if (this.stream.grpc.multiMode) {
  1740. obj.type = 'multi'
  1741. }
  1742. } else if (network === 'httpupgrade') {
  1743. const httpupgrade = this.stream.httpupgrade;
  1744. obj.path = httpupgrade.path;
  1745. obj.host = httpupgrade.host?.length > 0 ? httpupgrade.host : this.getHeader(httpupgrade, 'host');
  1746. } else if (network === 'xhttp') {
  1747. const xhttp = this.stream.xhttp;
  1748. obj.path = xhttp.path;
  1749. obj.host = xhttp.host?.length > 0 ? xhttp.host : this.getHeader(xhttp, 'host');
  1750. obj.type = xhttp.mode;
  1751. Inbound.applyXhttpExtraToObj(xhttp, obj);
  1752. }
  1753. Inbound.applyFinalMaskToObj(this.stream.finalmask, obj);
  1754. if (tls === 'tls') {
  1755. if (!ObjectUtil.isEmpty(this.stream.tls.sni)) {
  1756. obj.sni = this.stream.tls.sni;
  1757. }
  1758. if (!ObjectUtil.isEmpty(this.stream.tls.settings.fingerprint)) {
  1759. obj.fp = this.stream.tls.settings.fingerprint;
  1760. }
  1761. if (this.stream.tls.alpn.length > 0) {
  1762. obj.alpn = this.stream.tls.alpn.join(',');
  1763. }
  1764. }
  1765. return 'vmess://' + Base64.encode(JSON.stringify(obj, null, 2));
  1766. }
  1767. genVLESSLink(address = '', port = this.port, forceTls, remark = '', clientId, flow) {
  1768. const uuid = clientId;
  1769. const type = this.stream.network;
  1770. const security = forceTls == 'same' ? this.stream.security : forceTls;
  1771. const params = new Map();
  1772. params.set("type", this.stream.network);
  1773. params.set("encryption", this.settings.encryption);
  1774. switch (type) {
  1775. case "tcp":
  1776. const tcp = this.stream.tcp;
  1777. if (tcp.type === 'http') {
  1778. const request = tcp.request;
  1779. params.set("path", request.path.join(','));
  1780. const index = request.headers.findIndex(header => header.name.toLowerCase() === 'host');
  1781. if (index >= 0) {
  1782. const host = request.headers[index].value;
  1783. params.set("host", host);
  1784. }
  1785. params.set("headerType", 'http');
  1786. }
  1787. break;
  1788. case "kcp":
  1789. const kcp = this.stream.kcp;
  1790. params.set("mtu", kcp.mtu);
  1791. params.set("tti", kcp.tti);
  1792. break;
  1793. case "ws":
  1794. const ws = this.stream.ws;
  1795. params.set("path", ws.path);
  1796. params.set("host", ws.host?.length > 0 ? ws.host : this.getHeader(ws, 'host'));
  1797. break;
  1798. case "grpc":
  1799. const grpc = this.stream.grpc;
  1800. params.set("serviceName", grpc.serviceName);
  1801. params.set("authority", grpc.authority);
  1802. if (grpc.multiMode) {
  1803. params.set("mode", "multi");
  1804. }
  1805. break;
  1806. case "httpupgrade":
  1807. const httpupgrade = this.stream.httpupgrade;
  1808. params.set("path", httpupgrade.path);
  1809. params.set("host", httpupgrade.host?.length > 0 ? httpupgrade.host : this.getHeader(httpupgrade, 'host'));
  1810. break;
  1811. case "xhttp":
  1812. Inbound.applyXhttpExtraToParams(this.stream.xhttp, params);
  1813. break;
  1814. }
  1815. Inbound.applyFinalMaskToParams(this.stream.finalmask, params);
  1816. if (security === 'tls') {
  1817. params.set("security", "tls");
  1818. if (this.stream.isTls) {
  1819. params.set("fp", this.stream.tls.settings.fingerprint);
  1820. params.set("alpn", this.stream.tls.alpn);
  1821. if (!ObjectUtil.isEmpty(this.stream.tls.sni)) {
  1822. params.set("sni", this.stream.tls.sni);
  1823. }
  1824. if (this.stream.tls.settings.echConfigList?.length > 0) {
  1825. params.set("ech", this.stream.tls.settings.echConfigList);
  1826. }
  1827. if (type == "tcp" && !ObjectUtil.isEmpty(flow)) {
  1828. params.set("flow", flow);
  1829. }
  1830. }
  1831. }
  1832. else if (security === 'reality') {
  1833. params.set("security", "reality");
  1834. params.set("pbk", this.stream.reality.settings.publicKey);
  1835. params.set("fp", this.stream.reality.settings.fingerprint);
  1836. if (!ObjectUtil.isArrEmpty(this.stream.reality.serverNames)) {
  1837. params.set("sni", this.stream.reality.serverNames.split(",")[0]);
  1838. }
  1839. if (this.stream.reality.shortIds.length > 0) {
  1840. params.set("sid", this.stream.reality.shortIds.split(",")[0]);
  1841. }
  1842. if (!ObjectUtil.isEmpty(this.stream.reality.settings.spiderX)) {
  1843. params.set("spx", this.stream.reality.settings.spiderX);
  1844. }
  1845. if (!ObjectUtil.isEmpty(this.stream.reality.settings.mldsa65Verify)) {
  1846. params.set("pqv", this.stream.reality.settings.mldsa65Verify);
  1847. }
  1848. if (type == 'tcp' && !ObjectUtil.isEmpty(flow)) {
  1849. params.set("flow", flow);
  1850. }
  1851. }
  1852. else {
  1853. params.set("security", "none");
  1854. }
  1855. const link = `vless://${uuid}@${address}:${port}`;
  1856. const url = new URL(link);
  1857. for (const [key, value] of params) {
  1858. url.searchParams.set(key, value)
  1859. }
  1860. url.hash = encodeURIComponent(remark);
  1861. return url.toString();
  1862. }
  1863. genSSLink(address = '', port = this.port, forceTls, remark = '', clientPassword) {
  1864. let settings = this.settings;
  1865. const type = this.stream.network;
  1866. const security = forceTls == 'same' ? this.stream.security : forceTls;
  1867. const params = new Map();
  1868. params.set("type", this.stream.network);
  1869. switch (type) {
  1870. case "tcp":
  1871. const tcp = this.stream.tcp;
  1872. if (tcp.type === 'http') {
  1873. const request = tcp.request;
  1874. params.set("path", request.path.join(','));
  1875. const index = request.headers.findIndex(header => header.name.toLowerCase() === 'host');
  1876. if (index >= 0) {
  1877. const host = request.headers[index].value;
  1878. params.set("host", host);
  1879. }
  1880. params.set("headerType", 'http');
  1881. }
  1882. break;
  1883. case "kcp":
  1884. const kcp = this.stream.kcp;
  1885. params.set("mtu", kcp.mtu);
  1886. params.set("tti", kcp.tti);
  1887. break;
  1888. case "ws":
  1889. const ws = this.stream.ws;
  1890. params.set("path", ws.path);
  1891. params.set("host", ws.host?.length > 0 ? ws.host : this.getHeader(ws, 'host'));
  1892. break;
  1893. case "grpc":
  1894. const grpc = this.stream.grpc;
  1895. params.set("serviceName", grpc.serviceName);
  1896. params.set("authority", grpc.authority);
  1897. if (grpc.multiMode) {
  1898. params.set("mode", "multi");
  1899. }
  1900. break;
  1901. case "httpupgrade":
  1902. const httpupgrade = this.stream.httpupgrade;
  1903. params.set("path", httpupgrade.path);
  1904. params.set("host", httpupgrade.host?.length > 0 ? httpupgrade.host : this.getHeader(httpupgrade, 'host'));
  1905. break;
  1906. case "xhttp":
  1907. Inbound.applyXhttpExtraToParams(this.stream.xhttp, params);
  1908. break;
  1909. }
  1910. Inbound.applyFinalMaskToParams(this.stream.finalmask, params);
  1911. if (security === 'tls') {
  1912. params.set("security", "tls");
  1913. if (this.stream.isTls) {
  1914. params.set("fp", this.stream.tls.settings.fingerprint);
  1915. params.set("alpn", this.stream.tls.alpn);
  1916. if (this.stream.tls.settings.echConfigList?.length > 0) {
  1917. params.set("ech", this.stream.tls.settings.echConfigList);
  1918. }
  1919. if (!ObjectUtil.isEmpty(this.stream.tls.sni)) {
  1920. params.set("sni", this.stream.tls.sni);
  1921. }
  1922. }
  1923. }
  1924. let password = new Array();
  1925. if (this.isSS2022) password.push(settings.password);
  1926. if (this.isSSMultiUser) password.push(clientPassword);
  1927. let link = `ss://${Base64.encode(`${settings.method}:${password.join(':')}`, true)}@${address}:${port}`;
  1928. const url = new URL(link);
  1929. for (const [key, value] of params) {
  1930. url.searchParams.set(key, value)
  1931. }
  1932. url.hash = encodeURIComponent(remark);
  1933. return url.toString();
  1934. }
  1935. genTrojanLink(address = '', port = this.port, forceTls, remark = '', clientPassword) {
  1936. const security = forceTls == 'same' ? this.stream.security : forceTls;
  1937. const type = this.stream.network;
  1938. const params = new Map();
  1939. params.set("type", this.stream.network);
  1940. switch (type) {
  1941. case "tcp":
  1942. const tcp = this.stream.tcp;
  1943. if (tcp.type === 'http') {
  1944. const request = tcp.request;
  1945. params.set("path", request.path.join(','));
  1946. const index = request.headers.findIndex(header => header.name.toLowerCase() === 'host');
  1947. if (index >= 0) {
  1948. const host = request.headers[index].value;
  1949. params.set("host", host);
  1950. }
  1951. params.set("headerType", 'http');
  1952. }
  1953. break;
  1954. case "kcp":
  1955. const kcp = this.stream.kcp;
  1956. params.set("mtu", kcp.mtu);
  1957. params.set("tti", kcp.tti);
  1958. break;
  1959. case "ws":
  1960. const ws = this.stream.ws;
  1961. params.set("path", ws.path);
  1962. params.set("host", ws.host?.length > 0 ? ws.host : this.getHeader(ws, 'host'));
  1963. break;
  1964. case "grpc":
  1965. const grpc = this.stream.grpc;
  1966. params.set("serviceName", grpc.serviceName);
  1967. params.set("authority", grpc.authority);
  1968. if (grpc.multiMode) {
  1969. params.set("mode", "multi");
  1970. }
  1971. break;
  1972. case "httpupgrade":
  1973. const httpupgrade = this.stream.httpupgrade;
  1974. params.set("path", httpupgrade.path);
  1975. params.set("host", httpupgrade.host?.length > 0 ? httpupgrade.host : this.getHeader(httpupgrade, 'host'));
  1976. break;
  1977. case "xhttp":
  1978. Inbound.applyXhttpExtraToParams(this.stream.xhttp, params);
  1979. break;
  1980. }
  1981. Inbound.applyFinalMaskToParams(this.stream.finalmask, params);
  1982. if (security === 'tls') {
  1983. params.set("security", "tls");
  1984. if (this.stream.isTls) {
  1985. params.set("fp", this.stream.tls.settings.fingerprint);
  1986. params.set("alpn", this.stream.tls.alpn);
  1987. if (this.stream.tls.settings.echConfigList?.length > 0) {
  1988. params.set("ech", this.stream.tls.settings.echConfigList);
  1989. }
  1990. if (!ObjectUtil.isEmpty(this.stream.tls.sni)) {
  1991. params.set("sni", this.stream.tls.sni);
  1992. }
  1993. }
  1994. }
  1995. else if (security === 'reality') {
  1996. params.set("security", "reality");
  1997. params.set("pbk", this.stream.reality.settings.publicKey);
  1998. params.set("fp", this.stream.reality.settings.fingerprint);
  1999. if (!ObjectUtil.isArrEmpty(this.stream.reality.serverNames)) {
  2000. params.set("sni", this.stream.reality.serverNames.split(",")[0]);
  2001. }
  2002. if (this.stream.reality.shortIds.length > 0) {
  2003. params.set("sid", this.stream.reality.shortIds.split(",")[0]);
  2004. }
  2005. if (!ObjectUtil.isEmpty(this.stream.reality.settings.spiderX)) {
  2006. params.set("spx", this.stream.reality.settings.spiderX);
  2007. }
  2008. if (!ObjectUtil.isEmpty(this.stream.reality.settings.mldsa65Verify)) {
  2009. params.set("pqv", this.stream.reality.settings.mldsa65Verify);
  2010. }
  2011. }
  2012. else {
  2013. params.set("security", "none");
  2014. }
  2015. const link = `trojan://${clientPassword}@${address}:${port}`;
  2016. const url = new URL(link);
  2017. for (const [key, value] of params) {
  2018. url.searchParams.set(key, value)
  2019. }
  2020. url.hash = encodeURIComponent(remark);
  2021. return url.toString();
  2022. }
  2023. genHysteriaLink(address = '', port = this.port, remark = '', clientAuth) {
  2024. const protocol = this.settings.version == 2 ? "hysteria2" : "hysteria";
  2025. const link = `${protocol}://${clientAuth}@${address}:${port}`;
  2026. const params = new Map();
  2027. params.set("security", "tls");
  2028. if (this.stream.tls.settings.fingerprint?.length > 0) params.set("fp", this.stream.tls.settings.fingerprint);
  2029. if (this.stream.tls.alpn?.length > 0) params.set("alpn", this.stream.tls.alpn);
  2030. if (this.stream.tls.settings.allowInsecure) params.set("insecure", "1");
  2031. if (this.stream.tls.settings.echConfigList?.length > 0) params.set("ech", this.stream.tls.settings.echConfigList);
  2032. if (this.stream.tls.sni?.length > 0) params.set("sni", this.stream.tls.sni);
  2033. const udpMasks = this.stream?.finalmask?.udp;
  2034. if (Array.isArray(udpMasks)) {
  2035. const salamanderMask = udpMasks.find(mask => mask?.type === 'salamander');
  2036. const obfsPassword = salamanderMask?.settings?.password;
  2037. if (typeof obfsPassword === 'string' && obfsPassword.length > 0) {
  2038. params.set("obfs", "salamander");
  2039. params.set("obfs-password", obfsPassword);
  2040. }
  2041. }
  2042. Inbound.applyFinalMaskToParams(this.stream.finalmask, params);
  2043. const url = new URL(link);
  2044. for (const [key, value] of params) {
  2045. url.searchParams.set(key, value);
  2046. }
  2047. url.hash = encodeURIComponent(remark);
  2048. return url.toString();
  2049. }
  2050. getWireguardTxt(address, port, remark, peerId) {
  2051. let txt = `[Interface]\n`
  2052. txt += `PrivateKey = ${this.settings.peers[peerId].privateKey}\n`
  2053. txt += `Address = ${this.settings.peers[peerId].allowedIPs[0]}\n`
  2054. txt += `DNS = 1.1.1.1, 1.0.0.1\n`
  2055. if (this.settings.mtu) {
  2056. txt += `MTU = ${this.settings.mtu}\n`
  2057. }
  2058. txt += `\n# ${remark}\n`
  2059. txt += `[Peer]\n`
  2060. txt += `PublicKey = ${this.settings.pubKey}\n`
  2061. txt += `AllowedIPs = 0.0.0.0/0, ::/0\n`
  2062. txt += `Endpoint = ${address}:${port}`
  2063. if (this.settings.peers[peerId].psk) {
  2064. txt += `\nPresharedKey = ${this.settings.peers[peerId].psk}`
  2065. }
  2066. if (this.settings.peers[peerId].keepAlive) {
  2067. txt += `\nPersistentKeepalive = ${this.settings.peers[peerId].keepAlive}\n`
  2068. }
  2069. return txt;
  2070. }
  2071. getWireguardLink(address, port, remark, peerId) {
  2072. const peer = this.settings?.peers?.[peerId];
  2073. if (!peer) return '';
  2074. const link = `wireguard://${address}:${port}`;
  2075. const url = new URL(link);
  2076. url.username = peer.privateKey || '';
  2077. if (this.settings?.pubKey) {
  2078. url.searchParams.set("publickey", this.settings.pubKey);
  2079. }
  2080. if (Array.isArray(peer.allowedIPs) && peer.allowedIPs.length > 0 && peer.allowedIPs[0]) {
  2081. url.searchParams.set("address", peer.allowedIPs[0]);
  2082. }
  2083. if (this.settings?.mtu) {
  2084. url.searchParams.set("mtu", this.settings.mtu);
  2085. }
  2086. url.hash = encodeURIComponent(remark);
  2087. return url.toString();
  2088. }
  2089. genWireguardLinks(remark = '', remarkModel = '-ieo') {
  2090. const addr = !ObjectUtil.isEmpty(this.listen) && this.listen !== "0.0.0.0" ? this.listen : location.hostname;
  2091. const separationChar = remarkModel.charAt(0);
  2092. let links = [];
  2093. this.settings.peers.forEach((p, index) => {
  2094. links.push(this.getWireguardLink(addr, this.port, remark + separationChar + (index + 1), index));
  2095. });
  2096. return links.join('\r\n');
  2097. }
  2098. genWireguardConfigs(remark = '', remarkModel = '-ieo') {
  2099. const addr = !ObjectUtil.isEmpty(this.listen) && this.listen !== "0.0.0.0" ? this.listen : location.hostname;
  2100. const separationChar = remarkModel.charAt(0);
  2101. let links = [];
  2102. this.settings.peers.forEach((p, index) => {
  2103. links.push(this.getWireguardTxt(addr, this.port, remark + separationChar + (index + 1), index));
  2104. });
  2105. return links.join('\r\n');
  2106. }
  2107. genLink(address = '', port = this.port, forceTls = 'same', remark = '', client) {
  2108. switch (this.protocol) {
  2109. case Protocols.VMESS:
  2110. return this.genVmessLink(address, port, forceTls, remark, client.id, client.security);
  2111. case Protocols.VLESS:
  2112. return this.genVLESSLink(address, port, forceTls, remark, client.id, client.flow);
  2113. case Protocols.SHADOWSOCKS:
  2114. return this.genSSLink(address, port, forceTls, remark, this.isSSMultiUser ? client.password : '');
  2115. case Protocols.TROJAN:
  2116. return this.genTrojanLink(address, port, forceTls, remark, client.password);
  2117. case Protocols.HYSTERIA:
  2118. return this.genHysteriaLink(address, port, remark, client.auth.length > 0 ? client.auth : this.stream.hysteria.auth);
  2119. default: return '';
  2120. }
  2121. }
  2122. genAllLinks(remark = '', remarkModel = '-ieo', client) {
  2123. let result = [];
  2124. let email = client ? client.email : '';
  2125. let addr = !ObjectUtil.isEmpty(this.listen) && this.listen !== "0.0.0.0" ? this.listen : location.hostname;
  2126. let port = this.port;
  2127. const separationChar = remarkModel.charAt(0);
  2128. const orderChars = remarkModel.slice(1);
  2129. let orders = {
  2130. 'i': remark,
  2131. 'e': email,
  2132. 'o': '',
  2133. };
  2134. if (ObjectUtil.isArrEmpty(this.stream.externalProxy)) {
  2135. let r = orderChars.split('').map(char => orders[char]).filter(x => x.length > 0).join(separationChar);
  2136. result.push({
  2137. remark: r,
  2138. link: this.genLink(addr, port, 'same', r, client)
  2139. });
  2140. } else {
  2141. this.stream.externalProxy.forEach((ep) => {
  2142. orders['o'] = ep.remark;
  2143. let r = orderChars.split('').map(char => orders[char]).filter(x => x.length > 0).join(separationChar);
  2144. result.push({
  2145. remark: r,
  2146. link: this.genLink(ep.dest, ep.port, ep.forceTls, r, client)
  2147. });
  2148. });
  2149. }
  2150. return result;
  2151. }
  2152. genInboundLinks(remark = '', remarkModel = '-ieo') {
  2153. let addr = !ObjectUtil.isEmpty(this.listen) && this.listen !== "0.0.0.0" ? this.listen : location.hostname;
  2154. if (this.clients) {
  2155. let links = [];
  2156. this.clients.forEach((client) => {
  2157. this.genAllLinks(remark, remarkModel, client).forEach(l => {
  2158. links.push(l.link);
  2159. })
  2160. });
  2161. return links.join('\r\n');
  2162. } else {
  2163. if (this.protocol == Protocols.SHADOWSOCKS && !this.isSSMultiUser) return this.genSSLink(addr, this.port, 'same', remark);
  2164. if (this.protocol == Protocols.WIREGUARD) {
  2165. return this.genWireguardConfigs(remark, remarkModel);
  2166. }
  2167. return '';
  2168. }
  2169. }
  2170. static fromJson(json = {}) {
  2171. return new Inbound(
  2172. json.port,
  2173. json.listen,
  2174. json.protocol,
  2175. Inbound.Settings.fromJson(json.protocol, json.settings),
  2176. StreamSettings.fromJson(json.streamSettings),
  2177. json.tag,
  2178. Sniffing.fromJson(json.sniffing),
  2179. json.clientStats
  2180. )
  2181. }
  2182. toJson() {
  2183. let streamSettings;
  2184. if (this.canEnableStream() || this.stream?.sockopt) {
  2185. streamSettings = this.stream.toJson();
  2186. }
  2187. return {
  2188. port: this.port,
  2189. listen: this.listen,
  2190. protocol: this.protocol,
  2191. settings: this.settings instanceof XrayCommonClass ? this.settings.toJson() : this.settings,
  2192. streamSettings: streamSettings,
  2193. tag: this.tag,
  2194. sniffing: this.sniffing.toJson(),
  2195. clientStats: this.clientStats
  2196. };
  2197. }
  2198. }
  2199. Inbound.Settings = class extends XrayCommonClass {
  2200. constructor(protocol) {
  2201. super();
  2202. this.protocol = protocol;
  2203. }
  2204. static getSettings(protocol) {
  2205. switch (protocol) {
  2206. case Protocols.VMESS: return new Inbound.VmessSettings(protocol);
  2207. case Protocols.VLESS: return new Inbound.VLESSSettings(protocol);
  2208. case Protocols.TROJAN: return new Inbound.TrojanSettings(protocol);
  2209. case Protocols.SHADOWSOCKS: return new Inbound.ShadowsocksSettings(protocol);
  2210. case Protocols.TUNNEL: return new Inbound.TunnelSettings(protocol);
  2211. case Protocols.MIXED: return new Inbound.MixedSettings(protocol);
  2212. case Protocols.HTTP: return new Inbound.HttpSettings(protocol);
  2213. case Protocols.WIREGUARD: return new Inbound.WireguardSettings(protocol);
  2214. case Protocols.TUN: return new Inbound.TunSettings(protocol);
  2215. case Protocols.HYSTERIA: return new Inbound.HysteriaSettings(protocol);
  2216. default: return null;
  2217. }
  2218. }
  2219. static fromJson(protocol, json) {
  2220. switch (protocol) {
  2221. case Protocols.VMESS: return Inbound.VmessSettings.fromJson(json);
  2222. case Protocols.VLESS: return Inbound.VLESSSettings.fromJson(json);
  2223. case Protocols.TROJAN: return Inbound.TrojanSettings.fromJson(json);
  2224. case Protocols.SHADOWSOCKS: return Inbound.ShadowsocksSettings.fromJson(json);
  2225. case Protocols.TUNNEL: return Inbound.TunnelSettings.fromJson(json);
  2226. case Protocols.MIXED: return Inbound.MixedSettings.fromJson(json);
  2227. case Protocols.HTTP: return Inbound.HttpSettings.fromJson(json);
  2228. case Protocols.WIREGUARD: return Inbound.WireguardSettings.fromJson(json);
  2229. case Protocols.TUN: return Inbound.TunSettings.fromJson(json);
  2230. case Protocols.HYSTERIA: return Inbound.HysteriaSettings.fromJson(json);
  2231. default: return null;
  2232. }
  2233. }
  2234. toJson() {
  2235. return {};
  2236. }
  2237. };
  2238. /** Shared user-quota fields and UI helpers for multi-user protocol clients. */
  2239. Inbound.ClientBase = class extends XrayCommonClass {
  2240. constructor(
  2241. email = RandomUtil.randomLowerAndNum(8),
  2242. limitIp = 0,
  2243. totalGB = 0,
  2244. expiryTime = 0,
  2245. enable = true,
  2246. tgId = '',
  2247. subId = RandomUtil.randomLowerAndNum(16),
  2248. comment = '',
  2249. reset = 0,
  2250. created_at = undefined,
  2251. updated_at = undefined,
  2252. ) {
  2253. super();
  2254. this.email = email;
  2255. this.limitIp = limitIp;
  2256. this.totalGB = totalGB;
  2257. this.expiryTime = expiryTime;
  2258. this.enable = enable;
  2259. this.tgId = tgId;
  2260. this.subId = subId;
  2261. this.comment = comment;
  2262. this.reset = reset;
  2263. this.created_at = created_at;
  2264. this.updated_at = updated_at;
  2265. }
  2266. static commonArgsFromJson(json = {}) {
  2267. return [
  2268. json.email,
  2269. json.limitIp,
  2270. json.totalGB,
  2271. json.expiryTime,
  2272. json.enable,
  2273. json.tgId,
  2274. json.subId,
  2275. json.comment,
  2276. json.reset,
  2277. json.created_at,
  2278. json.updated_at,
  2279. ];
  2280. }
  2281. _clientBaseToJson() {
  2282. return {
  2283. email: this.email,
  2284. limitIp: this.limitIp,
  2285. totalGB: this.totalGB,
  2286. expiryTime: this.expiryTime,
  2287. enable: this.enable,
  2288. tgId: this.tgId,
  2289. subId: this.subId,
  2290. comment: this.comment,
  2291. reset: this.reset,
  2292. created_at: this.created_at,
  2293. updated_at: this.updated_at,
  2294. };
  2295. }
  2296. get _expiryTime() {
  2297. if (this.expiryTime === 0 || this.expiryTime === '') {
  2298. return null;
  2299. }
  2300. if (this.expiryTime < 0) {
  2301. return this.expiryTime / -86400000;
  2302. }
  2303. return moment(this.expiryTime);
  2304. }
  2305. set _expiryTime(t) {
  2306. if (t == null || t === '') {
  2307. this.expiryTime = 0;
  2308. } else {
  2309. this.expiryTime = t.valueOf();
  2310. }
  2311. }
  2312. get _totalGB() {
  2313. return NumberFormatter.toFixed(this.totalGB / SizeFormatter.ONE_GB, 2);
  2314. }
  2315. set _totalGB(gb) {
  2316. this.totalGB = NumberFormatter.toFixed(gb * SizeFormatter.ONE_GB, 0);
  2317. }
  2318. };
  2319. Inbound.VmessSettings = class extends Inbound.Settings {
  2320. constructor(protocol,
  2321. vmesses = [new Inbound.VmessSettings.VMESS()]) {
  2322. super(protocol);
  2323. this.vmesses = vmesses;
  2324. }
  2325. indexOfVmessById(id) {
  2326. return this.vmesses.findIndex(VMESS => VMESS.id === id);
  2327. }
  2328. addVmess(VMESS) {
  2329. if (this.indexOfVmessById(VMESS.id) >= 0) {
  2330. return false;
  2331. }
  2332. this.vmesses.push(VMESS);
  2333. }
  2334. delVmess(VMESS) {
  2335. const i = this.indexOfVmessById(VMESS.id);
  2336. if (i >= 0) {
  2337. this.vmesses.splice(i, 1);
  2338. }
  2339. }
  2340. static fromJson(json = {}) {
  2341. return new Inbound.VmessSettings(
  2342. Protocols.VMESS,
  2343. (json.clients || []).map(client => Inbound.VmessSettings.VMESS.fromJson(client)),
  2344. );
  2345. }
  2346. toJson() {
  2347. return {
  2348. clients: Inbound.VmessSettings.toJsonArray(this.vmesses),
  2349. };
  2350. }
  2351. };
  2352. Inbound.VmessSettings.VMESS = class extends Inbound.ClientBase {
  2353. constructor(
  2354. id = RandomUtil.randomUUID(),
  2355. security = USERS_SECURITY.AUTO,
  2356. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2357. ) {
  2358. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2359. this.id = id;
  2360. this.security = security;
  2361. }
  2362. static fromJson(json = {}) {
  2363. return new Inbound.VmessSettings.VMESS(
  2364. json.id,
  2365. json.security,
  2366. ...Inbound.ClientBase.commonArgsFromJson(json),
  2367. );
  2368. }
  2369. toJson() {
  2370. return {
  2371. id: this.id,
  2372. security: this.security,
  2373. ...this._clientBaseToJson(),
  2374. };
  2375. }
  2376. };
  2377. Inbound.VLESSSettings = class extends Inbound.Settings {
  2378. constructor(
  2379. protocol,
  2380. vlesses = [new Inbound.VLESSSettings.VLESS()],
  2381. decryption = "none",
  2382. encryption = "none",
  2383. fallbacks = [],
  2384. testseed = [],
  2385. ) {
  2386. super(protocol);
  2387. this.vlesses = vlesses;
  2388. this.decryption = decryption;
  2389. this.encryption = encryption;
  2390. this.fallbacks = fallbacks;
  2391. this.testseed = testseed;
  2392. }
  2393. addFallback() {
  2394. this.fallbacks.push(new Inbound.VLESSSettings.Fallback());
  2395. }
  2396. delFallback(index) {
  2397. this.fallbacks.splice(index, 1);
  2398. }
  2399. // Empty array means "use server defaults" (won't be sent).
  2400. // Anything else must be exactly 4 positive integers.
  2401. static isValidTestseed(arr) {
  2402. if (!Array.isArray(arr) || arr.length === 0) return true;
  2403. if (arr.length !== 4) return false;
  2404. return arr.every(v => Number.isInteger(v) && v > 0);
  2405. }
  2406. static fromJson(json = {}) {
  2407. // Preserve a saved testseed only if it's a valid 4-positive-int array; otherwise leave empty
  2408. // so toJson omits it and the form falls back to placeholder defaults.
  2409. const saved = json.testseed;
  2410. const testseed = (Array.isArray(saved)
  2411. && saved.length === 4
  2412. && saved.every(v => Number.isInteger(v) && v > 0))
  2413. ? saved
  2414. : [];
  2415. const obj = new Inbound.VLESSSettings(
  2416. Protocols.VLESS,
  2417. (json.clients || []).map(client => Inbound.VLESSSettings.VLESS.fromJson(client)),
  2418. json.decryption,
  2419. json.encryption,
  2420. Inbound.VLESSSettings.Fallback.fromJson(json.fallbacks || []),
  2421. testseed,
  2422. );
  2423. return obj;
  2424. }
  2425. toJson() {
  2426. const json = {
  2427. clients: Inbound.VLESSSettings.toJsonArray(this.vlesses),
  2428. };
  2429. if (this.decryption) {
  2430. json.decryption = this.decryption;
  2431. }
  2432. if (this.encryption) {
  2433. json.encryption = this.encryption;
  2434. }
  2435. if (this.fallbacks && this.fallbacks.length > 0) {
  2436. json.fallbacks = Inbound.VLESSSettings.toJsonArray(this.fallbacks);
  2437. }
  2438. // testseed is only meaningful for the exact xtls-rprx-vision flow, and only when
  2439. // the user supplied a complete 4-positive-int array. Otherwise omit and let the
  2440. // backend fall back to its safe defaults.
  2441. const hasVisionFlow = this.vlesses && this.vlesses.some(v => v.flow === TLS_FLOW_CONTROL.VISION);
  2442. if (hasVisionFlow
  2443. && Array.isArray(this.testseed)
  2444. && this.testseed.length === 4
  2445. && this.testseed.every(v => Number.isInteger(v) && v > 0)) {
  2446. json.testseed = this.testseed;
  2447. }
  2448. return json;
  2449. }
  2450. };
  2451. Inbound.VLESSSettings.VLESS = class extends Inbound.ClientBase {
  2452. constructor(
  2453. id = RandomUtil.randomUUID(),
  2454. flow = '',
  2455. reverseTag = '',
  2456. reverseSniffing = new Sniffing(),
  2457. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2458. ) {
  2459. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2460. this.id = id;
  2461. this.flow = flow;
  2462. this.reverseTag = reverseTag;
  2463. this.reverseSniffing = reverseSniffing;
  2464. }
  2465. static fromJson(json = {}) {
  2466. return new Inbound.VLESSSettings.VLESS(
  2467. json.id,
  2468. json.flow,
  2469. json.reverse?.tag ?? '',
  2470. Sniffing.fromJson(json.reverse?.sniffing || {}),
  2471. ...Inbound.ClientBase.commonArgsFromJson(json),
  2472. );
  2473. }
  2474. toJson() {
  2475. const json = {
  2476. id: this.id,
  2477. flow: this.flow,
  2478. ...this._clientBaseToJson(),
  2479. };
  2480. if (this.reverseTag) {
  2481. json.reverse = {
  2482. tag: this.reverseTag,
  2483. };
  2484. }
  2485. return json;
  2486. }
  2487. };
  2488. Inbound.VLESSSettings.Fallback = class extends XrayCommonClass {
  2489. constructor(name = "", alpn = '', path = '', dest = '', xver = 0) {
  2490. super();
  2491. this.name = name;
  2492. this.alpn = alpn;
  2493. this.path = path;
  2494. this.dest = dest;
  2495. this.xver = xver;
  2496. }
  2497. toJson() {
  2498. let xver = this.xver;
  2499. if (!Number.isInteger(xver)) {
  2500. xver = 0;
  2501. }
  2502. return {
  2503. name: this.name,
  2504. alpn: this.alpn,
  2505. path: this.path,
  2506. dest: this.dest,
  2507. xver: xver,
  2508. }
  2509. }
  2510. static fromJson(json = []) {
  2511. const fallbacks = [];
  2512. for (let fallback of json) {
  2513. fallbacks.push(new Inbound.VLESSSettings.Fallback(
  2514. fallback.name,
  2515. fallback.alpn,
  2516. fallback.path,
  2517. fallback.dest,
  2518. fallback.xver,
  2519. ))
  2520. }
  2521. return fallbacks;
  2522. }
  2523. };
  2524. Inbound.TrojanSettings = class extends Inbound.Settings {
  2525. constructor(protocol,
  2526. trojans = [new Inbound.TrojanSettings.Trojan()],
  2527. fallbacks = [],) {
  2528. super(protocol);
  2529. this.trojans = trojans;
  2530. this.fallbacks = fallbacks;
  2531. }
  2532. addFallback() {
  2533. this.fallbacks.push(new Inbound.TrojanSettings.Fallback());
  2534. }
  2535. delFallback(index) {
  2536. this.fallbacks.splice(index, 1);
  2537. }
  2538. static fromJson(json = {}) {
  2539. return new Inbound.TrojanSettings(
  2540. Protocols.TROJAN,
  2541. (json.clients || []).map(client => Inbound.TrojanSettings.Trojan.fromJson(client)),
  2542. Inbound.TrojanSettings.Fallback.fromJson(json.fallbacks),);
  2543. }
  2544. toJson() {
  2545. return {
  2546. clients: Inbound.TrojanSettings.toJsonArray(this.trojans),
  2547. fallbacks: Inbound.TrojanSettings.toJsonArray(this.fallbacks)
  2548. };
  2549. }
  2550. };
  2551. Inbound.TrojanSettings.Trojan = class extends Inbound.ClientBase {
  2552. constructor(
  2553. password = RandomUtil.randomSeq(10),
  2554. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2555. ) {
  2556. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2557. this.password = password;
  2558. }
  2559. toJson() {
  2560. return {
  2561. password: this.password,
  2562. ...this._clientBaseToJson(),
  2563. };
  2564. }
  2565. static fromJson(json = {}) {
  2566. return new Inbound.TrojanSettings.Trojan(
  2567. json.password,
  2568. ...Inbound.ClientBase.commonArgsFromJson(json),
  2569. );
  2570. }
  2571. };
  2572. Inbound.TrojanSettings.Fallback = class extends XrayCommonClass {
  2573. constructor(name = "", alpn = '', path = '', dest = '', xver = 0) {
  2574. super();
  2575. this.name = name;
  2576. this.alpn = alpn;
  2577. this.path = path;
  2578. this.dest = dest;
  2579. this.xver = xver;
  2580. }
  2581. toJson() {
  2582. let xver = this.xver;
  2583. if (!Number.isInteger(xver)) {
  2584. xver = 0;
  2585. }
  2586. return {
  2587. name: this.name,
  2588. alpn: this.alpn,
  2589. path: this.path,
  2590. dest: this.dest,
  2591. xver: xver,
  2592. }
  2593. }
  2594. static fromJson(json = []) {
  2595. const fallbacks = [];
  2596. for (let fallback of json) {
  2597. fallbacks.push(new Inbound.TrojanSettings.Fallback(
  2598. fallback.name,
  2599. fallback.alpn,
  2600. fallback.path,
  2601. fallback.dest,
  2602. fallback.xver,
  2603. ))
  2604. }
  2605. return fallbacks;
  2606. }
  2607. };
  2608. Inbound.ShadowsocksSettings = class extends Inbound.Settings {
  2609. constructor(protocol,
  2610. method = SSMethods.BLAKE3_AES_256_GCM,
  2611. password = RandomUtil.randomShadowsocksPassword(),
  2612. network = 'tcp,udp',
  2613. shadowsockses = [new Inbound.ShadowsocksSettings.Shadowsocks()],
  2614. ivCheck = false,
  2615. ) {
  2616. super(protocol);
  2617. this.method = method;
  2618. this.password = password;
  2619. this.network = network;
  2620. this.shadowsockses = shadowsockses;
  2621. this.ivCheck = ivCheck;
  2622. }
  2623. static fromJson(json = {}) {
  2624. return new Inbound.ShadowsocksSettings(
  2625. Protocols.SHADOWSOCKS,
  2626. json.method,
  2627. json.password,
  2628. json.network,
  2629. (json.clients || []).map(client => Inbound.ShadowsocksSettings.Shadowsocks.fromJson(client)),
  2630. json.ivCheck,
  2631. );
  2632. }
  2633. toJson() {
  2634. return {
  2635. method: this.method,
  2636. password: this.password,
  2637. network: this.network,
  2638. clients: Inbound.ShadowsocksSettings.toJsonArray(this.shadowsockses),
  2639. ivCheck: this.ivCheck,
  2640. };
  2641. }
  2642. };
  2643. Inbound.ShadowsocksSettings.Shadowsocks = class extends Inbound.ClientBase {
  2644. constructor(
  2645. method = '',
  2646. password = RandomUtil.randomShadowsocksPassword(),
  2647. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2648. ) {
  2649. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2650. this.method = method;
  2651. this.password = password;
  2652. }
  2653. toJson() {
  2654. return {
  2655. method: this.method,
  2656. password: this.password,
  2657. ...this._clientBaseToJson(),
  2658. };
  2659. }
  2660. static fromJson(json = {}) {
  2661. return new Inbound.ShadowsocksSettings.Shadowsocks(
  2662. json.method,
  2663. json.password,
  2664. ...Inbound.ClientBase.commonArgsFromJson(json),
  2665. );
  2666. }
  2667. };
  2668. Inbound.HysteriaSettings = class extends Inbound.Settings {
  2669. constructor(protocol, version = 2, hysterias = [new Inbound.HysteriaSettings.Hysteria()]) {
  2670. super(protocol);
  2671. this.version = version;
  2672. this.hysterias = hysterias;
  2673. }
  2674. static fromJson(json = {}) {
  2675. return new Inbound.HysteriaSettings(
  2676. Protocols.HYSTERIA,
  2677. json.version ?? 2,
  2678. (json.clients || []).map(client => Inbound.HysteriaSettings.Hysteria.fromJson(client)),
  2679. );
  2680. }
  2681. toJson() {
  2682. return {
  2683. version: this.version,
  2684. clients: Inbound.HysteriaSettings.toJsonArray(this.hysterias),
  2685. };
  2686. }
  2687. };
  2688. Inbound.HysteriaSettings.Hysteria = class extends Inbound.ClientBase {
  2689. constructor(
  2690. auth = RandomUtil.randomSeq(10),
  2691. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2692. ) {
  2693. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2694. this.auth = auth;
  2695. }
  2696. toJson() {
  2697. return {
  2698. auth: this.auth,
  2699. ...this._clientBaseToJson(),
  2700. };
  2701. }
  2702. static fromJson(json = {}) {
  2703. return new Inbound.HysteriaSettings.Hysteria(
  2704. json.auth,
  2705. ...Inbound.ClientBase.commonArgsFromJson(json),
  2706. );
  2707. }
  2708. };
  2709. Inbound.TunnelSettings = class extends Inbound.Settings {
  2710. constructor(
  2711. protocol,
  2712. address,
  2713. port,
  2714. portMap = [],
  2715. network = 'tcp,udp',
  2716. followRedirect = false
  2717. ) {
  2718. super(protocol);
  2719. this.address = address;
  2720. this.port = port;
  2721. this.portMap = portMap;
  2722. this.network = network;
  2723. this.followRedirect = followRedirect;
  2724. }
  2725. static fromJson(json = {}) {
  2726. return new Inbound.TunnelSettings(
  2727. Protocols.TUNNEL,
  2728. json.address,
  2729. json.port,
  2730. XrayCommonClass.toHeaders(json.portMap),
  2731. json.network,
  2732. json.followRedirect,
  2733. );
  2734. }
  2735. toJson() {
  2736. return {
  2737. address: this.address,
  2738. port: this.port,
  2739. portMap: XrayCommonClass.toV2Headers(this.portMap, false),
  2740. network: this.network,
  2741. followRedirect: this.followRedirect,
  2742. };
  2743. }
  2744. };
  2745. Inbound.MixedSettings = class extends Inbound.Settings {
  2746. constructor(protocol, auth = 'password', accounts = [new Inbound.MixedSettings.SocksAccount()], udp = false, ip = '127.0.0.1') {
  2747. super(protocol);
  2748. this.auth = auth;
  2749. this.accounts = accounts;
  2750. this.udp = udp;
  2751. this.ip = ip;
  2752. }
  2753. addAccount(account) {
  2754. this.accounts.push(account);
  2755. }
  2756. delAccount(index) {
  2757. this.accounts.splice(index, 1);
  2758. }
  2759. static fromJson(json = {}) {
  2760. let accounts;
  2761. if (json.auth === 'password') {
  2762. accounts = json.accounts.map(
  2763. account => Inbound.MixedSettings.SocksAccount.fromJson(account)
  2764. )
  2765. }
  2766. return new Inbound.MixedSettings(
  2767. Protocols.MIXED,
  2768. json.auth,
  2769. accounts,
  2770. json.udp,
  2771. json.ip,
  2772. );
  2773. }
  2774. toJson() {
  2775. return {
  2776. auth: this.auth,
  2777. accounts: this.auth === 'password' ? this.accounts.map(account => account.toJson()) : undefined,
  2778. udp: this.udp,
  2779. ip: this.ip,
  2780. };
  2781. }
  2782. };
  2783. Inbound.MixedSettings.SocksAccount = class extends XrayCommonClass {
  2784. constructor(user = RandomUtil.randomSeq(10), pass = RandomUtil.randomSeq(10)) {
  2785. super();
  2786. this.user = user;
  2787. this.pass = pass;
  2788. }
  2789. static fromJson(json = {}) {
  2790. return new Inbound.MixedSettings.SocksAccount(json.user, json.pass);
  2791. }
  2792. };
  2793. Inbound.HttpSettings = class extends Inbound.Settings {
  2794. constructor(
  2795. protocol,
  2796. accounts = [new Inbound.HttpSettings.HttpAccount()],
  2797. allowTransparent = false,
  2798. ) {
  2799. super(protocol);
  2800. this.accounts = accounts;
  2801. this.allowTransparent = allowTransparent;
  2802. }
  2803. addAccount(account) {
  2804. this.accounts.push(account);
  2805. }
  2806. delAccount(index) {
  2807. this.accounts.splice(index, 1);
  2808. }
  2809. static fromJson(json = {}) {
  2810. return new Inbound.HttpSettings(
  2811. Protocols.HTTP,
  2812. json.accounts.map(account => Inbound.HttpSettings.HttpAccount.fromJson(account)),
  2813. json.allowTransparent,
  2814. );
  2815. }
  2816. toJson() {
  2817. return {
  2818. accounts: Inbound.HttpSettings.toJsonArray(this.accounts),
  2819. allowTransparent: this.allowTransparent,
  2820. };
  2821. }
  2822. };
  2823. Inbound.HttpSettings.HttpAccount = class extends XrayCommonClass {
  2824. constructor(user = RandomUtil.randomSeq(10), pass = RandomUtil.randomSeq(10)) {
  2825. super();
  2826. this.user = user;
  2827. this.pass = pass;
  2828. }
  2829. static fromJson(json = {}) {
  2830. return new Inbound.HttpSettings.HttpAccount(json.user, json.pass);
  2831. }
  2832. };
  2833. Inbound.WireguardSettings = class extends XrayCommonClass {
  2834. constructor(
  2835. protocol,
  2836. mtu = 1420,
  2837. secretKey = Wireguard.generateKeypair().privateKey,
  2838. peers = [new Inbound.WireguardSettings.Peer()],
  2839. noKernelTun = false
  2840. ) {
  2841. super(protocol);
  2842. this.mtu = mtu;
  2843. this.secretKey = secretKey;
  2844. this.pubKey = secretKey.length > 0 ? Wireguard.generateKeypair(secretKey).publicKey : '';
  2845. this.peers = peers;
  2846. this.noKernelTun = noKernelTun;
  2847. }
  2848. addPeer() {
  2849. this.peers.push(new Inbound.WireguardSettings.Peer(null, null, '', ['10.0.0.' + (this.peers.length + 2)]));
  2850. }
  2851. delPeer(index) {
  2852. this.peers.splice(index, 1);
  2853. }
  2854. static fromJson(json = {}) {
  2855. return new Inbound.WireguardSettings(
  2856. Protocols.WIREGUARD,
  2857. json.mtu,
  2858. json.secretKey,
  2859. json.peers.map(peer => Inbound.WireguardSettings.Peer.fromJson(peer)),
  2860. json.noKernelTun,
  2861. );
  2862. }
  2863. toJson() {
  2864. return {
  2865. mtu: this.mtu ?? undefined,
  2866. secretKey: this.secretKey,
  2867. peers: Inbound.WireguardSettings.Peer.toJsonArray(this.peers),
  2868. noKernelTun: this.noKernelTun,
  2869. };
  2870. }
  2871. };
  2872. Inbound.WireguardSettings.Peer = class extends XrayCommonClass {
  2873. constructor(privateKey, publicKey, psk = '', allowedIPs = ['10.0.0.2/32'], keepAlive = 0) {
  2874. super();
  2875. this.privateKey = privateKey
  2876. this.publicKey = publicKey;
  2877. if (!this.publicKey) {
  2878. [this.publicKey, this.privateKey] = Object.values(Wireguard.generateKeypair())
  2879. }
  2880. this.psk = psk;
  2881. allowedIPs.forEach((a, index) => {
  2882. if (a.length > 0 && !a.includes('/')) allowedIPs[index] += '/32';
  2883. })
  2884. this.allowedIPs = allowedIPs;
  2885. this.keepAlive = keepAlive;
  2886. }
  2887. static fromJson(json = {}) {
  2888. return new Inbound.WireguardSettings.Peer(
  2889. json.privateKey,
  2890. json.publicKey,
  2891. json.preSharedKey,
  2892. json.allowedIPs,
  2893. json.keepAlive
  2894. );
  2895. }
  2896. toJson() {
  2897. this.allowedIPs.forEach((a, index) => {
  2898. if (a.length > 0 && !a.includes('/')) this.allowedIPs[index] += '/32';
  2899. });
  2900. return {
  2901. privateKey: this.privateKey,
  2902. publicKey: this.publicKey,
  2903. preSharedKey: this.psk.length > 0 ? this.psk : undefined,
  2904. allowedIPs: this.allowedIPs,
  2905. keepAlive: this.keepAlive ?? undefined,
  2906. };
  2907. }
  2908. };
  2909. Inbound.TunSettings = class extends Inbound.Settings {
  2910. constructor(
  2911. protocol,
  2912. name = 'xray0',
  2913. mtu = [1500, 1280],
  2914. gateway = [],
  2915. dns = [],
  2916. userLevel = 0,
  2917. autoSystemRoutingTable = [],
  2918. autoOutboundsInterface = 'auto'
  2919. ) {
  2920. super(protocol);
  2921. this.name = name;
  2922. this.mtu = this._normalizeMtu(mtu);
  2923. this.gateway = Array.isArray(gateway) ? gateway : [];
  2924. this.dns = Array.isArray(dns) ? dns : [];
  2925. this.userLevel = userLevel;
  2926. this.autoSystemRoutingTable = Array.isArray(autoSystemRoutingTable) ? autoSystemRoutingTable : [];
  2927. this.autoOutboundsInterface = autoOutboundsInterface;
  2928. }
  2929. _normalizeMtu(mtu) {
  2930. if (!Array.isArray(mtu)) {
  2931. const single = Number(mtu) || 1500;
  2932. return [single, single];
  2933. }
  2934. if (mtu.length === 0) {
  2935. return [1500, 1280];
  2936. }
  2937. if (mtu.length === 1) {
  2938. const single = Number(mtu[0]) || 1500;
  2939. return [single, single];
  2940. }
  2941. return [Number(mtu[0]) || 1500, Number(mtu[1]) || 1280];
  2942. }
  2943. static fromJson(json = {}) {
  2944. return new Inbound.TunSettings(
  2945. Protocols.TUN,
  2946. json.name ?? 'xray0',
  2947. json.mtu ?? json.MTU ?? [1500, 1280],
  2948. json.gateway ?? json.Gateway ?? [],
  2949. json.dns ?? json.DNS ?? [],
  2950. json.userLevel ?? 0,
  2951. json.autoSystemRoutingTable ?? [],
  2952. Object.prototype.hasOwnProperty.call(json, 'autoOutboundsInterface') ? json.autoOutboundsInterface : 'auto'
  2953. );
  2954. }
  2955. toJson() {
  2956. return {
  2957. name: this.name || 'xray0',
  2958. mtu: this._normalizeMtu(this.mtu),
  2959. gateway: this.gateway,
  2960. dns: this.dns,
  2961. userLevel: this.userLevel || 0,
  2962. autoSystemRoutingTable: this.autoSystemRoutingTable,
  2963. autoOutboundsInterface: this.autoOutboundsInterface,
  2964. };
  2965. }
  2966. };