inbound.js 78 KB

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