inbound.js 89 KB

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