inbound.js 84 KB

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