inbound.js 101 KB

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