inbound.js 78 KB

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