inbound.js 89 KB

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