inbound.js 86 KB

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