inbound.js 85 KB

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