inbound.js 89 KB

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