xray.js 79 KB

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