inbound.js 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797
  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 = 0,
  291. maxSendingWindow = 0,
  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. case 'xdns':
  992. return { domain: settings.domain || '' };
  993. case 'xicmp':
  994. return { ip: settings.ip || '', id: settings.id ?? 0 };
  995. case 'mkcp-original':
  996. case 'header-dtls':
  997. case 'header-srtp':
  998. case 'header-utp':
  999. case 'header-wechat':
  1000. case 'header-wireguard':
  1001. return {};
  1002. case 'header-custom':
  1003. return { client: [], server: [] };
  1004. case 'noise':
  1005. return { reset: 0, noise: [] };
  1006. case 'sudoku':
  1007. return { ascii: '', customTable: '', customTables: [], paddingMin: 0, paddingMax: 0 };
  1008. default:
  1009. return settings;
  1010. }
  1011. }
  1012. static fromJson(json = {}) {
  1013. return new UdpMask(
  1014. json.type || 'salamander',
  1015. json.settings || {}
  1016. );
  1017. }
  1018. toJson() {
  1019. return {
  1020. type: this.type,
  1021. settings: (this.settings && Object.keys(this.settings).length > 0) ? this.settings : undefined
  1022. };
  1023. }
  1024. }
  1025. class FinalMaskStreamSettings extends XrayCommonClass {
  1026. constructor(udp = []) {
  1027. super();
  1028. this.udp = Array.isArray(udp) ? udp.map(u => new UdpMask(u.type, u.settings)) : [new UdpMask(udp.type, udp.settings)];
  1029. }
  1030. static fromJson(json = {}) {
  1031. return new FinalMaskStreamSettings(json.udp || []);
  1032. }
  1033. toJson() {
  1034. return {
  1035. udp: this.udp.map(udp => udp.toJson())
  1036. };
  1037. }
  1038. }
  1039. class StreamSettings extends XrayCommonClass {
  1040. constructor(network = 'tcp',
  1041. security = 'none',
  1042. externalProxy = [],
  1043. tlsSettings = new TlsStreamSettings(),
  1044. realitySettings = new RealityStreamSettings(),
  1045. tcpSettings = new TcpStreamSettings(),
  1046. kcpSettings = new KcpStreamSettings(),
  1047. wsSettings = new WsStreamSettings(),
  1048. grpcSettings = new GrpcStreamSettings(),
  1049. httpupgradeSettings = new HTTPUpgradeStreamSettings(),
  1050. xhttpSettings = new xHTTPStreamSettings(),
  1051. hysteriaSettings = new HysteriaStreamSettings(),
  1052. finalmask = new FinalMaskStreamSettings(),
  1053. sockopt = undefined,
  1054. ) {
  1055. super();
  1056. this.network = network;
  1057. this.security = security;
  1058. this.externalProxy = externalProxy;
  1059. this.tls = tlsSettings;
  1060. this.reality = realitySettings;
  1061. this.tcp = tcpSettings;
  1062. this.kcp = kcpSettings;
  1063. this.ws = wsSettings;
  1064. this.grpc = grpcSettings;
  1065. this.httpupgrade = httpupgradeSettings;
  1066. this.xhttp = xhttpSettings;
  1067. this.hysteria = hysteriaSettings;
  1068. this.finalmask = finalmask;
  1069. this.sockopt = sockopt;
  1070. }
  1071. addUdpMask(type = 'salamander') {
  1072. this.finalmask.udp.push(new UdpMask(type));
  1073. }
  1074. delUdpMask(index) {
  1075. if (this.finalmask.udp) {
  1076. this.finalmask.udp.splice(index, 1);
  1077. }
  1078. }
  1079. get hasFinalMask() {
  1080. return this.finalmask.udp && this.finalmask.udp.length > 0;
  1081. }
  1082. get isTls() {
  1083. return this.security === "tls";
  1084. }
  1085. set isTls(isTls) {
  1086. if (isTls) {
  1087. this.security = 'tls';
  1088. } else {
  1089. this.security = 'none';
  1090. }
  1091. }
  1092. //for Reality
  1093. get isReality() {
  1094. return this.security === "reality";
  1095. }
  1096. set isReality(isReality) {
  1097. if (isReality) {
  1098. this.security = 'reality';
  1099. } else {
  1100. this.security = 'none';
  1101. }
  1102. }
  1103. get sockoptSwitch() {
  1104. return this.sockopt != undefined;
  1105. }
  1106. set sockoptSwitch(value) {
  1107. this.sockopt = value ? new SockoptStreamSettings() : undefined;
  1108. }
  1109. static fromJson(json = {}) {
  1110. return new StreamSettings(
  1111. json.network,
  1112. json.security,
  1113. json.externalProxy,
  1114. TlsStreamSettings.fromJson(json.tlsSettings),
  1115. RealityStreamSettings.fromJson(json.realitySettings),
  1116. TcpStreamSettings.fromJson(json.tcpSettings),
  1117. KcpStreamSettings.fromJson(json.kcpSettings),
  1118. WsStreamSettings.fromJson(json.wsSettings),
  1119. GrpcStreamSettings.fromJson(json.grpcSettings),
  1120. HTTPUpgradeStreamSettings.fromJson(json.httpupgradeSettings),
  1121. xHTTPStreamSettings.fromJson(json.xhttpSettings),
  1122. HysteriaStreamSettings.fromJson(json.hysteriaSettings),
  1123. FinalMaskStreamSettings.fromJson(json.finalmask),
  1124. SockoptStreamSettings.fromJson(json.sockopt),
  1125. );
  1126. }
  1127. toJson() {
  1128. const network = this.network;
  1129. return {
  1130. network: network,
  1131. security: this.security,
  1132. externalProxy: this.externalProxy,
  1133. tlsSettings: this.isTls ? this.tls.toJson() : undefined,
  1134. realitySettings: this.isReality ? this.reality.toJson() : undefined,
  1135. tcpSettings: network === 'tcp' ? this.tcp.toJson() : undefined,
  1136. kcpSettings: network === 'kcp' ? this.kcp.toJson() : undefined,
  1137. wsSettings: network === 'ws' ? this.ws.toJson() : undefined,
  1138. grpcSettings: network === 'grpc' ? this.grpc.toJson() : undefined,
  1139. httpupgradeSettings: network === 'httpupgrade' ? this.httpupgrade.toJson() : undefined,
  1140. xhttpSettings: network === 'xhttp' ? this.xhttp.toJson() : undefined,
  1141. hysteriaSettings: network === 'hysteria' ? this.hysteria.toJson() : undefined,
  1142. finalmask: this.hasFinalMask ? this.finalmask.toJson() : undefined,
  1143. sockopt: this.sockopt != undefined ? this.sockopt.toJson() : undefined,
  1144. };
  1145. }
  1146. }
  1147. class Sniffing extends XrayCommonClass {
  1148. constructor(
  1149. enabled = false,
  1150. destOverride = ['http', 'tls', 'quic', 'fakedns'],
  1151. metadataOnly = false,
  1152. routeOnly = false,
  1153. ipsExcluded = [],
  1154. domainsExcluded = []) {
  1155. super();
  1156. this.enabled = enabled;
  1157. this.destOverride = Array.isArray(destOverride) && destOverride.length > 0 ? destOverride : ['http', 'tls', 'quic', 'fakedns'];
  1158. this.metadataOnly = metadataOnly;
  1159. this.routeOnly = routeOnly;
  1160. this.ipsExcluded = Array.isArray(ipsExcluded) ? ipsExcluded : [];
  1161. this.domainsExcluded = Array.isArray(domainsExcluded) ? domainsExcluded : [];
  1162. }
  1163. static fromJson(json = {}) {
  1164. let destOverride = ObjectUtil.clone(json.destOverride);
  1165. if (ObjectUtil.isEmpty(destOverride) || ObjectUtil.isArrEmpty(destOverride) || ObjectUtil.isEmpty(destOverride[0])) {
  1166. destOverride = ['http', 'tls', 'quic', 'fakedns'];
  1167. }
  1168. return new Sniffing(
  1169. !!json.enabled,
  1170. destOverride,
  1171. json.metadataOnly,
  1172. json.routeOnly,
  1173. json.ipsExcluded || [],
  1174. json.domainsExcluded || [],
  1175. );
  1176. }
  1177. toJson() {
  1178. return {
  1179. enabled: this.enabled,
  1180. destOverride: this.destOverride,
  1181. metadataOnly: this.metadataOnly,
  1182. routeOnly: this.routeOnly,
  1183. ipsExcluded: this.ipsExcluded.length > 0 ? this.ipsExcluded : undefined,
  1184. domainsExcluded: this.domainsExcluded.length > 0 ? this.domainsExcluded : undefined,
  1185. };
  1186. }
  1187. }
  1188. class Inbound extends XrayCommonClass {
  1189. constructor(
  1190. port = RandomUtil.randomInteger(10000, 60000),
  1191. listen = '',
  1192. protocol = Protocols.VLESS,
  1193. settings = null,
  1194. streamSettings = new StreamSettings(),
  1195. tag = '',
  1196. sniffing = new Sniffing(),
  1197. clientStats = '',
  1198. ) {
  1199. super();
  1200. this.port = port;
  1201. this.listen = listen;
  1202. this._protocol = protocol;
  1203. this.settings = ObjectUtil.isEmpty(settings) ? Inbound.Settings.getSettings(protocol) : settings;
  1204. this.stream = streamSettings;
  1205. this.tag = tag;
  1206. this.sniffing = sniffing;
  1207. this.clientStats = clientStats;
  1208. }
  1209. getClientStats() {
  1210. return this.clientStats;
  1211. }
  1212. get clients() {
  1213. switch (this.protocol) {
  1214. case Protocols.VMESS: return this.settings.vmesses;
  1215. case Protocols.VLESS: return this.settings.vlesses;
  1216. case Protocols.TROJAN: return this.settings.trojans;
  1217. case Protocols.SHADOWSOCKS: return this.isSSMultiUser ? this.settings.shadowsockses : null;
  1218. case Protocols.HYSTERIA: return this.settings.hysterias;
  1219. default: return null;
  1220. }
  1221. }
  1222. get protocol() {
  1223. return this._protocol;
  1224. }
  1225. set protocol(protocol) {
  1226. this._protocol = protocol;
  1227. this.settings = Inbound.Settings.getSettings(protocol);
  1228. this.stream = new StreamSettings();
  1229. if (protocol === Protocols.TROJAN) {
  1230. this.tls = false;
  1231. }
  1232. if (protocol === Protocols.HYSTERIA) {
  1233. this.stream.network = 'hysteria';
  1234. this.stream.security = 'tls';
  1235. }
  1236. }
  1237. get network() {
  1238. return this.stream.network;
  1239. }
  1240. set network(network) {
  1241. this.stream.network = network;
  1242. }
  1243. get isTcp() {
  1244. return this.network === "tcp";
  1245. }
  1246. get isWs() {
  1247. return this.network === "ws";
  1248. }
  1249. get isKcp() {
  1250. return this.network === "kcp";
  1251. }
  1252. get isGrpc() {
  1253. return this.network === "grpc";
  1254. }
  1255. get isHttpupgrade() {
  1256. return this.network === "httpupgrade";
  1257. }
  1258. get isXHTTP() {
  1259. return this.network === "xhttp";
  1260. }
  1261. // Shadowsocks
  1262. get method() {
  1263. switch (this.protocol) {
  1264. case Protocols.SHADOWSOCKS:
  1265. return this.settings.method;
  1266. default:
  1267. return "";
  1268. }
  1269. }
  1270. get isSSMultiUser() {
  1271. return this.method != SSMethods.BLAKE3_CHACHA20_POLY1305;
  1272. }
  1273. get isSS2022() {
  1274. return this.method.substring(0, 4) === "2022";
  1275. }
  1276. get serverName() {
  1277. if (this.stream.isTls) return this.stream.tls.sni;
  1278. if (this.stream.isReality) return this.stream.reality.serverNames;
  1279. return "";
  1280. }
  1281. getHeader(obj, name) {
  1282. for (const header of obj.headers) {
  1283. if (header.name.toLowerCase() === name.toLowerCase()) {
  1284. return header.value;
  1285. }
  1286. }
  1287. return "";
  1288. }
  1289. get host() {
  1290. if (this.isTcp) {
  1291. return this.getHeader(this.stream.tcp.request, 'host');
  1292. } else if (this.isWs) {
  1293. return this.stream.ws.host?.length > 0 ? this.stream.ws.host : this.getHeader(this.stream.ws, 'host');
  1294. } else if (this.isHttpupgrade) {
  1295. return this.stream.httpupgrade.host?.length > 0 ? this.stream.httpupgrade.host : this.getHeader(this.stream.httpupgrade, 'host');
  1296. } else if (this.isXHTTP) {
  1297. return this.stream.xhttp.host?.length > 0 ? this.stream.xhttp.host : this.getHeader(this.stream.xhttp, 'host');
  1298. }
  1299. return null;
  1300. }
  1301. get path() {
  1302. if (this.isTcp) {
  1303. return this.stream.tcp.request.path[0];
  1304. } else if (this.isWs) {
  1305. return this.stream.ws.path;
  1306. } else if (this.isHttpupgrade) {
  1307. return this.stream.httpupgrade.path;
  1308. } else if (this.isXHTTP) {
  1309. return this.stream.xhttp.path;
  1310. }
  1311. return null;
  1312. }
  1313. get serviceName() {
  1314. return this.stream.grpc.serviceName;
  1315. }
  1316. isExpiry(index) {
  1317. let exp = this.clients[index].expiryTime;
  1318. return exp > 0 ? exp < new Date().getTime() : false;
  1319. }
  1320. canEnableTls() {
  1321. if (this.protocol === Protocols.HYSTERIA) return true;
  1322. if (![Protocols.VMESS, Protocols.VLESS, Protocols.TROJAN, Protocols.SHADOWSOCKS].includes(this.protocol)) return false;
  1323. return ["tcp", "ws", "http", "grpc", "httpupgrade", "xhttp"].includes(this.network);
  1324. }
  1325. //this is used for xtls-rprx-vision
  1326. canEnableTlsFlow() {
  1327. if (((this.stream.security === 'tls') || (this.stream.security === 'reality')) && (this.network === "tcp")) {
  1328. return this.protocol === Protocols.VLESS;
  1329. }
  1330. return false;
  1331. }
  1332. // Vision seed applies only when vision flow is selected
  1333. canEnableVisionSeed() {
  1334. if (!this.canEnableTlsFlow()) return false;
  1335. const clients = this.settings?.vlesses;
  1336. if (!Array.isArray(clients)) return false;
  1337. return clients.some(c => c?.flow === TLS_FLOW_CONTROL.VISION || c?.flow === TLS_FLOW_CONTROL.VISION_UDP443);
  1338. }
  1339. canEnableReality() {
  1340. if (![Protocols.VLESS, Protocols.TROJAN].includes(this.protocol)) return false;
  1341. return ["tcp", "http", "grpc", "xhttp"].includes(this.network);
  1342. }
  1343. canEnableStream() {
  1344. return [Protocols.VMESS, Protocols.VLESS, Protocols.TROJAN, Protocols.SHADOWSOCKS, Protocols.HYSTERIA].includes(this.protocol);
  1345. }
  1346. reset() {
  1347. this.port = RandomUtil.randomInteger(10000, 60000);
  1348. this.listen = '';
  1349. this.protocol = Protocols.VMESS;
  1350. this.settings = Inbound.Settings.getSettings(Protocols.VMESS);
  1351. this.stream = new StreamSettings();
  1352. this.tag = '';
  1353. this.sniffing = new Sniffing();
  1354. }
  1355. genVmessLink(address = '', port = this.port, forceTls, remark = '', clientId, security) {
  1356. if (this.protocol !== Protocols.VMESS) {
  1357. return '';
  1358. }
  1359. const tls = forceTls == 'same' ? this.stream.security : forceTls;
  1360. let obj = {
  1361. v: '2',
  1362. ps: remark,
  1363. add: address,
  1364. port: port,
  1365. id: clientId,
  1366. scy: security,
  1367. net: this.stream.network,
  1368. tls: tls,
  1369. };
  1370. const network = this.stream.network;
  1371. if (network === 'tcp') {
  1372. const tcp = this.stream.tcp;
  1373. obj.type = tcp.type;
  1374. if (tcp.type === 'http') {
  1375. const request = tcp.request;
  1376. obj.path = request.path.join(',');
  1377. const host = this.getHeader(request, 'host');
  1378. if (host) obj.host = host;
  1379. }
  1380. } else if (network === 'kcp') {
  1381. const kcp = this.stream.kcp;
  1382. } else if (network === 'ws') {
  1383. const ws = this.stream.ws;
  1384. obj.path = ws.path;
  1385. obj.host = ws.host?.length > 0 ? ws.host : this.getHeader(ws, 'host');
  1386. } else if (network === 'grpc') {
  1387. obj.path = this.stream.grpc.serviceName;
  1388. obj.authority = this.stream.grpc.authority;
  1389. if (this.stream.grpc.multiMode) {
  1390. obj.type = 'multi'
  1391. }
  1392. } else if (network === 'httpupgrade') {
  1393. const httpupgrade = this.stream.httpupgrade;
  1394. obj.path = httpupgrade.path;
  1395. obj.host = httpupgrade.host?.length > 0 ? httpupgrade.host : this.getHeader(httpupgrade, 'host');
  1396. } else if (network === 'xhttp') {
  1397. const xhttp = this.stream.xhttp;
  1398. obj.path = xhttp.path;
  1399. obj.host = xhttp.host?.length > 0 ? xhttp.host : this.getHeader(xhttp, 'host');
  1400. obj.type = xhttp.mode;
  1401. }
  1402. if (tls === 'tls') {
  1403. if (!ObjectUtil.isEmpty(this.stream.tls.sni)) {
  1404. obj.sni = this.stream.tls.sni;
  1405. }
  1406. if (!ObjectUtil.isEmpty(this.stream.tls.settings.fingerprint)) {
  1407. obj.fp = this.stream.tls.settings.fingerprint;
  1408. }
  1409. if (this.stream.tls.alpn.length > 0) {
  1410. obj.alpn = this.stream.tls.alpn.join(',');
  1411. }
  1412. }
  1413. return 'vmess://' + Base64.encode(JSON.stringify(obj, null, 2));
  1414. }
  1415. genVLESSLink(address = '', port = this.port, forceTls, remark = '', clientId, flow) {
  1416. const uuid = clientId;
  1417. const type = this.stream.network;
  1418. const security = forceTls == 'same' ? this.stream.security : forceTls;
  1419. const params = new Map();
  1420. params.set("type", this.stream.network);
  1421. params.set("encryption", this.settings.encryption);
  1422. switch (type) {
  1423. case "tcp":
  1424. const tcp = this.stream.tcp;
  1425. if (tcp.type === 'http') {
  1426. const request = tcp.request;
  1427. params.set("path", request.path.join(','));
  1428. const index = request.headers.findIndex(header => header.name.toLowerCase() === 'host');
  1429. if (index >= 0) {
  1430. const host = request.headers[index].value;
  1431. params.set("host", host);
  1432. }
  1433. params.set("headerType", 'http');
  1434. }
  1435. break;
  1436. case "kcp":
  1437. const kcp = this.stream.kcp;
  1438. break;
  1439. case "ws":
  1440. const ws = this.stream.ws;
  1441. params.set("path", ws.path);
  1442. params.set("host", ws.host?.length > 0 ? ws.host : this.getHeader(ws, 'host'));
  1443. break;
  1444. case "grpc":
  1445. const grpc = this.stream.grpc;
  1446. params.set("serviceName", grpc.serviceName);
  1447. params.set("authority", grpc.authority);
  1448. if (grpc.multiMode) {
  1449. params.set("mode", "multi");
  1450. }
  1451. break;
  1452. case "httpupgrade":
  1453. const httpupgrade = this.stream.httpupgrade;
  1454. params.set("path", httpupgrade.path);
  1455. params.set("host", httpupgrade.host?.length > 0 ? httpupgrade.host : this.getHeader(httpupgrade, 'host'));
  1456. break;
  1457. case "xhttp":
  1458. const xhttp = this.stream.xhttp;
  1459. params.set("path", xhttp.path);
  1460. params.set("host", xhttp.host?.length > 0 ? xhttp.host : this.getHeader(xhttp, 'host'));
  1461. params.set("mode", xhttp.mode);
  1462. break;
  1463. }
  1464. if (security === 'tls') {
  1465. params.set("security", "tls");
  1466. if (this.stream.isTls) {
  1467. params.set("fp", this.stream.tls.settings.fingerprint);
  1468. params.set("alpn", this.stream.tls.alpn);
  1469. if (!ObjectUtil.isEmpty(this.stream.tls.sni)) {
  1470. params.set("sni", this.stream.tls.sni);
  1471. }
  1472. if (this.stream.tls.settings.echConfigList?.length > 0) {
  1473. params.set("ech", this.stream.tls.settings.echConfigList);
  1474. }
  1475. if (type == "tcp" && !ObjectUtil.isEmpty(flow)) {
  1476. params.set("flow", flow);
  1477. }
  1478. }
  1479. }
  1480. else if (security === 'reality') {
  1481. params.set("security", "reality");
  1482. params.set("pbk", this.stream.reality.settings.publicKey);
  1483. params.set("fp", this.stream.reality.settings.fingerprint);
  1484. if (!ObjectUtil.isArrEmpty(this.stream.reality.serverNames)) {
  1485. params.set("sni", this.stream.reality.serverNames.split(",")[0]);
  1486. }
  1487. if (this.stream.reality.shortIds.length > 0) {
  1488. params.set("sid", this.stream.reality.shortIds.split(",")[0]);
  1489. }
  1490. if (!ObjectUtil.isEmpty(this.stream.reality.settings.spiderX)) {
  1491. params.set("spx", this.stream.reality.settings.spiderX);
  1492. }
  1493. if (!ObjectUtil.isEmpty(this.stream.reality.settings.mldsa65Verify)) {
  1494. params.set("pqv", this.stream.reality.settings.mldsa65Verify);
  1495. }
  1496. if (type == 'tcp' && !ObjectUtil.isEmpty(flow)) {
  1497. params.set("flow", flow);
  1498. }
  1499. }
  1500. else {
  1501. params.set("security", "none");
  1502. }
  1503. const link = `vless://${uuid}@${address}:${port}`;
  1504. const url = new URL(link);
  1505. for (const [key, value] of params) {
  1506. url.searchParams.set(key, value)
  1507. }
  1508. url.hash = encodeURIComponent(remark);
  1509. return url.toString();
  1510. }
  1511. genSSLink(address = '', port = this.port, forceTls, remark = '', clientPassword) {
  1512. let settings = this.settings;
  1513. const type = this.stream.network;
  1514. const security = forceTls == 'same' ? this.stream.security : forceTls;
  1515. const params = new Map();
  1516. params.set("type", this.stream.network);
  1517. switch (type) {
  1518. case "tcp":
  1519. const tcp = this.stream.tcp;
  1520. if (tcp.type === 'http') {
  1521. const request = tcp.request;
  1522. params.set("path", request.path.join(','));
  1523. const index = request.headers.findIndex(header => header.name.toLowerCase() === 'host');
  1524. if (index >= 0) {
  1525. const host = request.headers[index].value;
  1526. params.set("host", host);
  1527. }
  1528. params.set("headerType", 'http');
  1529. }
  1530. break;
  1531. case "kcp":
  1532. const kcp = this.stream.kcp;
  1533. break;
  1534. case "ws":
  1535. const ws = this.stream.ws;
  1536. params.set("path", ws.path);
  1537. params.set("host", ws.host?.length > 0 ? ws.host : this.getHeader(ws, 'host'));
  1538. break;
  1539. case "grpc":
  1540. const grpc = this.stream.grpc;
  1541. params.set("serviceName", grpc.serviceName);
  1542. params.set("authority", grpc.authority);
  1543. if (grpc.multiMode) {
  1544. params.set("mode", "multi");
  1545. }
  1546. break;
  1547. case "httpupgrade":
  1548. const httpupgrade = this.stream.httpupgrade;
  1549. params.set("path", httpupgrade.path);
  1550. params.set("host", httpupgrade.host?.length > 0 ? httpupgrade.host : this.getHeader(httpupgrade, 'host'));
  1551. break;
  1552. case "xhttp":
  1553. const xhttp = this.stream.xhttp;
  1554. params.set("path", xhttp.path);
  1555. params.set("host", xhttp.host?.length > 0 ? xhttp.host : this.getHeader(xhttp, 'host'));
  1556. params.set("mode", xhttp.mode);
  1557. break;
  1558. }
  1559. if (security === 'tls') {
  1560. params.set("security", "tls");
  1561. if (this.stream.isTls) {
  1562. params.set("fp", this.stream.tls.settings.fingerprint);
  1563. params.set("alpn", this.stream.tls.alpn);
  1564. if (this.stream.tls.settings.echConfigList?.length > 0) {
  1565. params.set("ech", this.stream.tls.settings.echConfigList);
  1566. }
  1567. if (!ObjectUtil.isEmpty(this.stream.tls.sni)) {
  1568. params.set("sni", this.stream.tls.sni);
  1569. }
  1570. }
  1571. }
  1572. let password = new Array();
  1573. if (this.isSS2022) password.push(settings.password);
  1574. if (this.isSSMultiUser) password.push(clientPassword);
  1575. let link = `ss://${Base64.encode(`${settings.method}:${password.join(':')}`, true)}@${address}:${port}`;
  1576. const url = new URL(link);
  1577. for (const [key, value] of params) {
  1578. url.searchParams.set(key, value)
  1579. }
  1580. url.hash = encodeURIComponent(remark);
  1581. return url.toString();
  1582. }
  1583. genTrojanLink(address = '', port = this.port, forceTls, remark = '', clientPassword) {
  1584. const security = forceTls == 'same' ? this.stream.security : forceTls;
  1585. const type = this.stream.network;
  1586. const params = new Map();
  1587. params.set("type", this.stream.network);
  1588. switch (type) {
  1589. case "tcp":
  1590. const tcp = this.stream.tcp;
  1591. if (tcp.type === 'http') {
  1592. const request = tcp.request;
  1593. params.set("path", request.path.join(','));
  1594. const index = request.headers.findIndex(header => header.name.toLowerCase() === 'host');
  1595. if (index >= 0) {
  1596. const host = request.headers[index].value;
  1597. params.set("host", host);
  1598. }
  1599. params.set("headerType", 'http');
  1600. }
  1601. break;
  1602. case "kcp":
  1603. const kcp = this.stream.kcp;
  1604. break;
  1605. case "ws":
  1606. const ws = this.stream.ws;
  1607. params.set("path", ws.path);
  1608. params.set("host", ws.host?.length > 0 ? ws.host : this.getHeader(ws, 'host'));
  1609. break;
  1610. case "grpc":
  1611. const grpc = this.stream.grpc;
  1612. params.set("serviceName", grpc.serviceName);
  1613. params.set("authority", grpc.authority);
  1614. if (grpc.multiMode) {
  1615. params.set("mode", "multi");
  1616. }
  1617. break;
  1618. case "httpupgrade":
  1619. const httpupgrade = this.stream.httpupgrade;
  1620. params.set("path", httpupgrade.path);
  1621. params.set("host", httpupgrade.host?.length > 0 ? httpupgrade.host : this.getHeader(httpupgrade, 'host'));
  1622. break;
  1623. case "xhttp":
  1624. const xhttp = this.stream.xhttp;
  1625. params.set("path", xhttp.path);
  1626. params.set("host", xhttp.host?.length > 0 ? xhttp.host : this.getHeader(xhttp, 'host'));
  1627. params.set("mode", xhttp.mode);
  1628. break;
  1629. }
  1630. if (security === 'tls') {
  1631. params.set("security", "tls");
  1632. if (this.stream.isTls) {
  1633. params.set("fp", this.stream.tls.settings.fingerprint);
  1634. params.set("alpn", this.stream.tls.alpn);
  1635. if (this.stream.tls.settings.echConfigList?.length > 0) {
  1636. params.set("ech", this.stream.tls.settings.echConfigList);
  1637. }
  1638. if (!ObjectUtil.isEmpty(this.stream.tls.sni)) {
  1639. params.set("sni", this.stream.tls.sni);
  1640. }
  1641. }
  1642. }
  1643. else if (security === 'reality') {
  1644. params.set("security", "reality");
  1645. params.set("pbk", this.stream.reality.settings.publicKey);
  1646. params.set("fp", this.stream.reality.settings.fingerprint);
  1647. if (!ObjectUtil.isArrEmpty(this.stream.reality.serverNames)) {
  1648. params.set("sni", this.stream.reality.serverNames.split(",")[0]);
  1649. }
  1650. if (this.stream.reality.shortIds.length > 0) {
  1651. params.set("sid", this.stream.reality.shortIds.split(",")[0]);
  1652. }
  1653. if (!ObjectUtil.isEmpty(this.stream.reality.settings.spiderX)) {
  1654. params.set("spx", this.stream.reality.settings.spiderX);
  1655. }
  1656. if (!ObjectUtil.isEmpty(this.stream.reality.settings.mldsa65Verify)) {
  1657. params.set("pqv", this.stream.reality.settings.mldsa65Verify);
  1658. }
  1659. }
  1660. else {
  1661. params.set("security", "none");
  1662. }
  1663. const link = `trojan://${clientPassword}@${address}:${port}`;
  1664. const url = new URL(link);
  1665. for (const [key, value] of params) {
  1666. url.searchParams.set(key, value)
  1667. }
  1668. url.hash = encodeURIComponent(remark);
  1669. return url.toString();
  1670. }
  1671. genHysteriaLink(address = '', port = this.port, remark = '', clientAuth) {
  1672. const protocol = this.settings.version == 2 ? "hysteria2" : "hysteria";
  1673. const link = `${protocol}://${clientAuth}@${address}:${port}`;
  1674. const params = new Map();
  1675. params.set("security", "tls");
  1676. if (this.stream.tls.settings.fingerprint?.length > 0) params.set("fp", this.stream.tls.settings.fingerprint);
  1677. if (this.stream.tls.alpn?.length > 0) params.set("alpn", this.stream.tls.alpn);
  1678. if (this.stream.tls.settings.allowInsecure) params.set("insecure", "1");
  1679. if (this.stream.tls.settings.echConfigList?.length > 0) params.set("ech", this.stream.tls.settings.echConfigList.join(','));
  1680. if (this.stream.tls.sni?.length > 0) params.set("sni", this.stream.tls.sni);
  1681. const url = new URL(link);
  1682. for (const [key, value] of params) {
  1683. url.searchParams.set(key, value);
  1684. }
  1685. url.hash = encodeURIComponent(remark);
  1686. return url.toString();
  1687. }
  1688. getWireguardLink(address, port, remark, peerId) {
  1689. let txt = `[Interface]\n`
  1690. txt += `PrivateKey = ${this.settings.peers[peerId].privateKey}\n`
  1691. txt += `Address = ${this.settings.peers[peerId].allowedIPs[0]}\n`
  1692. txt += `DNS = 1.1.1.1, 1.0.0.1\n`
  1693. if (this.settings.mtu) {
  1694. txt += `MTU = ${this.settings.mtu}\n`
  1695. }
  1696. txt += `\n# ${remark}\n`
  1697. txt += `[Peer]\n`
  1698. txt += `PublicKey = ${this.settings.pubKey}\n`
  1699. txt += `AllowedIPs = 0.0.0.0/0, ::/0\n`
  1700. txt += `Endpoint = ${address}:${port}`
  1701. if (this.settings.peers[peerId].psk) {
  1702. txt += `\nPresharedKey = ${this.settings.peers[peerId].psk}`
  1703. }
  1704. if (this.settings.peers[peerId].keepAlive) {
  1705. txt += `\nPersistentKeepalive = ${this.settings.peers[peerId].keepAlive}\n`
  1706. }
  1707. return txt;
  1708. }
  1709. genLink(address = '', port = this.port, forceTls = 'same', remark = '', client) {
  1710. switch (this.protocol) {
  1711. case Protocols.VMESS:
  1712. return this.genVmessLink(address, port, forceTls, remark, client.id, client.security);
  1713. case Protocols.VLESS:
  1714. return this.genVLESSLink(address, port, forceTls, remark, client.id, client.flow);
  1715. case Protocols.SHADOWSOCKS:
  1716. return this.genSSLink(address, port, forceTls, remark, this.isSSMultiUser ? client.password : '');
  1717. case Protocols.TROJAN:
  1718. return this.genTrojanLink(address, port, forceTls, remark, client.password);
  1719. case Protocols.HYSTERIA:
  1720. return this.genHysteriaLink(address, port, remark, client.auth.length > 0 ? client.auth : this.stream.hysteria.auth);
  1721. default: return '';
  1722. }
  1723. }
  1724. genAllLinks(remark = '', remarkModel = '-ieo', client) {
  1725. let result = [];
  1726. let email = client ? client.email : '';
  1727. let addr = !ObjectUtil.isEmpty(this.listen) && this.listen !== "0.0.0.0" ? this.listen : location.hostname;
  1728. let port = this.port;
  1729. const separationChar = remarkModel.charAt(0);
  1730. const orderChars = remarkModel.slice(1);
  1731. let orders = {
  1732. 'i': remark,
  1733. 'e': email,
  1734. 'o': '',
  1735. };
  1736. if (ObjectUtil.isArrEmpty(this.stream.externalProxy)) {
  1737. let r = orderChars.split('').map(char => orders[char]).filter(x => x.length > 0).join(separationChar);
  1738. result.push({
  1739. remark: r,
  1740. link: this.genLink(addr, port, 'same', r, client)
  1741. });
  1742. } else {
  1743. this.stream.externalProxy.forEach((ep) => {
  1744. orders['o'] = ep.remark;
  1745. let r = orderChars.split('').map(char => orders[char]).filter(x => x.length > 0).join(separationChar);
  1746. result.push({
  1747. remark: r,
  1748. link: this.genLink(ep.dest, ep.port, ep.forceTls, r, client)
  1749. });
  1750. });
  1751. }
  1752. return result;
  1753. }
  1754. genInboundLinks(remark = '', remarkModel = '-ieo') {
  1755. let addr = !ObjectUtil.isEmpty(this.listen) && this.listen !== "0.0.0.0" ? this.listen : location.hostname;
  1756. if (this.clients) {
  1757. let links = [];
  1758. this.clients.forEach((client) => {
  1759. this.genAllLinks(remark, remarkModel, client).forEach(l => {
  1760. links.push(l.link);
  1761. })
  1762. });
  1763. return links.join('\r\n');
  1764. } else {
  1765. if (this.protocol == Protocols.SHADOWSOCKS && !this.isSSMultiUser) return this.genSSLink(addr, this.port, 'same', remark);
  1766. if (this.protocol == Protocols.WIREGUARD) {
  1767. let links = [];
  1768. this.settings.peers.forEach((p, index) => {
  1769. links.push(this.getWireguardLink(addr, this.port, remark + remarkModel.charAt(0) + (index + 1), index));
  1770. });
  1771. return links.join('\r\n');
  1772. }
  1773. return '';
  1774. }
  1775. }
  1776. static fromJson(json = {}) {
  1777. return new Inbound(
  1778. json.port,
  1779. json.listen,
  1780. json.protocol,
  1781. Inbound.Settings.fromJson(json.protocol, json.settings),
  1782. StreamSettings.fromJson(json.streamSettings),
  1783. json.tag,
  1784. Sniffing.fromJson(json.sniffing),
  1785. json.clientStats
  1786. )
  1787. }
  1788. toJson() {
  1789. let streamSettings;
  1790. if (this.canEnableStream() || this.stream?.sockopt) {
  1791. streamSettings = this.stream.toJson();
  1792. }
  1793. return {
  1794. port: this.port,
  1795. listen: this.listen,
  1796. protocol: this.protocol,
  1797. settings: this.settings instanceof XrayCommonClass ? this.settings.toJson() : this.settings,
  1798. streamSettings: streamSettings,
  1799. tag: this.tag,
  1800. sniffing: this.sniffing.toJson(),
  1801. clientStats: this.clientStats
  1802. };
  1803. }
  1804. }
  1805. Inbound.Settings = class extends XrayCommonClass {
  1806. constructor(protocol) {
  1807. super();
  1808. this.protocol = protocol;
  1809. }
  1810. static getSettings(protocol) {
  1811. switch (protocol) {
  1812. case Protocols.VMESS: return new Inbound.VmessSettings(protocol);
  1813. case Protocols.VLESS: return new Inbound.VLESSSettings(protocol);
  1814. case Protocols.TROJAN: return new Inbound.TrojanSettings(protocol);
  1815. case Protocols.SHADOWSOCKS: return new Inbound.ShadowsocksSettings(protocol);
  1816. case Protocols.TUNNEL: return new Inbound.TunnelSettings(protocol);
  1817. case Protocols.MIXED: return new Inbound.MixedSettings(protocol);
  1818. case Protocols.HTTP: return new Inbound.HttpSettings(protocol);
  1819. case Protocols.WIREGUARD: return new Inbound.WireguardSettings(protocol);
  1820. case Protocols.TUN: return new Inbound.TunSettings(protocol);
  1821. case Protocols.HYSTERIA: return new Inbound.HysteriaSettings(protocol);
  1822. default: return null;
  1823. }
  1824. }
  1825. static fromJson(protocol, json) {
  1826. switch (protocol) {
  1827. case Protocols.VMESS: return Inbound.VmessSettings.fromJson(json);
  1828. case Protocols.VLESS: return Inbound.VLESSSettings.fromJson(json);
  1829. case Protocols.TROJAN: return Inbound.TrojanSettings.fromJson(json);
  1830. case Protocols.SHADOWSOCKS: return Inbound.ShadowsocksSettings.fromJson(json);
  1831. case Protocols.TUNNEL: return Inbound.TunnelSettings.fromJson(json);
  1832. case Protocols.MIXED: return Inbound.MixedSettings.fromJson(json);
  1833. case Protocols.HTTP: return Inbound.HttpSettings.fromJson(json);
  1834. case Protocols.WIREGUARD: return Inbound.WireguardSettings.fromJson(json);
  1835. case Protocols.TUN: return Inbound.TunSettings.fromJson(json);
  1836. case Protocols.HYSTERIA: return Inbound.HysteriaSettings.fromJson(json);
  1837. default: return null;
  1838. }
  1839. }
  1840. toJson() {
  1841. return {};
  1842. }
  1843. };
  1844. /** Shared user-quota fields and UI helpers for multi-user protocol clients. */
  1845. Inbound.ClientBase = class extends XrayCommonClass {
  1846. constructor(
  1847. email = RandomUtil.randomLowerAndNum(8),
  1848. limitIp = 0,
  1849. totalGB = 0,
  1850. expiryTime = 0,
  1851. enable = true,
  1852. tgId = '',
  1853. subId = RandomUtil.randomLowerAndNum(16),
  1854. comment = '',
  1855. reset = 0,
  1856. created_at = undefined,
  1857. updated_at = undefined,
  1858. ) {
  1859. super();
  1860. this.email = email;
  1861. this.limitIp = limitIp;
  1862. this.totalGB = totalGB;
  1863. this.expiryTime = expiryTime;
  1864. this.enable = enable;
  1865. this.tgId = tgId;
  1866. this.subId = subId;
  1867. this.comment = comment;
  1868. this.reset = reset;
  1869. this.created_at = created_at;
  1870. this.updated_at = updated_at;
  1871. }
  1872. static commonArgsFromJson(json = {}) {
  1873. return [
  1874. json.email,
  1875. json.limitIp,
  1876. json.totalGB,
  1877. json.expiryTime,
  1878. json.enable,
  1879. json.tgId,
  1880. json.subId,
  1881. json.comment,
  1882. json.reset,
  1883. json.created_at,
  1884. json.updated_at,
  1885. ];
  1886. }
  1887. _clientBaseToJson() {
  1888. return {
  1889. email: this.email,
  1890. limitIp: this.limitIp,
  1891. totalGB: this.totalGB,
  1892. expiryTime: this.expiryTime,
  1893. enable: this.enable,
  1894. tgId: this.tgId,
  1895. subId: this.subId,
  1896. comment: this.comment,
  1897. reset: this.reset,
  1898. created_at: this.created_at,
  1899. updated_at: this.updated_at,
  1900. };
  1901. }
  1902. get _expiryTime() {
  1903. if (this.expiryTime === 0 || this.expiryTime === '') {
  1904. return null;
  1905. }
  1906. if (this.expiryTime < 0) {
  1907. return this.expiryTime / -86400000;
  1908. }
  1909. return moment(this.expiryTime);
  1910. }
  1911. set _expiryTime(t) {
  1912. if (t == null || t === '') {
  1913. this.expiryTime = 0;
  1914. } else {
  1915. this.expiryTime = t.valueOf();
  1916. }
  1917. }
  1918. get _totalGB() {
  1919. return NumberFormatter.toFixed(this.totalGB / SizeFormatter.ONE_GB, 2);
  1920. }
  1921. set _totalGB(gb) {
  1922. this.totalGB = NumberFormatter.toFixed(gb * SizeFormatter.ONE_GB, 0);
  1923. }
  1924. };
  1925. Inbound.VmessSettings = class extends Inbound.Settings {
  1926. constructor(protocol,
  1927. vmesses = [new Inbound.VmessSettings.VMESS()]) {
  1928. super(protocol);
  1929. this.vmesses = vmesses;
  1930. }
  1931. indexOfVmessById(id) {
  1932. return this.vmesses.findIndex(VMESS => VMESS.id === id);
  1933. }
  1934. addVmess(VMESS) {
  1935. if (this.indexOfVmessById(VMESS.id) >= 0) {
  1936. return false;
  1937. }
  1938. this.vmesses.push(VMESS);
  1939. }
  1940. delVmess(VMESS) {
  1941. const i = this.indexOfVmessById(VMESS.id);
  1942. if (i >= 0) {
  1943. this.vmesses.splice(i, 1);
  1944. }
  1945. }
  1946. static fromJson(json = {}) {
  1947. return new Inbound.VmessSettings(
  1948. Protocols.VMESS,
  1949. (json.clients || []).map(client => Inbound.VmessSettings.VMESS.fromJson(client)),
  1950. );
  1951. }
  1952. toJson() {
  1953. return {
  1954. clients: Inbound.VmessSettings.toJsonArray(this.vmesses),
  1955. };
  1956. }
  1957. };
  1958. Inbound.VmessSettings.VMESS = class extends Inbound.ClientBase {
  1959. constructor(
  1960. id = RandomUtil.randomUUID(),
  1961. security = USERS_SECURITY.AUTO,
  1962. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  1963. ) {
  1964. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  1965. this.id = id;
  1966. this.security = security;
  1967. }
  1968. static fromJson(json = {}) {
  1969. return new Inbound.VmessSettings.VMESS(
  1970. json.id,
  1971. json.security,
  1972. ...Inbound.ClientBase.commonArgsFromJson(json),
  1973. );
  1974. }
  1975. toJson() {
  1976. return {
  1977. id: this.id,
  1978. security: this.security,
  1979. ...this._clientBaseToJson(),
  1980. };
  1981. }
  1982. };
  1983. Inbound.VLESSSettings = class extends Inbound.Settings {
  1984. constructor(
  1985. protocol,
  1986. vlesses = [new Inbound.VLESSSettings.VLESS()],
  1987. decryption = "none",
  1988. encryption = "none",
  1989. fallbacks = [],
  1990. selectedAuth = undefined,
  1991. testseed = [900, 500, 900, 256],
  1992. ) {
  1993. super(protocol);
  1994. this.vlesses = vlesses;
  1995. this.decryption = decryption;
  1996. this.encryption = encryption;
  1997. this.fallbacks = fallbacks;
  1998. this.selectedAuth = selectedAuth;
  1999. this.testseed = testseed;
  2000. }
  2001. addFallback() {
  2002. this.fallbacks.push(new Inbound.VLESSSettings.Fallback());
  2003. }
  2004. delFallback(index) {
  2005. this.fallbacks.splice(index, 1);
  2006. }
  2007. static fromJson(json = {}) {
  2008. // Ensure testseed is always initialized as an array
  2009. let testseed = [900, 500, 900, 256];
  2010. if (json.testseed && Array.isArray(json.testseed) && json.testseed.length >= 4) {
  2011. testseed = json.testseed;
  2012. }
  2013. const obj = new Inbound.VLESSSettings(
  2014. Protocols.VLESS,
  2015. (json.clients || []).map(client => Inbound.VLESSSettings.VLESS.fromJson(client)),
  2016. json.decryption,
  2017. json.encryption,
  2018. Inbound.VLESSSettings.Fallback.fromJson(json.fallbacks || []),
  2019. json.selectedAuth,
  2020. testseed
  2021. );
  2022. return obj;
  2023. }
  2024. toJson() {
  2025. const json = {
  2026. clients: Inbound.VLESSSettings.toJsonArray(this.vlesses),
  2027. };
  2028. if (this.decryption) {
  2029. json.decryption = this.decryption;
  2030. }
  2031. if (this.encryption) {
  2032. json.encryption = this.encryption;
  2033. }
  2034. if (this.fallbacks && this.fallbacks.length > 0) {
  2035. json.fallbacks = Inbound.VLESSSettings.toJsonArray(this.fallbacks);
  2036. }
  2037. if (this.selectedAuth) {
  2038. json.selectedAuth = this.selectedAuth;
  2039. }
  2040. // Only include testseed if at least one client has a flow set
  2041. const hasFlow = this.vlesses && this.vlesses.some(vless => vless.flow && vless.flow !== '');
  2042. if (hasFlow && this.testseed && this.testseed.length >= 4) {
  2043. json.testseed = this.testseed;
  2044. }
  2045. return json;
  2046. }
  2047. };
  2048. Inbound.VLESSSettings.VLESS = class extends Inbound.ClientBase {
  2049. constructor(
  2050. id = RandomUtil.randomUUID(),
  2051. flow = '',
  2052. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2053. ) {
  2054. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2055. this.id = id;
  2056. this.flow = flow;
  2057. }
  2058. static fromJson(json = {}) {
  2059. return new Inbound.VLESSSettings.VLESS(
  2060. json.id,
  2061. json.flow,
  2062. ...Inbound.ClientBase.commonArgsFromJson(json),
  2063. );
  2064. }
  2065. toJson() {
  2066. return {
  2067. id: this.id,
  2068. flow: this.flow,
  2069. ...this._clientBaseToJson(),
  2070. };
  2071. }
  2072. };
  2073. Inbound.VLESSSettings.Fallback = class extends XrayCommonClass {
  2074. constructor(name = "", alpn = '', path = '', dest = '', xver = 0) {
  2075. super();
  2076. this.name = name;
  2077. this.alpn = alpn;
  2078. this.path = path;
  2079. this.dest = dest;
  2080. this.xver = xver;
  2081. }
  2082. toJson() {
  2083. let xver = this.xver;
  2084. if (!Number.isInteger(xver)) {
  2085. xver = 0;
  2086. }
  2087. return {
  2088. name: this.name,
  2089. alpn: this.alpn,
  2090. path: this.path,
  2091. dest: this.dest,
  2092. xver: xver,
  2093. }
  2094. }
  2095. static fromJson(json = []) {
  2096. const fallbacks = [];
  2097. for (let fallback of json) {
  2098. fallbacks.push(new Inbound.VLESSSettings.Fallback(
  2099. fallback.name,
  2100. fallback.alpn,
  2101. fallback.path,
  2102. fallback.dest,
  2103. fallback.xver,
  2104. ))
  2105. }
  2106. return fallbacks;
  2107. }
  2108. };
  2109. Inbound.TrojanSettings = class extends Inbound.Settings {
  2110. constructor(protocol,
  2111. trojans = [new Inbound.TrojanSettings.Trojan()],
  2112. fallbacks = [],) {
  2113. super(protocol);
  2114. this.trojans = trojans;
  2115. this.fallbacks = fallbacks;
  2116. }
  2117. addFallback() {
  2118. this.fallbacks.push(new Inbound.TrojanSettings.Fallback());
  2119. }
  2120. delFallback(index) {
  2121. this.fallbacks.splice(index, 1);
  2122. }
  2123. static fromJson(json = {}) {
  2124. return new Inbound.TrojanSettings(
  2125. Protocols.TROJAN,
  2126. (json.clients || []).map(client => Inbound.TrojanSettings.Trojan.fromJson(client)),
  2127. Inbound.TrojanSettings.Fallback.fromJson(json.fallbacks),);
  2128. }
  2129. toJson() {
  2130. return {
  2131. clients: Inbound.TrojanSettings.toJsonArray(this.trojans),
  2132. fallbacks: Inbound.TrojanSettings.toJsonArray(this.fallbacks)
  2133. };
  2134. }
  2135. };
  2136. Inbound.TrojanSettings.Trojan = class extends Inbound.ClientBase {
  2137. constructor(
  2138. password = RandomUtil.randomSeq(10),
  2139. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2140. ) {
  2141. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2142. this.password = password;
  2143. }
  2144. toJson() {
  2145. return {
  2146. password: this.password,
  2147. ...this._clientBaseToJson(),
  2148. };
  2149. }
  2150. static fromJson(json = {}) {
  2151. return new Inbound.TrojanSettings.Trojan(
  2152. json.password,
  2153. ...Inbound.ClientBase.commonArgsFromJson(json),
  2154. );
  2155. }
  2156. };
  2157. Inbound.TrojanSettings.Fallback = class extends XrayCommonClass {
  2158. constructor(name = "", alpn = '', path = '', dest = '', xver = 0) {
  2159. super();
  2160. this.name = name;
  2161. this.alpn = alpn;
  2162. this.path = path;
  2163. this.dest = dest;
  2164. this.xver = xver;
  2165. }
  2166. toJson() {
  2167. let xver = this.xver;
  2168. if (!Number.isInteger(xver)) {
  2169. xver = 0;
  2170. }
  2171. return {
  2172. name: this.name,
  2173. alpn: this.alpn,
  2174. path: this.path,
  2175. dest: this.dest,
  2176. xver: xver,
  2177. }
  2178. }
  2179. static fromJson(json = []) {
  2180. const fallbacks = [];
  2181. for (let fallback of json) {
  2182. fallbacks.push(new Inbound.TrojanSettings.Fallback(
  2183. fallback.name,
  2184. fallback.alpn,
  2185. fallback.path,
  2186. fallback.dest,
  2187. fallback.xver,
  2188. ))
  2189. }
  2190. return fallbacks;
  2191. }
  2192. };
  2193. Inbound.ShadowsocksSettings = class extends Inbound.Settings {
  2194. constructor(protocol,
  2195. method = SSMethods.BLAKE3_AES_256_GCM,
  2196. password = RandomUtil.randomShadowsocksPassword(),
  2197. network = 'tcp,udp',
  2198. shadowsockses = [new Inbound.ShadowsocksSettings.Shadowsocks()],
  2199. ivCheck = false,
  2200. ) {
  2201. super(protocol);
  2202. this.method = method;
  2203. this.password = password;
  2204. this.network = network;
  2205. this.shadowsockses = shadowsockses;
  2206. this.ivCheck = ivCheck;
  2207. }
  2208. static fromJson(json = {}) {
  2209. return new Inbound.ShadowsocksSettings(
  2210. Protocols.SHADOWSOCKS,
  2211. json.method,
  2212. json.password,
  2213. json.network,
  2214. (json.clients || []).map(client => Inbound.ShadowsocksSettings.Shadowsocks.fromJson(client)),
  2215. json.ivCheck,
  2216. );
  2217. }
  2218. toJson() {
  2219. return {
  2220. method: this.method,
  2221. password: this.password,
  2222. network: this.network,
  2223. clients: Inbound.ShadowsocksSettings.toJsonArray(this.shadowsockses),
  2224. ivCheck: this.ivCheck,
  2225. };
  2226. }
  2227. };
  2228. Inbound.ShadowsocksSettings.Shadowsocks = class extends Inbound.ClientBase {
  2229. constructor(
  2230. method = '',
  2231. password = RandomUtil.randomShadowsocksPassword(),
  2232. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2233. ) {
  2234. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2235. this.method = method;
  2236. this.password = password;
  2237. }
  2238. toJson() {
  2239. return {
  2240. method: this.method,
  2241. password: this.password,
  2242. ...this._clientBaseToJson(),
  2243. };
  2244. }
  2245. static fromJson(json = {}) {
  2246. return new Inbound.ShadowsocksSettings.Shadowsocks(
  2247. json.method,
  2248. json.password,
  2249. ...Inbound.ClientBase.commonArgsFromJson(json),
  2250. );
  2251. }
  2252. };
  2253. Inbound.HysteriaSettings = class extends Inbound.Settings {
  2254. constructor(protocol, version = 2, hysterias = [new Inbound.HysteriaSettings.Hysteria()]) {
  2255. super(protocol);
  2256. this.version = version;
  2257. this.hysterias = hysterias;
  2258. }
  2259. static fromJson(json = {}) {
  2260. return new Inbound.HysteriaSettings(
  2261. Protocols.HYSTERIA,
  2262. json.version ?? 2,
  2263. (json.clients || []).map(client => Inbound.HysteriaSettings.Hysteria.fromJson(client)),
  2264. );
  2265. }
  2266. toJson() {
  2267. return {
  2268. version: this.version,
  2269. clients: Inbound.HysteriaSettings.toJsonArray(this.hysterias),
  2270. };
  2271. }
  2272. };
  2273. Inbound.HysteriaSettings.Hysteria = class extends Inbound.ClientBase {
  2274. constructor(
  2275. auth = RandomUtil.randomSeq(10),
  2276. email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at,
  2277. ) {
  2278. super(email, limitIp, totalGB, expiryTime, enable, tgId, subId, comment, reset, created_at, updated_at);
  2279. this.auth = auth;
  2280. }
  2281. toJson() {
  2282. return {
  2283. auth: this.auth,
  2284. ...this._clientBaseToJson(),
  2285. };
  2286. }
  2287. static fromJson(json = {}) {
  2288. return new Inbound.HysteriaSettings.Hysteria(
  2289. json.auth,
  2290. ...Inbound.ClientBase.commonArgsFromJson(json),
  2291. );
  2292. }
  2293. };
  2294. Inbound.TunnelSettings = class extends Inbound.Settings {
  2295. constructor(
  2296. protocol,
  2297. address,
  2298. port,
  2299. portMap = [],
  2300. network = 'tcp,udp',
  2301. followRedirect = false
  2302. ) {
  2303. super(protocol);
  2304. this.address = address;
  2305. this.port = port;
  2306. this.portMap = portMap;
  2307. this.network = network;
  2308. this.followRedirect = followRedirect;
  2309. }
  2310. static fromJson(json = {}) {
  2311. return new Inbound.TunnelSettings(
  2312. Protocols.TUNNEL,
  2313. json.address,
  2314. json.port,
  2315. XrayCommonClass.toHeaders(json.portMap),
  2316. json.network,
  2317. json.followRedirect,
  2318. );
  2319. }
  2320. toJson() {
  2321. return {
  2322. address: this.address,
  2323. port: this.port,
  2324. portMap: XrayCommonClass.toV2Headers(this.portMap, false),
  2325. network: this.network,
  2326. followRedirect: this.followRedirect,
  2327. };
  2328. }
  2329. };
  2330. Inbound.MixedSettings = class extends Inbound.Settings {
  2331. constructor(protocol, auth = 'password', accounts = [new Inbound.MixedSettings.SocksAccount()], udp = false, ip = '127.0.0.1') {
  2332. super(protocol);
  2333. this.auth = auth;
  2334. this.accounts = accounts;
  2335. this.udp = udp;
  2336. this.ip = ip;
  2337. }
  2338. addAccount(account) {
  2339. this.accounts.push(account);
  2340. }
  2341. delAccount(index) {
  2342. this.accounts.splice(index, 1);
  2343. }
  2344. static fromJson(json = {}) {
  2345. let accounts;
  2346. if (json.auth === 'password') {
  2347. accounts = json.accounts.map(
  2348. account => Inbound.MixedSettings.SocksAccount.fromJson(account)
  2349. )
  2350. }
  2351. return new Inbound.MixedSettings(
  2352. Protocols.MIXED,
  2353. json.auth,
  2354. accounts,
  2355. json.udp,
  2356. json.ip,
  2357. );
  2358. }
  2359. toJson() {
  2360. return {
  2361. auth: this.auth,
  2362. accounts: this.auth === 'password' ? this.accounts.map(account => account.toJson()) : undefined,
  2363. udp: this.udp,
  2364. ip: this.ip,
  2365. };
  2366. }
  2367. };
  2368. Inbound.MixedSettings.SocksAccount = class extends XrayCommonClass {
  2369. constructor(user = RandomUtil.randomSeq(10), pass = RandomUtil.randomSeq(10)) {
  2370. super();
  2371. this.user = user;
  2372. this.pass = pass;
  2373. }
  2374. static fromJson(json = {}) {
  2375. return new Inbound.MixedSettings.SocksAccount(json.user, json.pass);
  2376. }
  2377. };
  2378. Inbound.HttpSettings = class extends Inbound.Settings {
  2379. constructor(
  2380. protocol,
  2381. accounts = [new Inbound.HttpSettings.HttpAccount()],
  2382. allowTransparent = false,
  2383. ) {
  2384. super(protocol);
  2385. this.accounts = accounts;
  2386. this.allowTransparent = allowTransparent;
  2387. }
  2388. addAccount(account) {
  2389. this.accounts.push(account);
  2390. }
  2391. delAccount(index) {
  2392. this.accounts.splice(index, 1);
  2393. }
  2394. static fromJson(json = {}) {
  2395. return new Inbound.HttpSettings(
  2396. Protocols.HTTP,
  2397. json.accounts.map(account => Inbound.HttpSettings.HttpAccount.fromJson(account)),
  2398. json.allowTransparent,
  2399. );
  2400. }
  2401. toJson() {
  2402. return {
  2403. accounts: Inbound.HttpSettings.toJsonArray(this.accounts),
  2404. allowTransparent: this.allowTransparent,
  2405. };
  2406. }
  2407. };
  2408. Inbound.HttpSettings.HttpAccount = class extends XrayCommonClass {
  2409. constructor(user = RandomUtil.randomSeq(10), pass = RandomUtil.randomSeq(10)) {
  2410. super();
  2411. this.user = user;
  2412. this.pass = pass;
  2413. }
  2414. static fromJson(json = {}) {
  2415. return new Inbound.HttpSettings.HttpAccount(json.user, json.pass);
  2416. }
  2417. };
  2418. Inbound.WireguardSettings = class extends XrayCommonClass {
  2419. constructor(
  2420. protocol,
  2421. mtu = 1420,
  2422. secretKey = Wireguard.generateKeypair().privateKey,
  2423. peers = [new Inbound.WireguardSettings.Peer()],
  2424. noKernelTun = false
  2425. ) {
  2426. super(protocol);
  2427. this.mtu = mtu;
  2428. this.secretKey = secretKey;
  2429. this.pubKey = secretKey.length > 0 ? Wireguard.generateKeypair(secretKey).publicKey : '';
  2430. this.peers = peers;
  2431. this.noKernelTun = noKernelTun;
  2432. }
  2433. addPeer() {
  2434. this.peers.push(new Inbound.WireguardSettings.Peer(null, null, '', ['10.0.0.' + (this.peers.length + 2)]));
  2435. }
  2436. delPeer(index) {
  2437. this.peers.splice(index, 1);
  2438. }
  2439. static fromJson(json = {}) {
  2440. return new Inbound.WireguardSettings(
  2441. Protocols.WIREGUARD,
  2442. json.mtu,
  2443. json.secretKey,
  2444. json.peers.map(peer => Inbound.WireguardSettings.Peer.fromJson(peer)),
  2445. json.noKernelTun,
  2446. );
  2447. }
  2448. toJson() {
  2449. return {
  2450. mtu: this.mtu ?? undefined,
  2451. secretKey: this.secretKey,
  2452. peers: Inbound.WireguardSettings.Peer.toJsonArray(this.peers),
  2453. noKernelTun: this.noKernelTun,
  2454. };
  2455. }
  2456. };
  2457. Inbound.WireguardSettings.Peer = class extends XrayCommonClass {
  2458. constructor(privateKey, publicKey, psk = '', allowedIPs = ['10.0.0.2/32'], keepAlive = 0) {
  2459. super();
  2460. this.privateKey = privateKey
  2461. this.publicKey = publicKey;
  2462. if (!this.publicKey) {
  2463. [this.publicKey, this.privateKey] = Object.values(Wireguard.generateKeypair())
  2464. }
  2465. this.psk = psk;
  2466. allowedIPs.forEach((a, index) => {
  2467. if (a.length > 0 && !a.includes('/')) allowedIPs[index] += '/32';
  2468. })
  2469. this.allowedIPs = allowedIPs;
  2470. this.keepAlive = keepAlive;
  2471. }
  2472. static fromJson(json = {}) {
  2473. return new Inbound.WireguardSettings.Peer(
  2474. json.privateKey,
  2475. json.publicKey,
  2476. json.preSharedKey,
  2477. json.allowedIPs,
  2478. json.keepAlive
  2479. );
  2480. }
  2481. toJson() {
  2482. this.allowedIPs.forEach((a, index) => {
  2483. if (a.length > 0 && !a.includes('/')) this.allowedIPs[index] += '/32';
  2484. });
  2485. return {
  2486. privateKey: this.privateKey,
  2487. publicKey: this.publicKey,
  2488. preSharedKey: this.psk.length > 0 ? this.psk : undefined,
  2489. allowedIPs: this.allowedIPs,
  2490. keepAlive: this.keepAlive ?? undefined,
  2491. };
  2492. }
  2493. };
  2494. Inbound.TunSettings = class extends Inbound.Settings {
  2495. constructor(
  2496. protocol,
  2497. name = 'xray0',
  2498. mtu = [1500, 1280],
  2499. gateway = [],
  2500. dns = [],
  2501. userLevel = 0,
  2502. autoSystemRoutingTable = [],
  2503. autoOutboundsInterface = 'auto'
  2504. ) {
  2505. super(protocol);
  2506. this.name = name;
  2507. this.mtu = this._normalizeMtu(mtu);
  2508. this.gateway = Array.isArray(gateway) ? gateway : [];
  2509. this.dns = Array.isArray(dns) ? dns : [];
  2510. this.userLevel = userLevel;
  2511. this.autoSystemRoutingTable = Array.isArray(autoSystemRoutingTable) ? autoSystemRoutingTable : [];
  2512. this.autoOutboundsInterface = autoOutboundsInterface;
  2513. }
  2514. _normalizeMtu(mtu) {
  2515. if (!Array.isArray(mtu)) {
  2516. const single = Number(mtu) || 1500;
  2517. return [single, single];
  2518. }
  2519. if (mtu.length === 0) {
  2520. return [1500, 1280];
  2521. }
  2522. if (mtu.length === 1) {
  2523. const single = Number(mtu[0]) || 1500;
  2524. return [single, single];
  2525. }
  2526. return [Number(mtu[0]) || 1500, Number(mtu[1]) || 1280];
  2527. }
  2528. static fromJson(json = {}) {
  2529. return new Inbound.TunSettings(
  2530. Protocols.TUN,
  2531. json.name ?? 'xray0',
  2532. json.mtu ?? json.MTU ?? [1500, 1280],
  2533. json.gateway ?? json.Gateway ?? [],
  2534. json.dns ?? json.DNS ?? [],
  2535. json.userLevel ?? 0,
  2536. json.autoSystemRoutingTable ?? [],
  2537. Object.prototype.hasOwnProperty.call(json, 'autoOutboundsInterface') ? json.autoOutboundsInterface : 'auto'
  2538. );
  2539. }
  2540. toJson() {
  2541. return {
  2542. name: this.name || 'xray0',
  2543. mtu: this._normalizeMtu(this.mtu),
  2544. gateway: this.gateway,
  2545. dns: this.dns,
  2546. userLevel: this.userLevel || 0,
  2547. autoSystemRoutingTable: this.autoSystemRoutingTable,
  2548. autoOutboundsInterface: this.autoOutboundsInterface,
  2549. };
  2550. }
  2551. };