inbound.js 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913
  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. get clients() {
  1265. switch (this.protocol) {
  1266. case Protocols.VMESS: return this.settings.vmesses;
  1267. case Protocols.VLESS: return this.settings.vlesses;
  1268. case Protocols.TROJAN: return this.settings.trojans;
  1269. case Protocols.SHADOWSOCKS: return this.isSSMultiUser ? this.settings.shadowsockses : null;
  1270. case Protocols.HYSTERIA: return this.settings.hysterias;
  1271. default: return null;
  1272. }
  1273. }
  1274. get protocol() {
  1275. return this._protocol;
  1276. }
  1277. set protocol(protocol) {
  1278. this._protocol = protocol;
  1279. this.settings = Inbound.Settings.getSettings(protocol);
  1280. this.stream = new StreamSettings();
  1281. if (protocol === Protocols.TROJAN) {
  1282. this.tls = false;
  1283. }
  1284. if (protocol === Protocols.HYSTERIA) {
  1285. this.stream.network = 'hysteria';
  1286. this.stream.security = 'tls';
  1287. // Hysteria runs over QUIC and must not inherit TCP TLS ALPN defaults.
  1288. this.stream.tls.alpn = [ALPN_OPTION.H3];
  1289. }
  1290. }
  1291. get network() {
  1292. return this.stream.network;
  1293. }
  1294. set network(network) {
  1295. this.stream.network = network;
  1296. }
  1297. get isTcp() {
  1298. return this.network === "tcp";
  1299. }
  1300. get isWs() {
  1301. return this.network === "ws";
  1302. }
  1303. get isKcp() {
  1304. return this.network === "kcp";
  1305. }
  1306. get isGrpc() {
  1307. return this.network === "grpc";
  1308. }
  1309. get isHttpupgrade() {
  1310. return this.network === "httpupgrade";
  1311. }
  1312. get isXHTTP() {
  1313. return this.network === "xhttp";
  1314. }
  1315. // Shadowsocks
  1316. get method() {
  1317. switch (this.protocol) {
  1318. case Protocols.SHADOWSOCKS:
  1319. return this.settings.method;
  1320. default:
  1321. return "";
  1322. }
  1323. }
  1324. get isSSMultiUser() {
  1325. return this.method != SSMethods.BLAKE3_CHACHA20_POLY1305;
  1326. }
  1327. get isSS2022() {
  1328. return this.method.substring(0, 4) === "2022";
  1329. }
  1330. get serverName() {
  1331. if (this.stream.isTls) return this.stream.tls.sni;
  1332. if (this.stream.isReality) return this.stream.reality.serverNames;
  1333. return "";
  1334. }
  1335. getHeader(obj, name) {
  1336. for (const header of obj.headers) {
  1337. if (header.name.toLowerCase() === name.toLowerCase()) {
  1338. return header.value;
  1339. }
  1340. }
  1341. return "";
  1342. }
  1343. get host() {
  1344. if (this.isTcp) {
  1345. return this.getHeader(this.stream.tcp.request, 'host');
  1346. } else if (this.isWs) {
  1347. return this.stream.ws.host?.length > 0 ? this.stream.ws.host : this.getHeader(this.stream.ws, 'host');
  1348. } else if (this.isHttpupgrade) {
  1349. return this.stream.httpupgrade.host?.length > 0 ? this.stream.httpupgrade.host : this.getHeader(this.stream.httpupgrade, 'host');
  1350. } else if (this.isXHTTP) {
  1351. return this.stream.xhttp.host?.length > 0 ? this.stream.xhttp.host : this.getHeader(this.stream.xhttp, 'host');
  1352. }
  1353. return null;
  1354. }
  1355. get path() {
  1356. if (this.isTcp) {
  1357. return this.stream.tcp.request.path[0];
  1358. } else if (this.isWs) {
  1359. return this.stream.ws.path;
  1360. } else if (this.isHttpupgrade) {
  1361. return this.stream.httpupgrade.path;
  1362. } else if (this.isXHTTP) {
  1363. return this.stream.xhttp.path;
  1364. }
  1365. return null;
  1366. }
  1367. get serviceName() {
  1368. return this.stream.grpc.serviceName;
  1369. }
  1370. isExpiry(index) {
  1371. let exp = this.clients[index].expiryTime;
  1372. return exp > 0 ? exp < new Date().getTime() : false;
  1373. }
  1374. canEnableTls() {
  1375. if (this.protocol === Protocols.HYSTERIA) return true;
  1376. if (![Protocols.VMESS, Protocols.VLESS, Protocols.TROJAN, Protocols.SHADOWSOCKS].includes(this.protocol)) return false;
  1377. return ["tcp", "ws", "http", "grpc", "httpupgrade", "xhttp"].includes(this.network);
  1378. }
  1379. //this is used for xtls-rprx-vision
  1380. canEnableTlsFlow() {
  1381. if (((this.stream.security === 'tls') || (this.stream.security === 'reality')) && (this.network === "tcp")) {
  1382. return this.protocol === Protocols.VLESS;
  1383. }
  1384. return false;
  1385. }
  1386. // Vision seed applies only when vision flow is selected
  1387. canEnableVisionSeed() {
  1388. if (!this.canEnableTlsFlow()) return false;
  1389. const clients = this.settings?.vlesses;
  1390. if (!Array.isArray(clients)) return false;
  1391. return clients.some(c => c?.flow === TLS_FLOW_CONTROL.VISION || c?.flow === TLS_FLOW_CONTROL.VISION_UDP443);
  1392. }
  1393. canEnableReality() {
  1394. if (![Protocols.VLESS, Protocols.TROJAN].includes(this.protocol)) return false;
  1395. return ["tcp", "http", "grpc", "xhttp"].includes(this.network);
  1396. }
  1397. canEnableStream() {
  1398. return [Protocols.VMESS, Protocols.VLESS, Protocols.TROJAN, Protocols.SHADOWSOCKS, Protocols.HYSTERIA].includes(this.protocol);
  1399. }
  1400. reset() {
  1401. this.port = RandomUtil.randomInteger(10000, 60000);
  1402. this.listen = '';
  1403. this.protocol = Protocols.VMESS;
  1404. this.settings = Inbound.Settings.getSettings(Protocols.VMESS);
  1405. this.stream = new StreamSettings();
  1406. this.tag = '';
  1407. this.sniffing = new Sniffing();
  1408. }
  1409. genVmessLink(address = '', port = this.port, forceTls, remark = '', clientId, security) {
  1410. if (this.protocol !== Protocols.VMESS) {
  1411. return '';
  1412. }
  1413. const tls = forceTls == 'same' ? this.stream.security : forceTls;
  1414. let obj = {
  1415. v: '2',
  1416. ps: remark,
  1417. add: address,
  1418. port: port,
  1419. id: clientId,
  1420. scy: security,
  1421. net: this.stream.network,
  1422. tls: tls,
  1423. };
  1424. const network = this.stream.network;
  1425. if (network === 'tcp') {
  1426. const tcp = this.stream.tcp;
  1427. obj.type = tcp.type;
  1428. if (tcp.type === 'http') {
  1429. const request = tcp.request;
  1430. obj.path = request.path.join(',');
  1431. const host = this.getHeader(request, 'host');
  1432. if (host) obj.host = host;
  1433. }
  1434. } else if (network === 'kcp') {
  1435. const kcp = this.stream.kcp;
  1436. obj.mtu = kcp.mtu;
  1437. obj.tti = kcp.tti;
  1438. } else if (network === 'ws') {
  1439. const ws = this.stream.ws;
  1440. obj.path = ws.path;
  1441. obj.host = ws.host?.length > 0 ? ws.host : this.getHeader(ws, 'host');
  1442. } else if (network === 'grpc') {
  1443. obj.path = this.stream.grpc.serviceName;
  1444. obj.authority = this.stream.grpc.authority;
  1445. if (this.stream.grpc.multiMode) {
  1446. obj.type = 'multi'
  1447. }
  1448. } else if (network === 'httpupgrade') {
  1449. const httpupgrade = this.stream.httpupgrade;
  1450. obj.path = httpupgrade.path;
  1451. obj.host = httpupgrade.host?.length > 0 ? httpupgrade.host : this.getHeader(httpupgrade, 'host');
  1452. } else if (network === 'xhttp') {
  1453. const xhttp = this.stream.xhttp;
  1454. obj.path = xhttp.path;
  1455. obj.host = xhttp.host?.length > 0 ? xhttp.host : this.getHeader(xhttp, 'host');
  1456. obj.type = xhttp.mode;
  1457. Inbound.applyXhttpPaddingToObj(xhttp, obj);
  1458. }
  1459. if (tls === 'tls') {
  1460. if (!ObjectUtil.isEmpty(this.stream.tls.sni)) {
  1461. obj.sni = this.stream.tls.sni;
  1462. }
  1463. if (!ObjectUtil.isEmpty(this.stream.tls.settings.fingerprint)) {
  1464. obj.fp = this.stream.tls.settings.fingerprint;
  1465. }
  1466. if (this.stream.tls.alpn.length > 0) {
  1467. obj.alpn = this.stream.tls.alpn.join(',');
  1468. }
  1469. }
  1470. return 'vmess://' + Base64.encode(JSON.stringify(obj, null, 2));
  1471. }
  1472. genVLESSLink(address = '', port = this.port, forceTls, remark = '', clientId, flow) {
  1473. const uuid = clientId;
  1474. const type = this.stream.network;
  1475. const security = forceTls == 'same' ? this.stream.security : forceTls;
  1476. const params = new Map();
  1477. params.set("type", this.stream.network);
  1478. params.set("encryption", this.settings.encryption);
  1479. switch (type) {
  1480. case "tcp":
  1481. const tcp = this.stream.tcp;
  1482. if (tcp.type === 'http') {
  1483. const request = tcp.request;
  1484. params.set("path", request.path.join(','));
  1485. const index = request.headers.findIndex(header => header.name.toLowerCase() === 'host');
  1486. if (index >= 0) {
  1487. const host = request.headers[index].value;
  1488. params.set("host", host);
  1489. }
  1490. params.set("headerType", 'http');
  1491. }
  1492. break;
  1493. case "kcp":
  1494. const kcp = this.stream.kcp;
  1495. params.set("mtu", kcp.mtu);
  1496. params.set("tti", kcp.tti);
  1497. break;
  1498. case "ws":
  1499. const ws = this.stream.ws;
  1500. params.set("path", ws.path);
  1501. params.set("host", ws.host?.length > 0 ? ws.host : this.getHeader(ws, 'host'));
  1502. break;
  1503. case "grpc":
  1504. const grpc = this.stream.grpc;
  1505. params.set("serviceName", grpc.serviceName);
  1506. params.set("authority", grpc.authority);
  1507. if (grpc.multiMode) {
  1508. params.set("mode", "multi");
  1509. }
  1510. break;
  1511. case "httpupgrade":
  1512. const httpupgrade = this.stream.httpupgrade;
  1513. params.set("path", httpupgrade.path);
  1514. params.set("host", httpupgrade.host?.length > 0 ? httpupgrade.host : this.getHeader(httpupgrade, 'host'));
  1515. break;
  1516. case "xhttp":
  1517. const xhttp = this.stream.xhttp;
  1518. params.set("path", xhttp.path);
  1519. params.set("host", xhttp.host?.length > 0 ? xhttp.host : this.getHeader(xhttp, 'host'));
  1520. params.set("mode", xhttp.mode);
  1521. Inbound.applyXhttpPaddingToParams(xhttp, params);
  1522. break;
  1523. }
  1524. if (security === 'tls') {
  1525. params.set("security", "tls");
  1526. if (this.stream.isTls) {
  1527. params.set("fp", this.stream.tls.settings.fingerprint);
  1528. params.set("alpn", this.stream.tls.alpn);
  1529. if (!ObjectUtil.isEmpty(this.stream.tls.sni)) {
  1530. params.set("sni", this.stream.tls.sni);
  1531. }
  1532. if (this.stream.tls.settings.echConfigList?.length > 0) {
  1533. params.set("ech", this.stream.tls.settings.echConfigList);
  1534. }
  1535. if (type == "tcp" && !ObjectUtil.isEmpty(flow)) {
  1536. params.set("flow", flow);
  1537. }
  1538. }
  1539. }
  1540. else if (security === 'reality') {
  1541. params.set("security", "reality");
  1542. params.set("pbk", this.stream.reality.settings.publicKey);
  1543. params.set("fp", this.stream.reality.settings.fingerprint);
  1544. if (!ObjectUtil.isArrEmpty(this.stream.reality.serverNames)) {
  1545. params.set("sni", this.stream.reality.serverNames.split(",")[0]);
  1546. }
  1547. if (this.stream.reality.shortIds.length > 0) {
  1548. params.set("sid", this.stream.reality.shortIds.split(",")[0]);
  1549. }
  1550. if (!ObjectUtil.isEmpty(this.stream.reality.settings.spiderX)) {
  1551. params.set("spx", this.stream.reality.settings.spiderX);
  1552. }
  1553. if (!ObjectUtil.isEmpty(this.stream.reality.settings.mldsa65Verify)) {
  1554. params.set("pqv", this.stream.reality.settings.mldsa65Verify);
  1555. }
  1556. if (type == 'tcp' && !ObjectUtil.isEmpty(flow)) {
  1557. params.set("flow", flow);
  1558. }
  1559. }
  1560. else {
  1561. params.set("security", "none");
  1562. }
  1563. const link = `vless://${uuid}@${address}:${port}`;
  1564. const url = new URL(link);
  1565. for (const [key, value] of params) {
  1566. url.searchParams.set(key, value)
  1567. }
  1568. url.hash = encodeURIComponent(remark);
  1569. return url.toString();
  1570. }
  1571. genSSLink(address = '', port = this.port, forceTls, remark = '', clientPassword) {
  1572. let settings = this.settings;
  1573. const type = this.stream.network;
  1574. const security = forceTls == 'same' ? this.stream.security : forceTls;
  1575. const params = new Map();
  1576. params.set("type", this.stream.network);
  1577. switch (type) {
  1578. case "tcp":
  1579. const tcp = this.stream.tcp;
  1580. if (tcp.type === 'http') {
  1581. const request = tcp.request;
  1582. params.set("path", request.path.join(','));
  1583. const index = request.headers.findIndex(header => header.name.toLowerCase() === 'host');
  1584. if (index >= 0) {
  1585. const host = request.headers[index].value;
  1586. params.set("host", host);
  1587. }
  1588. params.set("headerType", 'http');
  1589. }
  1590. break;
  1591. case "kcp":
  1592. const kcp = this.stream.kcp;
  1593. params.set("mtu", kcp.mtu);
  1594. params.set("tti", kcp.tti);
  1595. break;
  1596. case "ws":
  1597. const ws = this.stream.ws;
  1598. params.set("path", ws.path);
  1599. params.set("host", ws.host?.length > 0 ? ws.host : this.getHeader(ws, 'host'));
  1600. break;
  1601. case "grpc":
  1602. const grpc = this.stream.grpc;
  1603. params.set("serviceName", grpc.serviceName);
  1604. params.set("authority", grpc.authority);
  1605. if (grpc.multiMode) {
  1606. params.set("mode", "multi");
  1607. }
  1608. break;
  1609. case "httpupgrade":
  1610. const httpupgrade = this.stream.httpupgrade;
  1611. params.set("path", httpupgrade.path);
  1612. params.set("host", httpupgrade.host?.length > 0 ? httpupgrade.host : this.getHeader(httpupgrade, 'host'));
  1613. break;
  1614. case "xhttp":
  1615. const xhttp = this.stream.xhttp;
  1616. params.set("path", xhttp.path);
  1617. params.set("host", xhttp.host?.length > 0 ? xhttp.host : this.getHeader(xhttp, 'host'));
  1618. params.set("mode", xhttp.mode);
  1619. Inbound.applyXhttpPaddingToParams(xhttp, params);
  1620. break;
  1621. }
  1622. if (security === 'tls') {
  1623. params.set("security", "tls");
  1624. if (this.stream.isTls) {
  1625. params.set("fp", this.stream.tls.settings.fingerprint);
  1626. params.set("alpn", this.stream.tls.alpn);
  1627. if (this.stream.tls.settings.echConfigList?.length > 0) {
  1628. params.set("ech", this.stream.tls.settings.echConfigList);
  1629. }
  1630. if (!ObjectUtil.isEmpty(this.stream.tls.sni)) {
  1631. params.set("sni", this.stream.tls.sni);
  1632. }
  1633. }
  1634. }
  1635. let password = new Array();
  1636. if (this.isSS2022) password.push(settings.password);
  1637. if (this.isSSMultiUser) password.push(clientPassword);
  1638. let link = `ss://${Base64.encode(`${settings.method}:${password.join(':')}`, true)}@${address}:${port}`;
  1639. const url = new URL(link);
  1640. for (const [key, value] of params) {
  1641. url.searchParams.set(key, value)
  1642. }
  1643. url.hash = encodeURIComponent(remark);
  1644. return url.toString();
  1645. }
  1646. genTrojanLink(address = '', port = this.port, forceTls, remark = '', clientPassword) {
  1647. const security = forceTls == 'same' ? this.stream.security : forceTls;
  1648. const type = this.stream.network;
  1649. const params = new Map();
  1650. params.set("type", this.stream.network);
  1651. switch (type) {
  1652. case "tcp":
  1653. const tcp = this.stream.tcp;
  1654. if (tcp.type === 'http') {
  1655. const request = tcp.request;
  1656. params.set("path", request.path.join(','));
  1657. const index = request.headers.findIndex(header => header.name.toLowerCase() === 'host');
  1658. if (index >= 0) {
  1659. const host = request.headers[index].value;
  1660. params.set("host", host);
  1661. }
  1662. params.set("headerType", 'http');
  1663. }
  1664. break;
  1665. case "kcp":
  1666. const kcp = this.stream.kcp;
  1667. params.set("mtu", kcp.mtu);
  1668. params.set("tti", kcp.tti);
  1669. break;
  1670. case "ws":
  1671. const ws = this.stream.ws;
  1672. params.set("path", ws.path);
  1673. params.set("host", ws.host?.length > 0 ? ws.host : this.getHeader(ws, 'host'));
  1674. break;
  1675. case "grpc":
  1676. const grpc = this.stream.grpc;
  1677. params.set("serviceName", grpc.serviceName);
  1678. params.set("authority", grpc.authority);
  1679. if (grpc.multiMode) {
  1680. params.set("mode", "multi");
  1681. }
  1682. break;
  1683. case "httpupgrade":
  1684. const httpupgrade = this.stream.httpupgrade;
  1685. params.set("path", httpupgrade.path);
  1686. params.set("host", httpupgrade.host?.length > 0 ? httpupgrade.host : this.getHeader(httpupgrade, 'host'));
  1687. break;
  1688. case "xhttp":
  1689. const xhttp = this.stream.xhttp;
  1690. params.set("path", xhttp.path);
  1691. params.set("host", xhttp.host?.length > 0 ? xhttp.host : this.getHeader(xhttp, 'host'));
  1692. params.set("mode", xhttp.mode);
  1693. Inbound.applyXhttpPaddingToParams(xhttp, params);
  1694. break;
  1695. }
  1696. if (security === 'tls') {
  1697. params.set("security", "tls");
  1698. if (this.stream.isTls) {
  1699. params.set("fp", this.stream.tls.settings.fingerprint);
  1700. params.set("alpn", this.stream.tls.alpn);
  1701. if (this.stream.tls.settings.echConfigList?.length > 0) {
  1702. params.set("ech", this.stream.tls.settings.echConfigList);
  1703. }
  1704. if (!ObjectUtil.isEmpty(this.stream.tls.sni)) {
  1705. params.set("sni", this.stream.tls.sni);
  1706. }
  1707. }
  1708. }
  1709. else if (security === 'reality') {
  1710. params.set("security", "reality");
  1711. params.set("pbk", this.stream.reality.settings.publicKey);
  1712. params.set("fp", this.stream.reality.settings.fingerprint);
  1713. if (!ObjectUtil.isArrEmpty(this.stream.reality.serverNames)) {
  1714. params.set("sni", this.stream.reality.serverNames.split(",")[0]);
  1715. }
  1716. if (this.stream.reality.shortIds.length > 0) {
  1717. params.set("sid", this.stream.reality.shortIds.split(",")[0]);
  1718. }
  1719. if (!ObjectUtil.isEmpty(this.stream.reality.settings.spiderX)) {
  1720. params.set("spx", this.stream.reality.settings.spiderX);
  1721. }
  1722. if (!ObjectUtil.isEmpty(this.stream.reality.settings.mldsa65Verify)) {
  1723. params.set("pqv", this.stream.reality.settings.mldsa65Verify);
  1724. }
  1725. }
  1726. else {
  1727. params.set("security", "none");
  1728. }
  1729. const link = `trojan://${clientPassword}@${address}:${port}`;
  1730. const url = new URL(link);
  1731. for (const [key, value] of params) {
  1732. url.searchParams.set(key, value)
  1733. }
  1734. url.hash = encodeURIComponent(remark);
  1735. return url.toString();
  1736. }
  1737. genHysteriaLink(address = '', port = this.port, remark = '', clientAuth) {
  1738. const protocol = this.settings.version == 2 ? "hysteria2" : "hysteria";
  1739. const link = `${protocol}://${clientAuth}@${address}:${port}`;
  1740. const params = new Map();
  1741. params.set("security", "tls");
  1742. if (this.stream.tls.settings.fingerprint?.length > 0) params.set("fp", this.stream.tls.settings.fingerprint);
  1743. if (this.stream.tls.alpn?.length > 0) params.set("alpn", this.stream.tls.alpn);
  1744. if (this.stream.tls.settings.allowInsecure) params.set("insecure", "1");
  1745. if (this.stream.tls.settings.echConfigList?.length > 0) params.set("ech", this.stream.tls.settings.echConfigList);
  1746. if (this.stream.tls.sni?.length > 0) params.set("sni", this.stream.tls.sni);
  1747. const udpMasks = this.stream?.finalmask?.udp;
  1748. if (Array.isArray(udpMasks)) {
  1749. const salamanderMask = udpMasks.find(mask => mask?.type === 'salamander');
  1750. const obfsPassword = salamanderMask?.settings?.password;
  1751. if (typeof obfsPassword === 'string' && obfsPassword.length > 0) {
  1752. params.set("obfs", "salamander");
  1753. params.set("obfs-password", obfsPassword);
  1754. }
  1755. }
  1756. const url = new URL(link);
  1757. for (const [key, value] of params) {
  1758. url.searchParams.set(key, value);
  1759. }
  1760. url.hash = encodeURIComponent(remark);
  1761. return url.toString();
  1762. }
  1763. getWireguardTxt(address, port, remark, peerId) {
  1764. let txt = `[Interface]\n`
  1765. txt += `PrivateKey = ${this.settings.peers[peerId].privateKey}\n`
  1766. txt += `Address = ${this.settings.peers[peerId].allowedIPs[0]}\n`
  1767. txt += `DNS = 1.1.1.1, 1.0.0.1\n`
  1768. if (this.settings.mtu) {
  1769. txt += `MTU = ${this.settings.mtu}\n`
  1770. }
  1771. txt += `\n# ${remark}\n`
  1772. txt += `[Peer]\n`
  1773. txt += `PublicKey = ${this.settings.pubKey}\n`
  1774. txt += `AllowedIPs = 0.0.0.0/0, ::/0\n`
  1775. txt += `Endpoint = ${address}:${port}`
  1776. if (this.settings.peers[peerId].psk) {
  1777. txt += `\nPresharedKey = ${this.settings.peers[peerId].psk}`
  1778. }
  1779. if (this.settings.peers[peerId].keepAlive) {
  1780. txt += `\nPersistentKeepalive = ${this.settings.peers[peerId].keepAlive}\n`
  1781. }
  1782. return txt;
  1783. }
  1784. getWireguardLink(address, port, remark, peerId) {
  1785. const peer = this.settings?.peers?.[peerId];
  1786. if (!peer) return '';
  1787. const link = `wireguard://${address}:${port}`;
  1788. const url = new URL(link);
  1789. url.username = peer.privateKey || '';
  1790. if (this.settings?.pubKey) {
  1791. url.searchParams.set("publickey", this.settings.pubKey);
  1792. }
  1793. if (Array.isArray(peer.allowedIPs) && peer.allowedIPs.length > 0 && peer.allowedIPs[0]) {
  1794. url.searchParams.set("address", peer.allowedIPs[0]);
  1795. }
  1796. if (this.settings?.mtu) {
  1797. url.searchParams.set("mtu", this.settings.mtu);
  1798. }
  1799. url.hash = encodeURIComponent(remark);
  1800. return url.toString();
  1801. }
  1802. genWireguardLinks(remark = '', remarkModel = '-ieo') {
  1803. const addr = !ObjectUtil.isEmpty(this.listen) && this.listen !== "0.0.0.0" ? this.listen : location.hostname;
  1804. const separationChar = remarkModel.charAt(0);
  1805. let links = [];
  1806. this.settings.peers.forEach((p, index) => {
  1807. links.push(this.getWireguardLink(addr, this.port, remark + separationChar + (index + 1), index));
  1808. });
  1809. return links.join('\r\n');
  1810. }
  1811. genWireguardConfigs(remark = '', remarkModel = '-ieo') {
  1812. const addr = !ObjectUtil.isEmpty(this.listen) && this.listen !== "0.0.0.0" ? this.listen : location.hostname;
  1813. const separationChar = remarkModel.charAt(0);
  1814. let links = [];
  1815. this.settings.peers.forEach((p, index) => {
  1816. links.push(this.getWireguardTxt(addr, this.port, remark + separationChar + (index + 1), index));
  1817. });
  1818. return links.join('\r\n');
  1819. }
  1820. genLink(address = '', port = this.port, forceTls = 'same', remark = '', client) {
  1821. switch (this.protocol) {
  1822. case Protocols.VMESS:
  1823. return this.genVmessLink(address, port, forceTls, remark, client.id, client.security);
  1824. case Protocols.VLESS:
  1825. return this.genVLESSLink(address, port, forceTls, remark, client.id, client.flow);
  1826. case Protocols.SHADOWSOCKS:
  1827. return this.genSSLink(address, port, forceTls, remark, this.isSSMultiUser ? client.password : '');
  1828. case Protocols.TROJAN:
  1829. return this.genTrojanLink(address, port, forceTls, remark, client.password);
  1830. case Protocols.HYSTERIA:
  1831. return this.genHysteriaLink(address, port, remark, client.auth.length > 0 ? client.auth : this.stream.hysteria.auth);
  1832. default: return '';
  1833. }
  1834. }
  1835. genAllLinks(remark = '', remarkModel = '-ieo', client) {
  1836. let result = [];
  1837. let email = client ? client.email : '';
  1838. let addr = !ObjectUtil.isEmpty(this.listen) && this.listen !== "0.0.0.0" ? this.listen : location.hostname;
  1839. let port = this.port;
  1840. const separationChar = remarkModel.charAt(0);
  1841. const orderChars = remarkModel.slice(1);
  1842. let orders = {
  1843. 'i': remark,
  1844. 'e': email,
  1845. 'o': '',
  1846. };
  1847. if (ObjectUtil.isArrEmpty(this.stream.externalProxy)) {
  1848. let r = orderChars.split('').map(char => orders[char]).filter(x => x.length > 0).join(separationChar);
  1849. result.push({
  1850. remark: r,
  1851. link: this.genLink(addr, port, 'same', r, client)
  1852. });
  1853. } else {
  1854. this.stream.externalProxy.forEach((ep) => {
  1855. orders['o'] = ep.remark;
  1856. let r = orderChars.split('').map(char => orders[char]).filter(x => x.length > 0).join(separationChar);
  1857. result.push({
  1858. remark: r,
  1859. link: this.genLink(ep.dest, ep.port, ep.forceTls, r, client)
  1860. });
  1861. });
  1862. }
  1863. return result;
  1864. }
  1865. genInboundLinks(remark = '', remarkModel = '-ieo') {
  1866. let addr = !ObjectUtil.isEmpty(this.listen) && this.listen !== "0.0.0.0" ? this.listen : location.hostname;
  1867. if (this.clients) {
  1868. let links = [];
  1869. this.clients.forEach((client) => {
  1870. this.genAllLinks(remark, remarkModel, client).forEach(l => {
  1871. links.push(l.link);
  1872. })
  1873. });
  1874. return links.join('\r\n');
  1875. } else {
  1876. if (this.protocol == Protocols.SHADOWSOCKS && !this.isSSMultiUser) return this.genSSLink(addr, this.port, 'same', remark);
  1877. if (this.protocol == Protocols.WIREGUARD) {
  1878. return this.genWireguardConfigs(remark, remarkModel);
  1879. }
  1880. return '';
  1881. }
  1882. }
  1883. static fromJson(json = {}) {
  1884. return new Inbound(
  1885. json.port,
  1886. json.listen,
  1887. json.protocol,
  1888. Inbound.Settings.fromJson(json.protocol, json.settings),
  1889. StreamSettings.fromJson(json.streamSettings),
  1890. json.tag,
  1891. Sniffing.fromJson(json.sniffing),
  1892. json.clientStats
  1893. )
  1894. }
  1895. toJson() {
  1896. let streamSettings;
  1897. if (this.canEnableStream() || this.stream?.sockopt) {
  1898. streamSettings = this.stream.toJson();
  1899. }
  1900. return {
  1901. port: this.port,
  1902. listen: this.listen,
  1903. protocol: this.protocol,
  1904. settings: this.settings instanceof XrayCommonClass ? this.settings.toJson() : this.settings,
  1905. streamSettings: streamSettings,
  1906. tag: this.tag,
  1907. sniffing: this.sniffing.toJson(),
  1908. clientStats: this.clientStats
  1909. };
  1910. }
  1911. }
  1912. Inbound.Settings = class extends XrayCommonClass {
  1913. constructor(protocol) {
  1914. super();
  1915. this.protocol = protocol;
  1916. }
  1917. static getSettings(protocol) {
  1918. switch (protocol) {
  1919. case Protocols.VMESS: return new Inbound.VmessSettings(protocol);
  1920. case Protocols.VLESS: return new Inbound.VLESSSettings(protocol);
  1921. case Protocols.TROJAN: return new Inbound.TrojanSettings(protocol);
  1922. case Protocols.SHADOWSOCKS: return new Inbound.ShadowsocksSettings(protocol);
  1923. case Protocols.TUNNEL: return new Inbound.TunnelSettings(protocol);
  1924. case Protocols.MIXED: return new Inbound.MixedSettings(protocol);
  1925. case Protocols.HTTP: return new Inbound.HttpSettings(protocol);
  1926. case Protocols.WIREGUARD: return new Inbound.WireguardSettings(protocol);
  1927. case Protocols.TUN: return new Inbound.TunSettings(protocol);
  1928. case Protocols.HYSTERIA: return new Inbound.HysteriaSettings(protocol);
  1929. default: return null;
  1930. }
  1931. }
  1932. static fromJson(protocol, json) {
  1933. switch (protocol) {
  1934. case Protocols.VMESS: return Inbound.VmessSettings.fromJson(json);
  1935. case Protocols.VLESS: return Inbound.VLESSSettings.fromJson(json);
  1936. case Protocols.TROJAN: return Inbound.TrojanSettings.fromJson(json);
  1937. case Protocols.SHADOWSOCKS: return Inbound.ShadowsocksSettings.fromJson(json);
  1938. case Protocols.TUNNEL: return Inbound.TunnelSettings.fromJson(json);
  1939. case Protocols.MIXED: return Inbound.MixedSettings.fromJson(json);
  1940. case Protocols.HTTP: return Inbound.HttpSettings.fromJson(json);
  1941. case Protocols.WIREGUARD: return Inbound.WireguardSettings.fromJson(json);
  1942. case Protocols.TUN: return Inbound.TunSettings.fromJson(json);
  1943. case Protocols.HYSTERIA: return Inbound.HysteriaSettings.fromJson(json);
  1944. default: return null;
  1945. }
  1946. }
  1947. toJson() {
  1948. return {};
  1949. }
  1950. };
  1951. /** Shared user-quota fields and UI helpers for multi-user protocol clients. */
  1952. Inbound.ClientBase = class extends XrayCommonClass {
  1953. constructor(
  1954. email = RandomUtil.randomLowerAndNum(8),
  1955. limitIp = 0,
  1956. totalGB = 0,
  1957. expiryTime = 0,
  1958. enable = true,
  1959. tgId = '',
  1960. subId = RandomUtil.randomLowerAndNum(16),
  1961. comment = '',
  1962. reset = 0,
  1963. created_at = undefined,
  1964. updated_at = undefined,
  1965. ) {
  1966. super();
  1967. this.email = email;
  1968. this.limitIp = limitIp;
  1969. this.totalGB = totalGB;
  1970. this.expiryTime = expiryTime;
  1971. this.enable = enable;
  1972. this.tgId = tgId;
  1973. this.subId = subId;
  1974. this.comment = comment;
  1975. this.reset = reset;
  1976. this.created_at = created_at;
  1977. this.updated_at = updated_at;
  1978. }
  1979. static commonArgsFromJson(json = {}) {
  1980. return [
  1981. json.email,
  1982. json.limitIp,
  1983. json.totalGB,
  1984. json.expiryTime,
  1985. json.enable,
  1986. json.tgId,
  1987. json.subId,
  1988. json.comment,
  1989. json.reset,
  1990. json.created_at,
  1991. json.updated_at,
  1992. ];
  1993. }
  1994. _clientBaseToJson() {
  1995. return {
  1996. email: this.email,
  1997. limitIp: this.limitIp,
  1998. totalGB: this.totalGB,
  1999. expiryTime: this.expiryTime,
  2000. enable: this.enable,
  2001. tgId: this.tgId,
  2002. subId: this.subId,
  2003. comment: this.comment,
  2004. reset: this.reset,
  2005. created_at: this.created_at,
  2006. updated_at: this.updated_at,
  2007. };
  2008. }
  2009. get _expiryTime() {
  2010. if (this.expiryTime === 0 || this.expiryTime === '') {
  2011. return null;
  2012. }
  2013. if (this.expiryTime < 0) {
  2014. return this.expiryTime / -86400000;
  2015. }
  2016. return moment(this.expiryTime);
  2017. }
  2018. set _expiryTime(t) {
  2019. if (t == null || t === '') {
  2020. this.expiryTime = 0;
  2021. } else {
  2022. this.expiryTime = t.valueOf();
  2023. }
  2024. }
  2025. get _totalGB() {
  2026. return NumberFormatter.toFixed(this.totalGB / SizeFormatter.ONE_GB, 2);
  2027. }
  2028. set _totalGB(gb) {
  2029. this.totalGB = NumberFormatter.toFixed(gb * SizeFormatter.ONE_GB, 0);
  2030. }
  2031. };
  2032. Inbound.VmessSettings = class extends Inbound.Settings {
  2033. constructor(protocol,
  2034. vmesses = [new Inbound.VmessSettings.VMESS()]) {
  2035. super(protocol);
  2036. this.vmesses = vmesses;
  2037. }
  2038. indexOfVmessById(id) {
  2039. return this.vmesses.findIndex(VMESS => VMESS.id === id);
  2040. }
  2041. addVmess(VMESS) {
  2042. if (this.indexOfVmessById(VMESS.id) >= 0) {
  2043. return false;
  2044. }
  2045. this.vmesses.push(VMESS);
  2046. }
  2047. delVmess(VMESS) {
  2048. const i = this.indexOfVmessById(VMESS.id);
  2049. if (i >= 0) {
  2050. this.vmesses.splice(i, 1);
  2051. }
  2052. }
  2053. static fromJson(json = {}) {
  2054. return new Inbound.VmessSettings(
  2055. Protocols.VMESS,
  2056. (json.clients || []).map(client => Inbound.VmessSettings.VMESS.fromJson(client)),
  2057. );
  2058. }
  2059. toJson() {
  2060. return {
  2061. clients: Inbound.VmessSettings.toJsonArray(this.vmesses),
  2062. };
  2063. }
  2064. };
  2065. Inbound.VmessSettings.VMESS = class extends Inbound.ClientBase {
  2066. constructor(
  2067. id = RandomUtil.randomUUID(),
  2068. security = USERS_SECURITY.AUTO,
  2069. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2070. ) {
  2071. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2072. this.id = id;
  2073. this.security = security;
  2074. }
  2075. static fromJson(json = {}) {
  2076. return new Inbound.VmessSettings.VMESS(
  2077. json.id,
  2078. json.security,
  2079. ...Inbound.ClientBase.commonArgsFromJson(json),
  2080. );
  2081. }
  2082. toJson() {
  2083. return {
  2084. id: this.id,
  2085. security: this.security,
  2086. ...this._clientBaseToJson(),
  2087. };
  2088. }
  2089. };
  2090. Inbound.VLESSSettings = class extends Inbound.Settings {
  2091. constructor(
  2092. protocol,
  2093. vlesses = [new Inbound.VLESSSettings.VLESS()],
  2094. decryption = "none",
  2095. encryption = "none",
  2096. fallbacks = [],
  2097. selectedAuth = undefined,
  2098. testseed = [900, 500, 900, 256],
  2099. ) {
  2100. super(protocol);
  2101. this.vlesses = vlesses;
  2102. this.decryption = decryption;
  2103. this.encryption = encryption;
  2104. this.fallbacks = fallbacks;
  2105. this.selectedAuth = selectedAuth;
  2106. this.testseed = testseed;
  2107. }
  2108. addFallback() {
  2109. this.fallbacks.push(new Inbound.VLESSSettings.Fallback());
  2110. }
  2111. delFallback(index) {
  2112. this.fallbacks.splice(index, 1);
  2113. }
  2114. static fromJson(json = {}) {
  2115. // Ensure testseed is always initialized as an array
  2116. let testseed = [900, 500, 900, 256];
  2117. if (json.testseed && Array.isArray(json.testseed) && json.testseed.length >= 4) {
  2118. testseed = json.testseed;
  2119. }
  2120. const obj = new Inbound.VLESSSettings(
  2121. Protocols.VLESS,
  2122. (json.clients || []).map(client => Inbound.VLESSSettings.VLESS.fromJson(client)),
  2123. json.decryption,
  2124. json.encryption,
  2125. Inbound.VLESSSettings.Fallback.fromJson(json.fallbacks || []),
  2126. json.selectedAuth,
  2127. testseed
  2128. );
  2129. return obj;
  2130. }
  2131. toJson() {
  2132. const json = {
  2133. clients: Inbound.VLESSSettings.toJsonArray(this.vlesses),
  2134. };
  2135. if (this.decryption) {
  2136. json.decryption = this.decryption;
  2137. }
  2138. if (this.encryption) {
  2139. json.encryption = this.encryption;
  2140. }
  2141. if (this.fallbacks && this.fallbacks.length > 0) {
  2142. json.fallbacks = Inbound.VLESSSettings.toJsonArray(this.fallbacks);
  2143. }
  2144. if (this.selectedAuth) {
  2145. json.selectedAuth = this.selectedAuth;
  2146. }
  2147. // Only include testseed if at least one client has a flow set
  2148. const hasFlow = this.vlesses && this.vlesses.some(vless => vless.flow && vless.flow !== '');
  2149. if (hasFlow && this.testseed && this.testseed.length >= 4) {
  2150. json.testseed = this.testseed;
  2151. }
  2152. return json;
  2153. }
  2154. };
  2155. Inbound.VLESSSettings.VLESS = class extends Inbound.ClientBase {
  2156. constructor(
  2157. id = RandomUtil.randomUUID(),
  2158. flow = '',
  2159. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2160. ) {
  2161. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2162. this.id = id;
  2163. this.flow = flow;
  2164. }
  2165. static fromJson(json = {}) {
  2166. return new Inbound.VLESSSettings.VLESS(
  2167. json.id,
  2168. json.flow,
  2169. ...Inbound.ClientBase.commonArgsFromJson(json),
  2170. );
  2171. }
  2172. toJson() {
  2173. return {
  2174. id: this.id,
  2175. flow: this.flow,
  2176. ...this._clientBaseToJson(),
  2177. };
  2178. }
  2179. };
  2180. Inbound.VLESSSettings.Fallback = class extends XrayCommonClass {
  2181. constructor(name = "", alpn = '', path = '', dest = '', xver = 0) {
  2182. super();
  2183. this.name = name;
  2184. this.alpn = alpn;
  2185. this.path = path;
  2186. this.dest = dest;
  2187. this.xver = xver;
  2188. }
  2189. toJson() {
  2190. let xver = this.xver;
  2191. if (!Number.isInteger(xver)) {
  2192. xver = 0;
  2193. }
  2194. return {
  2195. name: this.name,
  2196. alpn: this.alpn,
  2197. path: this.path,
  2198. dest: this.dest,
  2199. xver: xver,
  2200. }
  2201. }
  2202. static fromJson(json = []) {
  2203. const fallbacks = [];
  2204. for (let fallback of json) {
  2205. fallbacks.push(new Inbound.VLESSSettings.Fallback(
  2206. fallback.name,
  2207. fallback.alpn,
  2208. fallback.path,
  2209. fallback.dest,
  2210. fallback.xver,
  2211. ))
  2212. }
  2213. return fallbacks;
  2214. }
  2215. };
  2216. Inbound.TrojanSettings = class extends Inbound.Settings {
  2217. constructor(protocol,
  2218. trojans = [new Inbound.TrojanSettings.Trojan()],
  2219. fallbacks = [],) {
  2220. super(protocol);
  2221. this.trojans = trojans;
  2222. this.fallbacks = fallbacks;
  2223. }
  2224. addFallback() {
  2225. this.fallbacks.push(new Inbound.TrojanSettings.Fallback());
  2226. }
  2227. delFallback(index) {
  2228. this.fallbacks.splice(index, 1);
  2229. }
  2230. static fromJson(json = {}) {
  2231. return new Inbound.TrojanSettings(
  2232. Protocols.TROJAN,
  2233. (json.clients || []).map(client => Inbound.TrojanSettings.Trojan.fromJson(client)),
  2234. Inbound.TrojanSettings.Fallback.fromJson(json.fallbacks),);
  2235. }
  2236. toJson() {
  2237. return {
  2238. clients: Inbound.TrojanSettings.toJsonArray(this.trojans),
  2239. fallbacks: Inbound.TrojanSettings.toJsonArray(this.fallbacks)
  2240. };
  2241. }
  2242. };
  2243. Inbound.TrojanSettings.Trojan = class extends Inbound.ClientBase {
  2244. constructor(
  2245. password = RandomUtil.randomSeq(10),
  2246. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2247. ) {
  2248. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2249. this.password = password;
  2250. }
  2251. toJson() {
  2252. return {
  2253. password: this.password,
  2254. ...this._clientBaseToJson(),
  2255. };
  2256. }
  2257. static fromJson(json = {}) {
  2258. return new Inbound.TrojanSettings.Trojan(
  2259. json.password,
  2260. ...Inbound.ClientBase.commonArgsFromJson(json),
  2261. );
  2262. }
  2263. };
  2264. Inbound.TrojanSettings.Fallback = class extends XrayCommonClass {
  2265. constructor(name = "", alpn = '', path = '', dest = '', xver = 0) {
  2266. super();
  2267. this.name = name;
  2268. this.alpn = alpn;
  2269. this.path = path;
  2270. this.dest = dest;
  2271. this.xver = xver;
  2272. }
  2273. toJson() {
  2274. let xver = this.xver;
  2275. if (!Number.isInteger(xver)) {
  2276. xver = 0;
  2277. }
  2278. return {
  2279. name: this.name,
  2280. alpn: this.alpn,
  2281. path: this.path,
  2282. dest: this.dest,
  2283. xver: xver,
  2284. }
  2285. }
  2286. static fromJson(json = []) {
  2287. const fallbacks = [];
  2288. for (let fallback of json) {
  2289. fallbacks.push(new Inbound.TrojanSettings.Fallback(
  2290. fallback.name,
  2291. fallback.alpn,
  2292. fallback.path,
  2293. fallback.dest,
  2294. fallback.xver,
  2295. ))
  2296. }
  2297. return fallbacks;
  2298. }
  2299. };
  2300. Inbound.ShadowsocksSettings = class extends Inbound.Settings {
  2301. constructor(protocol,
  2302. method = SSMethods.BLAKE3_AES_256_GCM,
  2303. password = RandomUtil.randomShadowsocksPassword(),
  2304. network = 'tcp,udp',
  2305. shadowsockses = [new Inbound.ShadowsocksSettings.Shadowsocks()],
  2306. ivCheck = false,
  2307. ) {
  2308. super(protocol);
  2309. this.method = method;
  2310. this.password = password;
  2311. this.network = network;
  2312. this.shadowsockses = shadowsockses;
  2313. this.ivCheck = ivCheck;
  2314. }
  2315. static fromJson(json = {}) {
  2316. return new Inbound.ShadowsocksSettings(
  2317. Protocols.SHADOWSOCKS,
  2318. json.method,
  2319. json.password,
  2320. json.network,
  2321. (json.clients || []).map(client => Inbound.ShadowsocksSettings.Shadowsocks.fromJson(client)),
  2322. json.ivCheck,
  2323. );
  2324. }
  2325. toJson() {
  2326. return {
  2327. method: this.method,
  2328. password: this.password,
  2329. network: this.network,
  2330. clients: Inbound.ShadowsocksSettings.toJsonArray(this.shadowsockses),
  2331. ivCheck: this.ivCheck,
  2332. };
  2333. }
  2334. };
  2335. Inbound.ShadowsocksSettings.Shadowsocks = class extends Inbound.ClientBase {
  2336. constructor(
  2337. method = '',
  2338. password = RandomUtil.randomShadowsocksPassword(),
  2339. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2340. ) {
  2341. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2342. this.method = method;
  2343. this.password = password;
  2344. }
  2345. toJson() {
  2346. return {
  2347. method: this.method,
  2348. password: this.password,
  2349. ...this._clientBaseToJson(),
  2350. };
  2351. }
  2352. static fromJson(json = {}) {
  2353. return new Inbound.ShadowsocksSettings.Shadowsocks(
  2354. json.method,
  2355. json.password,
  2356. ...Inbound.ClientBase.commonArgsFromJson(json),
  2357. );
  2358. }
  2359. };
  2360. Inbound.HysteriaSettings = class extends Inbound.Settings {
  2361. constructor(protocol, version = 2, hysterias = [new Inbound.HysteriaSettings.Hysteria()]) {
  2362. super(protocol);
  2363. this.version = version;
  2364. this.hysterias = hysterias;
  2365. }
  2366. static fromJson(json = {}) {
  2367. return new Inbound.HysteriaSettings(
  2368. Protocols.HYSTERIA,
  2369. json.version ?? 2,
  2370. (json.clients || []).map(client => Inbound.HysteriaSettings.Hysteria.fromJson(client)),
  2371. );
  2372. }
  2373. toJson() {
  2374. return {
  2375. version: this.version,
  2376. clients: Inbound.HysteriaSettings.toJsonArray(this.hysterias),
  2377. };
  2378. }
  2379. };
  2380. Inbound.HysteriaSettings.Hysteria = class extends Inbound.ClientBase {
  2381. constructor(
  2382. auth = RandomUtil.randomSeq(10),
  2383. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2384. ) {
  2385. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2386. this.auth = auth;
  2387. }
  2388. toJson() {
  2389. return {
  2390. auth: this.auth,
  2391. ...this._clientBaseToJson(),
  2392. };
  2393. }
  2394. static fromJson(json = {}) {
  2395. return new Inbound.HysteriaSettings.Hysteria(
  2396. json.auth,
  2397. ...Inbound.ClientBase.commonArgsFromJson(json),
  2398. );
  2399. }
  2400. };
  2401. Inbound.TunnelSettings = class extends Inbound.Settings {
  2402. constructor(
  2403. protocol,
  2404. address,
  2405. port,
  2406. portMap = [],
  2407. network = 'tcp,udp',
  2408. followRedirect = false
  2409. ) {
  2410. super(protocol);
  2411. this.address = address;
  2412. this.port = port;
  2413. this.portMap = portMap;
  2414. this.network = network;
  2415. this.followRedirect = followRedirect;
  2416. }
  2417. static fromJson(json = {}) {
  2418. return new Inbound.TunnelSettings(
  2419. Protocols.TUNNEL,
  2420. json.address,
  2421. json.port,
  2422. XrayCommonClass.toHeaders(json.portMap),
  2423. json.network,
  2424. json.followRedirect,
  2425. );
  2426. }
  2427. toJson() {
  2428. return {
  2429. address: this.address,
  2430. port: this.port,
  2431. portMap: XrayCommonClass.toV2Headers(this.portMap, false),
  2432. network: this.network,
  2433. followRedirect: this.followRedirect,
  2434. };
  2435. }
  2436. };
  2437. Inbound.MixedSettings = class extends Inbound.Settings {
  2438. constructor(protocol, auth = 'password', accounts = [new Inbound.MixedSettings.SocksAccount()], udp = false, ip = '127.0.0.1') {
  2439. super(protocol);
  2440. this.auth = auth;
  2441. this.accounts = accounts;
  2442. this.udp = udp;
  2443. this.ip = ip;
  2444. }
  2445. addAccount(account) {
  2446. this.accounts.push(account);
  2447. }
  2448. delAccount(index) {
  2449. this.accounts.splice(index, 1);
  2450. }
  2451. static fromJson(json = {}) {
  2452. let accounts;
  2453. if (json.auth === 'password') {
  2454. accounts = json.accounts.map(
  2455. account => Inbound.MixedSettings.SocksAccount.fromJson(account)
  2456. )
  2457. }
  2458. return new Inbound.MixedSettings(
  2459. Protocols.MIXED,
  2460. json.auth,
  2461. accounts,
  2462. json.udp,
  2463. json.ip,
  2464. );
  2465. }
  2466. toJson() {
  2467. return {
  2468. auth: this.auth,
  2469. accounts: this.auth === 'password' ? this.accounts.map(account => account.toJson()) : undefined,
  2470. udp: this.udp,
  2471. ip: this.ip,
  2472. };
  2473. }
  2474. };
  2475. Inbound.MixedSettings.SocksAccount = class extends XrayCommonClass {
  2476. constructor(user = RandomUtil.randomSeq(10), pass = RandomUtil.randomSeq(10)) {
  2477. super();
  2478. this.user = user;
  2479. this.pass = pass;
  2480. }
  2481. static fromJson(json = {}) {
  2482. return new Inbound.MixedSettings.SocksAccount(json.user, json.pass);
  2483. }
  2484. };
  2485. Inbound.HttpSettings = class extends Inbound.Settings {
  2486. constructor(
  2487. protocol,
  2488. accounts = [new Inbound.HttpSettings.HttpAccount()],
  2489. allowTransparent = false,
  2490. ) {
  2491. super(protocol);
  2492. this.accounts = accounts;
  2493. this.allowTransparent = allowTransparent;
  2494. }
  2495. addAccount(account) {
  2496. this.accounts.push(account);
  2497. }
  2498. delAccount(index) {
  2499. this.accounts.splice(index, 1);
  2500. }
  2501. static fromJson(json = {}) {
  2502. return new Inbound.HttpSettings(
  2503. Protocols.HTTP,
  2504. json.accounts.map(account => Inbound.HttpSettings.HttpAccount.fromJson(account)),
  2505. json.allowTransparent,
  2506. );
  2507. }
  2508. toJson() {
  2509. return {
  2510. accounts: Inbound.HttpSettings.toJsonArray(this.accounts),
  2511. allowTransparent: this.allowTransparent,
  2512. };
  2513. }
  2514. };
  2515. Inbound.HttpSettings.HttpAccount = class extends XrayCommonClass {
  2516. constructor(user = RandomUtil.randomSeq(10), pass = RandomUtil.randomSeq(10)) {
  2517. super();
  2518. this.user = user;
  2519. this.pass = pass;
  2520. }
  2521. static fromJson(json = {}) {
  2522. return new Inbound.HttpSettings.HttpAccount(json.user, json.pass);
  2523. }
  2524. };
  2525. Inbound.WireguardSettings = class extends XrayCommonClass {
  2526. constructor(
  2527. protocol,
  2528. mtu = 1420,
  2529. secretKey = Wireguard.generateKeypair().privateKey,
  2530. peers = [new Inbound.WireguardSettings.Peer()],
  2531. noKernelTun = false
  2532. ) {
  2533. super(protocol);
  2534. this.mtu = mtu;
  2535. this.secretKey = secretKey;
  2536. this.pubKey = secretKey.length > 0 ? Wireguard.generateKeypair(secretKey).publicKey : '';
  2537. this.peers = peers;
  2538. this.noKernelTun = noKernelTun;
  2539. }
  2540. addPeer() {
  2541. this.peers.push(new Inbound.WireguardSettings.Peer(null, null, '', ['10.0.0.' + (this.peers.length + 2)]));
  2542. }
  2543. delPeer(index) {
  2544. this.peers.splice(index, 1);
  2545. }
  2546. static fromJson(json = {}) {
  2547. return new Inbound.WireguardSettings(
  2548. Protocols.WIREGUARD,
  2549. json.mtu,
  2550. json.secretKey,
  2551. json.peers.map(peer => Inbound.WireguardSettings.Peer.fromJson(peer)),
  2552. json.noKernelTun,
  2553. );
  2554. }
  2555. toJson() {
  2556. return {
  2557. mtu: this.mtu ?? undefined,
  2558. secretKey: this.secretKey,
  2559. peers: Inbound.WireguardSettings.Peer.toJsonArray(this.peers),
  2560. noKernelTun: this.noKernelTun,
  2561. };
  2562. }
  2563. };
  2564. Inbound.WireguardSettings.Peer = class extends XrayCommonClass {
  2565. constructor(privateKey, publicKey, psk = '', allowedIPs = ['10.0.0.2/32'], keepAlive = 0) {
  2566. super();
  2567. this.privateKey = privateKey
  2568. this.publicKey = publicKey;
  2569. if (!this.publicKey) {
  2570. [this.publicKey, this.privateKey] = Object.values(Wireguard.generateKeypair())
  2571. }
  2572. this.psk = psk;
  2573. allowedIPs.forEach((a, index) => {
  2574. if (a.length > 0 && !a.includes('/')) allowedIPs[index] += '/32';
  2575. })
  2576. this.allowedIPs = allowedIPs;
  2577. this.keepAlive = keepAlive;
  2578. }
  2579. static fromJson(json = {}) {
  2580. return new Inbound.WireguardSettings.Peer(
  2581. json.privateKey,
  2582. json.publicKey,
  2583. json.preSharedKey,
  2584. json.allowedIPs,
  2585. json.keepAlive
  2586. );
  2587. }
  2588. toJson() {
  2589. this.allowedIPs.forEach((a, index) => {
  2590. if (a.length > 0 && !a.includes('/')) this.allowedIPs[index] += '/32';
  2591. });
  2592. return {
  2593. privateKey: this.privateKey,
  2594. publicKey: this.publicKey,
  2595. preSharedKey: this.psk.length > 0 ? this.psk : undefined,
  2596. allowedIPs: this.allowedIPs,
  2597. keepAlive: this.keepAlive ?? undefined,
  2598. };
  2599. }
  2600. };
  2601. Inbound.TunSettings = class extends Inbound.Settings {
  2602. constructor(
  2603. protocol,
  2604. name = 'xray0',
  2605. mtu = [1500, 1280],
  2606. gateway = [],
  2607. dns = [],
  2608. userLevel = 0,
  2609. autoSystemRoutingTable = [],
  2610. autoOutboundsInterface = 'auto'
  2611. ) {
  2612. super(protocol);
  2613. this.name = name;
  2614. this.mtu = this._normalizeMtu(mtu);
  2615. this.gateway = Array.isArray(gateway) ? gateway : [];
  2616. this.dns = Array.isArray(dns) ? dns : [];
  2617. this.userLevel = userLevel;
  2618. this.autoSystemRoutingTable = Array.isArray(autoSystemRoutingTable) ? autoSystemRoutingTable : [];
  2619. this.autoOutboundsInterface = autoOutboundsInterface;
  2620. }
  2621. _normalizeMtu(mtu) {
  2622. if (!Array.isArray(mtu)) {
  2623. const single = Number(mtu) || 1500;
  2624. return [single, single];
  2625. }
  2626. if (mtu.length === 0) {
  2627. return [1500, 1280];
  2628. }
  2629. if (mtu.length === 1) {
  2630. const single = Number(mtu[0]) || 1500;
  2631. return [single, single];
  2632. }
  2633. return [Number(mtu[0]) || 1500, Number(mtu[1]) || 1280];
  2634. }
  2635. static fromJson(json = {}) {
  2636. return new Inbound.TunSettings(
  2637. Protocols.TUN,
  2638. json.name ?? 'xray0',
  2639. json.mtu ?? json.MTU ?? [1500, 1280],
  2640. json.gateway ?? json.Gateway ?? [],
  2641. json.dns ?? json.DNS ?? [],
  2642. json.userLevel ?? 0,
  2643. json.autoSystemRoutingTable ?? [],
  2644. Object.prototype.hasOwnProperty.call(json, 'autoOutboundsInterface') ? json.autoOutboundsInterface : 'auto'
  2645. );
  2646. }
  2647. toJson() {
  2648. return {
  2649. name: this.name || 'xray0',
  2650. mtu: this._normalizeMtu(this.mtu),
  2651. gateway: this.gateway,
  2652. dns: this.dns,
  2653. userLevel: this.userLevel || 0,
  2654. autoSystemRoutingTable: this.autoSystemRoutingTable,
  2655. autoOutboundsInterface: this.autoOutboundsInterface,
  2656. };
  2657. }
  2658. };