xray.js 79 KB

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