inbound.js 93 KB

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