inbound.js 104 KB

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