outbound.js 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215
  1. const Protocols = {
  2. Freedom: "freedom",
  3. Blackhole: "blackhole",
  4. DNS: "dns",
  5. VMess: "vmess",
  6. VLESS: "vless",
  7. Trojan: "trojan",
  8. Shadowsocks: "shadowsocks",
  9. Wireguard: "wireguard",
  10. Hysteria: "hysteria",
  11. Socks: "socks",
  12. HTTP: "http",
  13. };
  14. const SSMethods = {
  15. AES_256_GCM: 'aes-256-gcm',
  16. AES_128_GCM: 'aes-128-gcm',
  17. CHACHA20_POLY1305: 'chacha20-poly1305',
  18. CHACHA20_IETF_POLY1305: 'chacha20-ietf-poly1305',
  19. XCHACHA20_POLY1305: 'xchacha20-poly1305',
  20. XCHACHA20_IETF_POLY1305: 'xchacha20-ietf-poly1305',
  21. BLAKE3_AES_128_GCM: '2022-blake3-aes-128-gcm',
  22. BLAKE3_AES_256_GCM: '2022-blake3-aes-256-gcm',
  23. BLAKE3_CHACHA20_POLY1305: '2022-blake3-chacha20-poly1305',
  24. };
  25. const TLS_FLOW_CONTROL = {
  26. VISION: "xtls-rprx-vision",
  27. VISION_UDP443: "xtls-rprx-vision-udp443",
  28. };
  29. const UTLS_FINGERPRINT = {
  30. UTLS_CHROME: "chrome",
  31. UTLS_FIREFOX: "firefox",
  32. UTLS_SAFARI: "safari",
  33. UTLS_IOS: "ios",
  34. UTLS_android: "android",
  35. UTLS_EDGE: "edge",
  36. UTLS_360: "360",
  37. UTLS_QQ: "qq",
  38. UTLS_RANDOM: "random",
  39. UTLS_RANDOMIZED: "randomized",
  40. UTLS_RONDOMIZEDNOALPN: "randomizednoalpn",
  41. UTLS_UNSAFE: "unsafe",
  42. };
  43. const ALPN_OPTION = {
  44. H3: "h3",
  45. H2: "h2",
  46. HTTP1: "http/1.1",
  47. };
  48. const SNIFFING_OPTION = {
  49. HTTP: "http",
  50. TLS: "tls",
  51. QUIC: "quic",
  52. FAKEDNS: "fakedns"
  53. };
  54. const OutboundDomainStrategies = [
  55. "AsIs",
  56. "UseIP",
  57. "UseIPv4",
  58. "UseIPv6",
  59. "UseIPv6v4",
  60. "UseIPv4v6",
  61. "ForceIP",
  62. "ForceIPv6v4",
  63. "ForceIPv6",
  64. "ForceIPv4v6",
  65. "ForceIPv4"
  66. ];
  67. const WireguardDomainStrategy = [
  68. "ForceIP",
  69. "ForceIPv4",
  70. "ForceIPv4v6",
  71. "ForceIPv6",
  72. "ForceIPv6v4"
  73. ];
  74. const USERS_SECURITY = {
  75. AES_128_GCM: "aes-128-gcm",
  76. CHACHA20_POLY1305: "chacha20-poly1305",
  77. AUTO: "auto",
  78. NONE: "none",
  79. ZERO: "zero",
  80. };
  81. const MODE_OPTION = {
  82. AUTO: "auto",
  83. PACKET_UP: "packet-up",
  84. STREAM_UP: "stream-up",
  85. STREAM_ONE: "stream-one",
  86. };
  87. const Address_Port_Strategy = {
  88. NONE: "none",
  89. SrvPortOnly: "srvportonly",
  90. SrvAddressOnly: "srvaddressonly",
  91. SrvPortAndAddress: "srvportandaddress",
  92. TxtPortOnly: "txtportonly",
  93. TxtAddressOnly: "txtaddressonly",
  94. TxtPortAndAddress: "txtportandaddress"
  95. };
  96. const DNSRuleActions = ['direct', 'drop', 'reject', 'hijack'];
  97. function normalizeDNSRuleField(value) {
  98. if (value === null || value === undefined) {
  99. return '';
  100. }
  101. if (Array.isArray(value)) {
  102. return value.map(item => item.toString().trim()).filter(item => item.length > 0).join(',');
  103. }
  104. return value.toString().trim();
  105. }
  106. function normalizeDNSRuleAction(action) {
  107. action = ObjectUtil.isEmpty(action) ? 'direct' : action.toString().toLowerCase().trim();
  108. return DNSRuleActions.includes(action) ? action : 'direct';
  109. }
  110. function parseLegacyDNSBlockTypes(blockTypes) {
  111. if (blockTypes === null || blockTypes === undefined || blockTypes === '') {
  112. return [];
  113. }
  114. if (Array.isArray(blockTypes)) {
  115. return blockTypes
  116. .map(item => Number(item))
  117. .filter(item => Number.isInteger(item) && item >= 0 && item <= 65535);
  118. }
  119. if (typeof blockTypes === 'number') {
  120. return Number.isInteger(blockTypes) && blockTypes >= 0 && blockTypes <= 65535 ? [blockTypes] : [];
  121. }
  122. return blockTypes
  123. .toString()
  124. .split(',')
  125. .map(item => item.trim())
  126. .filter(item => /^\d+$/.test(item))
  127. .map(item => Number(item))
  128. .filter(item => item >= 0 && item <= 65535);
  129. }
  130. function buildLegacyDNSRules(nonIPQuery, blockTypes) {
  131. const mode = ['reject', 'drop', 'skip'].includes(nonIPQuery) ? nonIPQuery : 'reject';
  132. const rules = [];
  133. const parsedBlockTypes = parseLegacyDNSBlockTypes(blockTypes);
  134. if (parsedBlockTypes.length > 0) {
  135. rules.push(new Outbound.DNSRule(mode === 'reject' ? 'reject' : 'drop', parsedBlockTypes.join(',')));
  136. }
  137. rules.push(new Outbound.DNSRule('hijack', '1,28'));
  138. rules.push(new Outbound.DNSRule(mode === 'skip' ? 'direct' : mode));
  139. return rules;
  140. }
  141. function getDNSRulesFromJson(json = {}) {
  142. if (Array.isArray(json.rules) && json.rules.length > 0) {
  143. return json.rules.map(rule => Outbound.DNSRule.fromJson(rule));
  144. }
  145. if (json.nonIPQuery !== undefined || json.blockTypes !== undefined) {
  146. return buildLegacyDNSRules(json.nonIPQuery, json.blockTypes);
  147. }
  148. return [];
  149. }
  150. Object.freeze(Protocols);
  151. Object.freeze(SSMethods);
  152. Object.freeze(TLS_FLOW_CONTROL);
  153. Object.freeze(UTLS_FINGERPRINT);
  154. Object.freeze(ALPN_OPTION);
  155. Object.freeze(SNIFFING_OPTION);
  156. Object.freeze(OutboundDomainStrategies);
  157. Object.freeze(WireguardDomainStrategy);
  158. Object.freeze(USERS_SECURITY);
  159. Object.freeze(MODE_OPTION);
  160. Object.freeze(Address_Port_Strategy);
  161. Object.freeze(DNSRuleActions);
  162. class CommonClass {
  163. static toJsonArray(arr) {
  164. return arr.map(obj => obj.toJson());
  165. }
  166. static fromJson() {
  167. return new CommonClass();
  168. }
  169. toJson() {
  170. return this;
  171. }
  172. toString(format = true) {
  173. return format ? JSON.stringify(this.toJson(), null, 2) : JSON.stringify(this.toJson());
  174. }
  175. }
  176. class ReverseSniffing extends CommonClass {
  177. constructor(
  178. enabled = false,
  179. destOverride = ['http', 'tls', 'quic', 'fakedns'],
  180. metadataOnly = false,
  181. routeOnly = false,
  182. ipsExcluded = [],
  183. domainsExcluded = [],
  184. ) {
  185. super();
  186. this.enabled = enabled;
  187. this.destOverride = Array.isArray(destOverride) && destOverride.length > 0 ? destOverride : ['http', 'tls', 'quic', 'fakedns'];
  188. this.metadataOnly = metadataOnly;
  189. this.routeOnly = routeOnly;
  190. this.ipsExcluded = Array.isArray(ipsExcluded) ? ipsExcluded : [];
  191. this.domainsExcluded = Array.isArray(domainsExcluded) ? domainsExcluded : [];
  192. }
  193. static fromJson(json = {}) {
  194. if (!json || Object.keys(json).length === 0) {
  195. return new ReverseSniffing();
  196. }
  197. return new ReverseSniffing(
  198. !!json.enabled,
  199. json.destOverride,
  200. json.metadataOnly,
  201. json.routeOnly,
  202. json.ipsExcluded || [],
  203. json.domainsExcluded || [],
  204. );
  205. }
  206. toJson() {
  207. return {
  208. enabled: this.enabled,
  209. destOverride: this.destOverride,
  210. metadataOnly: this.metadataOnly,
  211. routeOnly: this.routeOnly,
  212. ipsExcluded: this.ipsExcluded.length > 0 ? this.ipsExcluded : undefined,
  213. domainsExcluded: this.domainsExcluded.length > 0 ? this.domainsExcluded : undefined,
  214. };
  215. }
  216. }
  217. class TcpStreamSettings extends CommonClass {
  218. constructor(type = 'none', host, path) {
  219. super();
  220. this.type = type;
  221. this.host = host;
  222. this.path = path;
  223. }
  224. static fromJson(json = {}) {
  225. let header = json.header;
  226. if (!header) return new TcpStreamSettings();
  227. if (header.type == 'http' && header.request) {
  228. return new TcpStreamSettings(
  229. header.type,
  230. header.request.headers.Host.join(','),
  231. header.request.path.join(','),
  232. );
  233. }
  234. return new TcpStreamSettings(header.type, '', '');
  235. }
  236. toJson() {
  237. return {
  238. header: {
  239. type: this.type,
  240. request: this.type === 'http' ? {
  241. headers: {
  242. Host: ObjectUtil.isEmpty(this.host) ? [] : this.host.split(',')
  243. },
  244. path: ObjectUtil.isEmpty(this.path) ? ["/"] : this.path.split(',')
  245. } : undefined,
  246. }
  247. };
  248. }
  249. }
  250. class KcpStreamSettings extends CommonClass {
  251. constructor(
  252. mtu = 1350,
  253. tti = 20,
  254. uplinkCapacity = 5,
  255. downlinkCapacity = 20,
  256. cwndMultiplier = 1,
  257. maxSendingWindow = 1350,
  258. ) {
  259. super();
  260. this.mtu = mtu;
  261. this.tti = tti;
  262. this.upCap = uplinkCapacity;
  263. this.downCap = downlinkCapacity;
  264. this.cwndMultiplier = cwndMultiplier;
  265. this.maxSendingWindow = maxSendingWindow;
  266. }
  267. static fromJson(json = {}) {
  268. return new KcpStreamSettings(
  269. json.mtu,
  270. json.tti,
  271. json.uplinkCapacity,
  272. json.downlinkCapacity,
  273. json.cwndMultiplier,
  274. json.maxSendingWindow,
  275. );
  276. }
  277. toJson() {
  278. return {
  279. mtu: this.mtu,
  280. tti: this.tti,
  281. uplinkCapacity: this.upCap,
  282. downlinkCapacity: this.downCap,
  283. cwndMultiplier: this.cwndMultiplier,
  284. maxSendingWindow: this.maxSendingWindow,
  285. };
  286. }
  287. }
  288. class WsStreamSettings extends CommonClass {
  289. constructor(
  290. path = '/',
  291. host = '',
  292. heartbeatPeriod = 0,
  293. ) {
  294. super();
  295. this.path = path;
  296. this.host = host;
  297. this.heartbeatPeriod = heartbeatPeriod;
  298. }
  299. static fromJson(json = {}) {
  300. return new WsStreamSettings(
  301. json.path,
  302. json.host,
  303. json.heartbeatPeriod,
  304. );
  305. }
  306. toJson() {
  307. return {
  308. path: this.path,
  309. host: this.host,
  310. heartbeatPeriod: this.heartbeatPeriod
  311. };
  312. }
  313. }
  314. class GrpcStreamSettings extends CommonClass {
  315. constructor(
  316. serviceName = "",
  317. authority = "",
  318. multiMode = false
  319. ) {
  320. super();
  321. this.serviceName = serviceName;
  322. this.authority = authority;
  323. this.multiMode = multiMode;
  324. }
  325. static fromJson(json = {}) {
  326. return new GrpcStreamSettings(json.serviceName, json.authority, json.multiMode);
  327. }
  328. toJson() {
  329. return {
  330. serviceName: this.serviceName,
  331. authority: this.authority,
  332. multiMode: this.multiMode
  333. }
  334. }
  335. }
  336. class HttpUpgradeStreamSettings extends CommonClass {
  337. constructor(path = '/', host = '') {
  338. super();
  339. this.path = path;
  340. this.host = host;
  341. }
  342. static fromJson(json = {}) {
  343. return new HttpUpgradeStreamSettings(
  344. json.path,
  345. json.host,
  346. );
  347. }
  348. toJson() {
  349. return {
  350. path: this.path,
  351. host: this.host,
  352. };
  353. }
  354. }
  355. // Mirrors the outbound (client-side) view of Xray-core's SplitHTTPConfig
  356. // (infra/conf/transport_internet.go). Only fields the client actually
  357. // reads at runtime, plus the bidirectional fields the client must match
  358. // against the server, live here. Server-only fields (noSSEHeader,
  359. // scMaxBufferedPosts, scStreamUpServerSecs, serverMaxHeaderBytes) belong
  360. // on the inbound class instead.
  361. class xHTTPStreamSettings extends CommonClass {
  362. constructor(
  363. // Bidirectional — must match the inbound side
  364. path = '/',
  365. host = '',
  366. mode = '',
  367. xPaddingBytes = "100-1000",
  368. xPaddingObfsMode = false,
  369. xPaddingKey = '',
  370. xPaddingHeader = '',
  371. xPaddingPlacement = '',
  372. xPaddingMethod = '',
  373. sessionPlacement = '',
  374. sessionKey = '',
  375. seqPlacement = '',
  376. seqKey = '',
  377. uplinkDataPlacement = '',
  378. uplinkDataKey = '',
  379. scMaxEachPostBytes = "1000000",
  380. // Client-side only
  381. headers = [],
  382. uplinkHTTPMethod = '',
  383. uplinkChunkSize = 0,
  384. noGRPCHeader = false,
  385. scMinPostsIntervalMs = "30",
  386. xmux = {
  387. maxConcurrency: "16-32",
  388. maxConnections: 0,
  389. cMaxReuseTimes: 0,
  390. hMaxRequestTimes: "600-900",
  391. hMaxReusableSecs: "1800-3000",
  392. hKeepAlivePeriod: 0,
  393. },
  394. // UI-only toggle — controls whether the XMUX block is expanded in
  395. // the form (mirrors the QUIC Params switch in stream_finalmask).
  396. // Never serialized; toJson() only emits the xmux block itself.
  397. enableXmux = false,
  398. ) {
  399. super();
  400. this.path = path;
  401. this.host = host;
  402. this.mode = mode;
  403. this.xPaddingBytes = xPaddingBytes;
  404. this.xPaddingObfsMode = xPaddingObfsMode;
  405. this.xPaddingKey = xPaddingKey;
  406. this.xPaddingHeader = xPaddingHeader;
  407. this.xPaddingPlacement = xPaddingPlacement;
  408. this.xPaddingMethod = xPaddingMethod;
  409. this.sessionPlacement = sessionPlacement;
  410. this.sessionKey = sessionKey;
  411. this.seqPlacement = seqPlacement;
  412. this.seqKey = seqKey;
  413. this.uplinkDataPlacement = uplinkDataPlacement;
  414. this.uplinkDataKey = uplinkDataKey;
  415. this.scMaxEachPostBytes = scMaxEachPostBytes;
  416. this.headers = headers;
  417. this.uplinkHTTPMethod = uplinkHTTPMethod;
  418. this.uplinkChunkSize = uplinkChunkSize;
  419. this.noGRPCHeader = noGRPCHeader;
  420. this.scMinPostsIntervalMs = scMinPostsIntervalMs;
  421. this.xmux = xmux;
  422. this.enableXmux = enableXmux;
  423. }
  424. addHeader(name, value) {
  425. this.headers.push({ name: name, value: value });
  426. }
  427. removeHeader(index) {
  428. this.headers.splice(index, 1);
  429. }
  430. static fromJson(json = {}) {
  431. const headersInput = json.headers;
  432. let headers = [];
  433. if (Array.isArray(headersInput)) {
  434. headers = headersInput;
  435. } else if (headersInput && typeof headersInput === 'object') {
  436. // Upstream uses a {name: value} map; convert to the panel's [{name, value}] form.
  437. headers = Object.entries(headersInput).map(([name, value]) => ({ name, value }));
  438. }
  439. return new xHTTPStreamSettings(
  440. json.path,
  441. json.host,
  442. json.mode,
  443. json.xPaddingBytes,
  444. json.xPaddingObfsMode,
  445. json.xPaddingKey,
  446. json.xPaddingHeader,
  447. json.xPaddingPlacement,
  448. json.xPaddingMethod,
  449. json.sessionPlacement,
  450. json.sessionKey,
  451. json.seqPlacement,
  452. json.seqKey,
  453. json.uplinkDataPlacement,
  454. json.uplinkDataKey,
  455. json.scMaxEachPostBytes,
  456. headers,
  457. json.uplinkHTTPMethod,
  458. json.uplinkChunkSize,
  459. json.noGRPCHeader,
  460. json.scMinPostsIntervalMs,
  461. json.xmux,
  462. // Auto-toggle the XMUX switch on when an existing outbound has
  463. // the xmux key saved, so users editing such configs see their
  464. // values immediately.
  465. json.xmux !== undefined,
  466. );
  467. }
  468. toJson() {
  469. // Upstream expects headers as a {name: value} map, not a list of entries.
  470. const headersMap = {};
  471. if (Array.isArray(this.headers)) {
  472. for (const h of this.headers) {
  473. if (h && h.name) headersMap[h.name] = h.value || '';
  474. }
  475. }
  476. return {
  477. path: this.path,
  478. host: this.host,
  479. mode: this.mode,
  480. xPaddingBytes: this.xPaddingBytes,
  481. xPaddingObfsMode: this.xPaddingObfsMode,
  482. xPaddingKey: this.xPaddingKey,
  483. xPaddingHeader: this.xPaddingHeader,
  484. xPaddingPlacement: this.xPaddingPlacement,
  485. xPaddingMethod: this.xPaddingMethod,
  486. sessionPlacement: this.sessionPlacement,
  487. sessionKey: this.sessionKey,
  488. seqPlacement: this.seqPlacement,
  489. seqKey: this.seqKey,
  490. uplinkDataPlacement: this.uplinkDataPlacement,
  491. uplinkDataKey: this.uplinkDataKey,
  492. scMaxEachPostBytes: this.scMaxEachPostBytes,
  493. headers: headersMap,
  494. uplinkHTTPMethod: this.uplinkHTTPMethod,
  495. uplinkChunkSize: this.uplinkChunkSize,
  496. noGRPCHeader: this.noGRPCHeader,
  497. scMinPostsIntervalMs: this.scMinPostsIntervalMs,
  498. xmux: {
  499. maxConcurrency: this.xmux.maxConcurrency,
  500. maxConnections: this.xmux.maxConnections,
  501. cMaxReuseTimes: this.xmux.cMaxReuseTimes,
  502. hMaxRequestTimes: this.xmux.hMaxRequestTimes,
  503. hMaxReusableSecs: this.xmux.hMaxReusableSecs,
  504. hKeepAlivePeriod: this.xmux.hKeepAlivePeriod,
  505. },
  506. };
  507. }
  508. }
  509. class TlsStreamSettings extends CommonClass {
  510. constructor(
  511. serverName = '',
  512. alpn = [],
  513. fingerprint = '',
  514. echConfigList = '',
  515. verifyPeerCertByName = '',
  516. pinnedPeerCertSha256 = '',
  517. ) {
  518. super();
  519. this.serverName = serverName;
  520. this.alpn = alpn;
  521. this.fingerprint = fingerprint;
  522. this.echConfigList = echConfigList;
  523. this.verifyPeerCertByName = verifyPeerCertByName;
  524. this.pinnedPeerCertSha256 = pinnedPeerCertSha256;
  525. }
  526. static fromJson(json = {}) {
  527. return new TlsStreamSettings(
  528. json.serverName,
  529. json.alpn,
  530. json.fingerprint,
  531. json.echConfigList,
  532. json.verifyPeerCertByName,
  533. json.pinnedPeerCertSha256,
  534. );
  535. }
  536. toJson() {
  537. return {
  538. serverName: this.serverName,
  539. alpn: this.alpn,
  540. fingerprint: this.fingerprint,
  541. echConfigList: this.echConfigList,
  542. verifyPeerCertByName: this.verifyPeerCertByName,
  543. pinnedPeerCertSha256: this.pinnedPeerCertSha256
  544. };
  545. }
  546. }
  547. class RealityStreamSettings extends CommonClass {
  548. constructor(
  549. publicKey = '',
  550. fingerprint = '',
  551. serverName = '',
  552. shortId = '',
  553. spiderX = '',
  554. mldsa65Verify = ''
  555. ) {
  556. super();
  557. this.publicKey = publicKey;
  558. this.fingerprint = fingerprint;
  559. this.serverName = serverName;
  560. this.shortId = shortId
  561. this.spiderX = spiderX;
  562. this.mldsa65Verify = mldsa65Verify;
  563. }
  564. static fromJson(json = {}) {
  565. return new RealityStreamSettings(
  566. json.publicKey,
  567. json.fingerprint,
  568. json.serverName,
  569. json.shortId,
  570. json.spiderX,
  571. json.mldsa65Verify
  572. );
  573. }
  574. toJson() {
  575. return {
  576. publicKey: this.publicKey,
  577. fingerprint: this.fingerprint,
  578. serverName: this.serverName,
  579. shortId: this.shortId,
  580. spiderX: this.spiderX,
  581. mldsa65Verify: this.mldsa65Verify
  582. };
  583. }
  584. };
  585. class HysteriaStreamSettings extends CommonClass {
  586. constructor(
  587. version = 2,
  588. auth = '',
  589. congestion = '',
  590. up = '0',
  591. down = '0',
  592. udphopPort = '',
  593. udphopIntervalMin = 30,
  594. udphopIntervalMax = 30,
  595. initStreamReceiveWindow = 8388608,
  596. maxStreamReceiveWindow = 8388608,
  597. initConnectionReceiveWindow = 20971520,
  598. maxConnectionReceiveWindow = 20971520,
  599. maxIdleTimeout = 30,
  600. keepAlivePeriod = 2,
  601. disablePathMTUDiscovery = false
  602. ) {
  603. super();
  604. this.version = version;
  605. this.auth = auth;
  606. this.congestion = congestion;
  607. this.up = up;
  608. this.down = down;
  609. this.udphopPort = udphopPort;
  610. this.udphopIntervalMin = udphopIntervalMin;
  611. this.udphopIntervalMax = udphopIntervalMax;
  612. this.initStreamReceiveWindow = initStreamReceiveWindow;
  613. this.maxStreamReceiveWindow = maxStreamReceiveWindow;
  614. this.initConnectionReceiveWindow = initConnectionReceiveWindow;
  615. this.maxConnectionReceiveWindow = maxConnectionReceiveWindow;
  616. this.maxIdleTimeout = maxIdleTimeout;
  617. this.keepAlivePeriod = keepAlivePeriod;
  618. this.disablePathMTUDiscovery = disablePathMTUDiscovery;
  619. }
  620. static fromJson(json = {}) {
  621. let udphopPort = '';
  622. let udphopIntervalMin = 30;
  623. let udphopIntervalMax = 30;
  624. if (json.udphop) {
  625. udphopPort = json.udphop.port || '';
  626. // Backward compatibility: if old 'interval' exists, use it for both min/max
  627. if (json.udphop.interval !== undefined) {
  628. udphopIntervalMin = json.udphop.interval;
  629. udphopIntervalMax = json.udphop.interval;
  630. } else {
  631. udphopIntervalMin = json.udphop.intervalMin || 30;
  632. udphopIntervalMax = json.udphop.intervalMax || 30;
  633. }
  634. }
  635. return new HysteriaStreamSettings(
  636. json.version,
  637. json.auth,
  638. json.congestion,
  639. json.up,
  640. json.down,
  641. udphopPort,
  642. udphopIntervalMin,
  643. udphopIntervalMax,
  644. json.initStreamReceiveWindow,
  645. json.maxStreamReceiveWindow,
  646. json.initConnectionReceiveWindow,
  647. json.maxConnectionReceiveWindow,
  648. json.maxIdleTimeout,
  649. json.keepAlivePeriod,
  650. json.disablePathMTUDiscovery
  651. );
  652. }
  653. toJson() {
  654. const result = {
  655. version: this.version,
  656. auth: this.auth,
  657. congestion: this.congestion,
  658. up: this.up,
  659. down: this.down,
  660. initStreamReceiveWindow: this.initStreamReceiveWindow,
  661. maxStreamReceiveWindow: this.maxStreamReceiveWindow,
  662. initConnectionReceiveWindow: this.initConnectionReceiveWindow,
  663. maxConnectionReceiveWindow: this.maxConnectionReceiveWindow,
  664. maxIdleTimeout: this.maxIdleTimeout,
  665. keepAlivePeriod: this.keepAlivePeriod,
  666. disablePathMTUDiscovery: this.disablePathMTUDiscovery
  667. };
  668. if (this.udphopPort) {
  669. result.udphop = {
  670. port: this.udphopPort,
  671. intervalMin: this.udphopIntervalMin,
  672. intervalMax: this.udphopIntervalMax
  673. };
  674. }
  675. return result;
  676. }
  677. };
  678. class SockoptStreamSettings extends CommonClass {
  679. constructor(
  680. dialerProxy = "",
  681. tcpFastOpen = false,
  682. tcpKeepAliveInterval = 0,
  683. tcpMptcp = false,
  684. penetrate = false,
  685. addressPortStrategy = Address_Port_Strategy.NONE,
  686. trustedXForwardedFor = [],
  687. ) {
  688. super();
  689. this.dialerProxy = dialerProxy;
  690. this.tcpFastOpen = tcpFastOpen;
  691. this.tcpKeepAliveInterval = tcpKeepAliveInterval;
  692. this.tcpMptcp = tcpMptcp;
  693. this.penetrate = penetrate;
  694. this.addressPortStrategy = addressPortStrategy;
  695. this.trustedXForwardedFor = trustedXForwardedFor;
  696. }
  697. static fromJson(json = {}) {
  698. if (Object.keys(json).length === 0) return undefined;
  699. return new SockoptStreamSettings(
  700. json.dialerProxy,
  701. json.tcpFastOpen,
  702. json.tcpKeepAliveInterval,
  703. json.tcpMptcp,
  704. json.penetrate,
  705. json.addressPortStrategy,
  706. json.trustedXForwardedFor || []
  707. );
  708. }
  709. toJson() {
  710. const result = {
  711. dialerProxy: this.dialerProxy,
  712. tcpFastOpen: this.tcpFastOpen,
  713. tcpKeepAliveInterval: this.tcpKeepAliveInterval,
  714. tcpMptcp: this.tcpMptcp,
  715. penetrate: this.penetrate,
  716. addressPortStrategy: this.addressPortStrategy
  717. };
  718. if (this.trustedXForwardedFor && this.trustedXForwardedFor.length > 0) {
  719. result.trustedXForwardedFor = this.trustedXForwardedFor;
  720. }
  721. return result;
  722. }
  723. }
  724. class UdpMask extends CommonClass {
  725. constructor(type = 'salamander', settings = {}) {
  726. super();
  727. this.type = type;
  728. this.settings = this._getDefaultSettings(type, settings);
  729. }
  730. _getDefaultSettings(type, settings = {}) {
  731. switch (type) {
  732. case 'salamander':
  733. case 'mkcp-aes128gcm':
  734. return { password: settings.password || '' };
  735. case 'header-dns':
  736. return { domain: settings.domain || '' };
  737. case 'xdns':
  738. return { resolvers: Array.isArray(settings.resolvers) ? settings.resolvers : [] };
  739. case 'xicmp':
  740. return { ip: settings.ip || '', id: settings.id ?? 0 };
  741. case 'mkcp-original':
  742. case 'header-dtls':
  743. case 'header-srtp':
  744. case 'header-utp':
  745. case 'header-wechat':
  746. case 'header-wireguard':
  747. return {}; // No settings needed
  748. case 'header-custom':
  749. return {
  750. client: Array.isArray(settings.client) ? settings.client : [],
  751. server: Array.isArray(settings.server) ? settings.server : [],
  752. };
  753. case 'noise':
  754. return {
  755. reset: settings.reset ?? 0,
  756. noise: Array.isArray(settings.noise) ? settings.noise : [],
  757. };
  758. case 'sudoku':
  759. return {
  760. ascii: settings.ascii || '',
  761. customTable: settings.customTable || '',
  762. customTables: Array.isArray(settings.customTables) ? settings.customTables : [],
  763. paddingMin: settings.paddingMin ?? 0,
  764. paddingMax: settings.paddingMax ?? 0
  765. };
  766. default:
  767. return settings;
  768. }
  769. }
  770. static fromJson(json = {}) {
  771. return new UdpMask(
  772. json.type || 'salamander',
  773. json.settings || {}
  774. );
  775. }
  776. toJson() {
  777. const cleanItem = item => {
  778. const out = { ...item };
  779. if (out.type === 'array') {
  780. delete out.packet;
  781. } else {
  782. delete out.rand;
  783. delete out.randRange;
  784. }
  785. return out;
  786. };
  787. let settings = this.settings;
  788. if (this.type === 'noise' && settings && Array.isArray(settings.noise)) {
  789. settings = { ...settings, noise: settings.noise.map(cleanItem) };
  790. } else if (this.type === 'header-custom' && settings) {
  791. settings = {
  792. ...settings,
  793. client: Array.isArray(settings.client) ? settings.client.map(cleanItem) : settings.client,
  794. server: Array.isArray(settings.server) ? settings.server.map(cleanItem) : settings.server,
  795. };
  796. }
  797. return {
  798. type: this.type,
  799. settings: (settings && Object.keys(settings).length > 0) ? settings : undefined
  800. };
  801. }
  802. }
  803. class TcpMask extends CommonClass {
  804. constructor(type = 'fragment', settings = {}) {
  805. super();
  806. this.type = type;
  807. this.settings = this._getDefaultSettings(type, settings);
  808. }
  809. _getDefaultSettings(type, settings = {}) {
  810. switch (type) {
  811. case 'fragment':
  812. return {
  813. packets: settings.packets ?? 'tlshello',
  814. length: settings.length ?? '',
  815. delay: settings.delay ?? '',
  816. maxSplit: settings.maxSplit ?? '',
  817. };
  818. case 'sudoku':
  819. return {
  820. password: settings.password ?? '',
  821. ascii: settings.ascii ?? '',
  822. customTable: settings.customTable ?? '',
  823. customTables: Array.isArray(settings.customTables) ? settings.customTables : [],
  824. paddingMin: settings.paddingMin ?? 0,
  825. paddingMax: settings.paddingMax ?? 0,
  826. };
  827. case 'header-custom':
  828. return {
  829. clients: Array.isArray(settings.clients) ? settings.clients : [],
  830. servers: Array.isArray(settings.servers) ? settings.servers : [],
  831. };
  832. default:
  833. return settings;
  834. }
  835. }
  836. static fromJson(json = {}) {
  837. return new TcpMask(
  838. json.type || 'fragment',
  839. json.settings || {}
  840. );
  841. }
  842. toJson() {
  843. const cleanItem = item => {
  844. const out = { ...item };
  845. if (out.type === 'array') {
  846. delete out.packet;
  847. } else {
  848. delete out.rand;
  849. delete out.randRange;
  850. }
  851. return out;
  852. };
  853. let settings = this.settings;
  854. if (this.type === 'header-custom' && settings) {
  855. const cleanGroup = group => Array.isArray(group) ? group.map(cleanItem) : group;
  856. settings = {
  857. ...settings,
  858. clients: Array.isArray(settings.clients) ? settings.clients.map(cleanGroup) : settings.clients,
  859. servers: Array.isArray(settings.servers) ? settings.servers.map(cleanGroup) : settings.servers,
  860. };
  861. }
  862. return {
  863. type: this.type,
  864. settings: (settings && Object.keys(settings).length > 0) ? settings : undefined
  865. };
  866. }
  867. }
  868. class QuicParams extends CommonClass {
  869. constructor(
  870. congestion = 'bbr',
  871. debug = false,
  872. brutalUp = 65537,
  873. brutalDown = 65537,
  874. udpHop = undefined,
  875. initStreamReceiveWindow = 8388608,
  876. maxStreamReceiveWindow = 8388608,
  877. initConnectionReceiveWindow = 20971520,
  878. maxConnectionReceiveWindow = 20971520,
  879. maxIdleTimeout = 30,
  880. keepAlivePeriod = 5,
  881. disablePathMTUDiscovery = false,
  882. maxIncomingStreams = 1024,
  883. ) {
  884. super();
  885. this.congestion = congestion;
  886. this.debug = debug;
  887. this.brutalUp = brutalUp;
  888. this.brutalDown = brutalDown;
  889. this.udpHop = udpHop;
  890. this.initStreamReceiveWindow = initStreamReceiveWindow;
  891. this.maxStreamReceiveWindow = maxStreamReceiveWindow;
  892. this.initConnectionReceiveWindow = initConnectionReceiveWindow;
  893. this.maxConnectionReceiveWindow = maxConnectionReceiveWindow;
  894. this.maxIdleTimeout = maxIdleTimeout;
  895. this.keepAlivePeriod = keepAlivePeriod;
  896. this.disablePathMTUDiscovery = disablePathMTUDiscovery;
  897. this.maxIncomingStreams = maxIncomingStreams;
  898. }
  899. get hasUdpHop() {
  900. return this.udpHop != null;
  901. }
  902. set hasUdpHop(value) {
  903. this.udpHop = value ? (this.udpHop || { ports: '20000-50000', interval: '5-10' }) : undefined;
  904. }
  905. static fromJson(json = {}) {
  906. if (!json || Object.keys(json).length === 0) return undefined;
  907. return new QuicParams(
  908. json.congestion,
  909. json.debug,
  910. json.brutalUp,
  911. json.brutalDown,
  912. json.udpHop ? { ports: json.udpHop.ports, interval: json.udpHop.interval } : undefined,
  913. json.initStreamReceiveWindow,
  914. json.maxStreamReceiveWindow,
  915. json.initConnectionReceiveWindow,
  916. json.maxConnectionReceiveWindow,
  917. json.maxIdleTimeout,
  918. json.keepAlivePeriod,
  919. json.disablePathMTUDiscovery,
  920. json.maxIncomingStreams,
  921. );
  922. }
  923. toJson() {
  924. const result = { congestion: this.congestion };
  925. if (this.debug) result.debug = this.debug;
  926. if (['brutal', 'force-brutal'].includes(this.congestion)) {
  927. if (this.brutalUp) result.brutalUp = this.brutalUp;
  928. if (this.brutalDown) result.brutalDown = this.brutalDown;
  929. }
  930. if (this.udpHop) result.udpHop = { ports: this.udpHop.ports, interval: this.udpHop.interval };
  931. if (this.initStreamReceiveWindow > 0) result.initStreamReceiveWindow = this.initStreamReceiveWindow;
  932. if (this.maxStreamReceiveWindow > 0) result.maxStreamReceiveWindow = this.maxStreamReceiveWindow;
  933. if (this.initConnectionReceiveWindow > 0) result.initConnectionReceiveWindow = this.initConnectionReceiveWindow;
  934. if (this.maxConnectionReceiveWindow > 0) result.maxConnectionReceiveWindow = this.maxConnectionReceiveWindow;
  935. if (this.maxIdleTimeout !== 30 && this.maxIdleTimeout > 0) result.maxIdleTimeout = this.maxIdleTimeout;
  936. if (this.keepAlivePeriod > 0) result.keepAlivePeriod = this.keepAlivePeriod;
  937. if (this.disablePathMTUDiscovery) result.disablePathMTUDiscovery = this.disablePathMTUDiscovery;
  938. if (this.maxIncomingStreams > 0) result.maxIncomingStreams = this.maxIncomingStreams;
  939. return result;
  940. }
  941. }
  942. class FinalMaskStreamSettings extends CommonClass {
  943. constructor(tcp = [], udp = [], quicParams = undefined) {
  944. super();
  945. this.tcp = Array.isArray(tcp) ? tcp.map(t => t instanceof TcpMask ? t : new TcpMask(t.type, t.settings)) : [];
  946. this.udp = Array.isArray(udp) ? udp.map(u => new UdpMask(u.type, u.settings)) : [new UdpMask(udp.type, udp.settings)];
  947. this.quicParams = quicParams instanceof QuicParams ? quicParams : (quicParams ? QuicParams.fromJson(quicParams) : undefined);
  948. }
  949. get enableQuicParams() {
  950. return this.quicParams != null;
  951. }
  952. set enableQuicParams(value) {
  953. this.quicParams = value ? (this.quicParams || new QuicParams()) : undefined;
  954. }
  955. static fromJson(json = {}) {
  956. return new FinalMaskStreamSettings(
  957. json.tcp || [],
  958. json.udp || [],
  959. json.quicParams ? QuicParams.fromJson(json.quicParams) : undefined,
  960. );
  961. }
  962. toJson() {
  963. const result = {};
  964. if (this.tcp && this.tcp.length > 0) {
  965. result.tcp = this.tcp.map(t => t.toJson());
  966. }
  967. if (this.udp && this.udp.length > 0) {
  968. result.udp = this.udp.map(udp => udp.toJson());
  969. }
  970. if (this.quicParams) {
  971. result.quicParams = this.quicParams.toJson();
  972. }
  973. return result;
  974. }
  975. }
  976. class StreamSettings extends CommonClass {
  977. constructor(
  978. network = 'tcp',
  979. security = 'none',
  980. tlsSettings = new TlsStreamSettings(),
  981. realitySettings = new RealityStreamSettings(),
  982. tcpSettings = new TcpStreamSettings(),
  983. kcpSettings = new KcpStreamSettings(),
  984. wsSettings = new WsStreamSettings(),
  985. grpcSettings = new GrpcStreamSettings(),
  986. httpupgradeSettings = new HttpUpgradeStreamSettings(),
  987. xhttpSettings = new xHTTPStreamSettings(),
  988. hysteriaSettings = new HysteriaStreamSettings(),
  989. finalmask = new FinalMaskStreamSettings(),
  990. sockopt = undefined,
  991. ) {
  992. super();
  993. this.network = network;
  994. this.security = security;
  995. this.tls = tlsSettings;
  996. this.reality = realitySettings;
  997. this.tcp = tcpSettings;
  998. this.kcp = kcpSettings;
  999. this.ws = wsSettings;
  1000. this.grpc = grpcSettings;
  1001. this.httpupgrade = httpupgradeSettings;
  1002. this.xhttp = xhttpSettings;
  1003. this.hysteria = hysteriaSettings;
  1004. this.finalmask = finalmask;
  1005. this.sockopt = sockopt;
  1006. }
  1007. addTcpMask(type = 'fragment') {
  1008. this.finalmask.tcp.push(new TcpMask(type));
  1009. }
  1010. delTcpMask(index) {
  1011. if (this.finalmask.tcp) {
  1012. this.finalmask.tcp.splice(index, 1);
  1013. }
  1014. }
  1015. addUdpMask(type = 'salamander') {
  1016. this.finalmask.udp.push(new UdpMask(type));
  1017. }
  1018. delUdpMask(index) {
  1019. if (this.finalmask.udp) {
  1020. this.finalmask.udp.splice(index, 1);
  1021. }
  1022. }
  1023. get hasFinalMask() {
  1024. const hasTcp = this.finalmask.tcp && this.finalmask.tcp.length > 0;
  1025. const hasUdp = this.finalmask.udp && this.finalmask.udp.length > 0;
  1026. const hasQuicParams = this.finalmask.quicParams != null;
  1027. return hasTcp || hasUdp || hasQuicParams;
  1028. }
  1029. get isTls() {
  1030. return this.security === 'tls';
  1031. }
  1032. get isReality() {
  1033. return this.security === "reality";
  1034. }
  1035. get sockoptSwitch() {
  1036. return this.sockopt != undefined;
  1037. }
  1038. set sockoptSwitch(value) {
  1039. this.sockopt = value ? new SockoptStreamSettings() : undefined;
  1040. }
  1041. static fromJson(json = {}) {
  1042. return new StreamSettings(
  1043. json.network,
  1044. json.security,
  1045. TlsStreamSettings.fromJson(json.tlsSettings),
  1046. RealityStreamSettings.fromJson(json.realitySettings),
  1047. TcpStreamSettings.fromJson(json.tcpSettings),
  1048. KcpStreamSettings.fromJson(json.kcpSettings),
  1049. WsStreamSettings.fromJson(json.wsSettings),
  1050. GrpcStreamSettings.fromJson(json.grpcSettings),
  1051. HttpUpgradeStreamSettings.fromJson(json.httpupgradeSettings),
  1052. xHTTPStreamSettings.fromJson(json.xhttpSettings),
  1053. HysteriaStreamSettings.fromJson(json.hysteriaSettings),
  1054. FinalMaskStreamSettings.fromJson(json.finalmask),
  1055. SockoptStreamSettings.fromJson(json.sockopt),
  1056. );
  1057. }
  1058. toJson() {
  1059. const network = this.network;
  1060. return {
  1061. network: network,
  1062. security: this.security,
  1063. tlsSettings: this.security == 'tls' ? this.tls.toJson() : undefined,
  1064. realitySettings: this.security == 'reality' ? this.reality.toJson() : undefined,
  1065. tcpSettings: network === 'tcp' ? this.tcp.toJson() : undefined,
  1066. kcpSettings: network === 'kcp' ? this.kcp.toJson() : undefined,
  1067. wsSettings: network === 'ws' ? this.ws.toJson() : undefined,
  1068. grpcSettings: network === 'grpc' ? this.grpc.toJson() : undefined,
  1069. httpupgradeSettings: network === 'httpupgrade' ? this.httpupgrade.toJson() : undefined,
  1070. xhttpSettings: network === 'xhttp' ? this.xhttp.toJson() : undefined,
  1071. hysteriaSettings: network === 'hysteria' ? this.hysteria.toJson() : undefined,
  1072. finalmask: this.hasFinalMask ? this.finalmask.toJson() : undefined,
  1073. sockopt: this.sockopt != undefined ? this.sockopt.toJson() : undefined,
  1074. };
  1075. }
  1076. }
  1077. class Mux extends CommonClass {
  1078. constructor(enabled = false, concurrency = 8, xudpConcurrency = 16, xudpProxyUDP443 = "reject") {
  1079. super();
  1080. this.enabled = enabled;
  1081. this.concurrency = concurrency;
  1082. this.xudpConcurrency = xudpConcurrency;
  1083. this.xudpProxyUDP443 = xudpProxyUDP443;
  1084. }
  1085. static fromJson(json = {}) {
  1086. if (Object.keys(json).length === 0) return undefined;
  1087. return new Mux(
  1088. json.enabled,
  1089. json.concurrency,
  1090. json.xudpConcurrency,
  1091. json.xudpProxyUDP443,
  1092. );
  1093. }
  1094. toJson() {
  1095. return {
  1096. enabled: this.enabled,
  1097. concurrency: this.concurrency,
  1098. xudpConcurrency: this.xudpConcurrency,
  1099. xudpProxyUDP443: this.xudpProxyUDP443,
  1100. };
  1101. }
  1102. }
  1103. class Outbound extends CommonClass {
  1104. constructor(
  1105. tag = '',
  1106. protocol = Protocols.VLESS,
  1107. settings = null,
  1108. streamSettings = new StreamSettings(),
  1109. sendThrough,
  1110. mux = new Mux(),
  1111. ) {
  1112. super();
  1113. this.tag = tag;
  1114. this._protocol = protocol;
  1115. this.settings = settings == null ? Outbound.Settings.getSettings(protocol) : settings;
  1116. this.stream = streamSettings;
  1117. this.sendThrough = sendThrough;
  1118. this.mux = mux;
  1119. }
  1120. get protocol() {
  1121. return this._protocol;
  1122. }
  1123. set protocol(protocol) {
  1124. this._protocol = protocol;
  1125. this.settings = Outbound.Settings.getSettings(protocol);
  1126. this.stream = new StreamSettings();
  1127. }
  1128. canEnableTls() {
  1129. if (this.protocol === Protocols.Hysteria) return true;
  1130. if (![Protocols.VMess, Protocols.VLESS, Protocols.Trojan, Protocols.Shadowsocks].includes(this.protocol)) return false;
  1131. return ["tcp", "ws", "http", "grpc", "httpupgrade", "xhttp"].includes(this.stream.network);
  1132. }
  1133. //this is used for xtls-rprx-vision
  1134. canEnableTlsFlow() {
  1135. if ((this.stream.security != 'none') && (this.stream.network === "tcp")) {
  1136. return this.protocol === Protocols.VLESS;
  1137. }
  1138. return false;
  1139. }
  1140. // Vision seed applies only when the XTLS Vision (TCP/TLS) flow is selected.
  1141. // Excludes the UDP variant per spec.
  1142. canEnableVisionSeed() {
  1143. if (!this.canEnableTlsFlow()) return false;
  1144. return this.settings?.flow === TLS_FLOW_CONTROL.VISION;
  1145. }
  1146. canEnableReality() {
  1147. if (![Protocols.VLESS, Protocols.Trojan].includes(this.protocol)) return false;
  1148. return ["tcp", "http", "grpc", "xhttp"].includes(this.stream.network);
  1149. }
  1150. canEnableStream() {
  1151. return [Protocols.VMess, Protocols.VLESS, Protocols.Trojan, Protocols.Shadowsocks, Protocols.Hysteria].includes(this.protocol);
  1152. }
  1153. canEnableMux() {
  1154. // Disable Mux if flow is set
  1155. if (this.settings.flow && this.settings.flow !== '') {
  1156. this.mux.enabled = false;
  1157. return false;
  1158. }
  1159. // Disable Mux if network is xhttp
  1160. if (this.stream.network === 'xhttp') {
  1161. this.mux.enabled = false;
  1162. return false;
  1163. }
  1164. // Allow Mux only for these protocols
  1165. return [
  1166. Protocols.VMess,
  1167. Protocols.VLESS,
  1168. Protocols.Trojan,
  1169. Protocols.Shadowsocks,
  1170. Protocols.HTTP,
  1171. Protocols.Socks
  1172. ].includes(this.protocol);
  1173. }
  1174. hasServers() {
  1175. return [Protocols.Trojan, Protocols.Shadowsocks, Protocols.Socks, Protocols.HTTP].includes(this.protocol);
  1176. }
  1177. hasAddressPort() {
  1178. return [
  1179. Protocols.DNS,
  1180. Protocols.VMess,
  1181. Protocols.VLESS,
  1182. Protocols.Trojan,
  1183. Protocols.Shadowsocks,
  1184. Protocols.Socks,
  1185. Protocols.HTTP,
  1186. Protocols.Hysteria
  1187. ].includes(this.protocol);
  1188. }
  1189. hasUsername() {
  1190. return [Protocols.Socks, Protocols.HTTP].includes(this.protocol);
  1191. }
  1192. static fromJson(json = {}) {
  1193. return new Outbound(
  1194. json.tag,
  1195. json.protocol,
  1196. Outbound.Settings.fromJson(json.protocol, json.settings),
  1197. StreamSettings.fromJson(json.streamSettings),
  1198. json.sendThrough,
  1199. Mux.fromJson(json.mux),
  1200. )
  1201. }
  1202. toJson() {
  1203. var stream;
  1204. if (this.canEnableStream()) {
  1205. stream = this.stream.toJson();
  1206. } else {
  1207. if (this.stream?.sockopt)
  1208. stream = { sockopt: this.stream.sockopt.toJson() };
  1209. }
  1210. let settingsOut = this.settings instanceof CommonClass ? this.settings.toJson() : this.settings;
  1211. return {
  1212. protocol: this.protocol,
  1213. settings: settingsOut,
  1214. // Only include tag, streamSettings, sendThrough, mux if present and not empty
  1215. ...(this.tag ? { tag: this.tag } : {}),
  1216. ...(stream ? { streamSettings: stream } : {}),
  1217. ...(this.sendThrough ? { sendThrough: this.sendThrough } : {}),
  1218. ...(this.mux?.enabled ? { mux: this.mux } : {}),
  1219. };
  1220. }
  1221. static fromLink(link) {
  1222. data = link.split('://');
  1223. if (data.length != 2) return null;
  1224. switch (data[0].toLowerCase()) {
  1225. case Protocols.VMess:
  1226. return this.fromVmessLink(JSON.parse(Base64.decode(data[1])));
  1227. case Protocols.VLESS:
  1228. case Protocols.Trojan:
  1229. case 'ss':
  1230. return this.fromParamLink(link);
  1231. case 'hysteria2':
  1232. case Protocols.Hysteria:
  1233. return this.fromHysteriaLink(link);
  1234. default:
  1235. return null;
  1236. }
  1237. }
  1238. static fromVmessLink(json = {}) {
  1239. let stream = new StreamSettings(json.net, json.tls);
  1240. let network = json.net;
  1241. if (network === 'tcp') {
  1242. stream.tcp = new TcpStreamSettings(
  1243. json.type,
  1244. json.host ?? '',
  1245. json.path ?? '');
  1246. } else if (network === 'kcp') {
  1247. stream.kcp = new KcpStreamSettings();
  1248. stream.type = json.type;
  1249. stream.seed = json.path;
  1250. const mtu = Number(json.mtu);
  1251. if (Number.isFinite(mtu) && mtu > 0) stream.kcp.mtu = mtu;
  1252. const tti = Number(json.tti);
  1253. if (Number.isFinite(tti) && tti > 0) stream.kcp.tti = tti;
  1254. } else if (network === 'ws') {
  1255. stream.ws = new WsStreamSettings(json.path, json.host);
  1256. } else if (network === 'grpc') {
  1257. stream.grpc = new GrpcStreamSettings(json.path, json.authority, json.type == 'multi');
  1258. } else if (network === 'httpupgrade') {
  1259. stream.httpupgrade = new HttpUpgradeStreamSettings(json.path, json.host);
  1260. } else if (network === 'xhttp') {
  1261. // xHTTPStreamSettings positional args are (path, host, headers, ..., mode);
  1262. // passing `json.mode` as the 3rd argument used to land in the `headers`
  1263. // slot, dropping the mode on the floor. Build the object and set mode
  1264. // explicitly to avoid that.
  1265. const xh = new xHTTPStreamSettings(json.path, json.host);
  1266. if (json.mode) xh.mode = json.mode;
  1267. stream.xhttp = xh;
  1268. }
  1269. if (json.tls && json.tls == 'tls') {
  1270. stream.tls = new TlsStreamSettings(
  1271. json.sni,
  1272. json.alpn ? json.alpn.split(',') : [],
  1273. json.fp);
  1274. }
  1275. const port = json.port * 1;
  1276. return new Outbound(json.ps, Protocols.VMess, new Outbound.VmessSettings(json.add, port, json.id, json.scy), stream);
  1277. }
  1278. static fromParamLink(link) {
  1279. const url = new URL(link);
  1280. let type = url.searchParams.get('type') ?? 'tcp';
  1281. let security = url.searchParams.get('security') ?? 'none';
  1282. let stream = new StreamSettings(type, security);
  1283. let headerType = url.searchParams.get('headerType') ?? undefined;
  1284. let host = url.searchParams.get('host') ?? undefined;
  1285. let path = url.searchParams.get('path') ?? undefined;
  1286. let seed = url.searchParams.get('seed') ?? path ?? undefined;
  1287. let mode = url.searchParams.get('mode') ?? undefined;
  1288. if (type === 'tcp' || type === 'none') {
  1289. stream.tcp = new TcpStreamSettings(headerType ?? 'none', host, path);
  1290. } else if (type === 'kcp') {
  1291. stream.kcp = new KcpStreamSettings();
  1292. stream.kcp.type = headerType ?? 'none';
  1293. stream.kcp.seed = seed;
  1294. const mtu = Number(url.searchParams.get('mtu'));
  1295. if (Number.isFinite(mtu) && mtu > 0) stream.kcp.mtu = mtu;
  1296. const tti = Number(url.searchParams.get('tti'));
  1297. if (Number.isFinite(tti) && tti > 0) stream.kcp.tti = tti;
  1298. } else if (type === 'ws') {
  1299. stream.ws = new WsStreamSettings(path, host);
  1300. } else if (type === 'grpc') {
  1301. stream.grpc = new GrpcStreamSettings(
  1302. url.searchParams.get('serviceName') ?? '',
  1303. url.searchParams.get('authority') ?? '',
  1304. url.searchParams.get('mode') == 'multi');
  1305. } else if (type === 'httpupgrade') {
  1306. stream.httpupgrade = new HttpUpgradeStreamSettings(path, host);
  1307. } else if (type === 'xhttp') {
  1308. // Same positional bug as in the VMess-JSON branch above:
  1309. // passing `mode` as the 3rd positional arg put it into the
  1310. // `headers` slot. Build explicitly instead.
  1311. const xh = new xHTTPStreamSettings(path, host);
  1312. if (mode) xh.mode = mode;
  1313. const xpb = url.searchParams.get('x_padding_bytes');
  1314. if (xpb) xh.xPaddingBytes = xpb;
  1315. const extraRaw = url.searchParams.get('extra');
  1316. if (extraRaw) {
  1317. try {
  1318. const extra = JSON.parse(extraRaw);
  1319. if (typeof extra.xPaddingBytes === 'string' && extra.xPaddingBytes) xh.xPaddingBytes = extra.xPaddingBytes;
  1320. if (extra.xPaddingObfsMode === true) xh.xPaddingObfsMode = true;
  1321. ["xPaddingKey", "xPaddingHeader", "xPaddingPlacement", "xPaddingMethod"].forEach(k => {
  1322. if (typeof extra[k] === 'string' && extra[k]) xh[k] = extra[k];
  1323. });
  1324. } catch (_) { /* ignore malformed extra */ }
  1325. }
  1326. stream.xhttp = xh;
  1327. }
  1328. if (security == 'tls') {
  1329. let fp = url.searchParams.get('fp') ?? 'none';
  1330. let alpn = url.searchParams.get('alpn');
  1331. let sni = url.searchParams.get('sni') ?? '';
  1332. let ech = url.searchParams.get('ech') ?? '';
  1333. stream.tls = new TlsStreamSettings(sni, alpn ? alpn.split(',') : [], fp, ech);
  1334. }
  1335. if (security == 'reality') {
  1336. let pbk = url.searchParams.get('pbk');
  1337. let fp = url.searchParams.get('fp');
  1338. let sni = url.searchParams.get('sni') ?? '';
  1339. let sid = url.searchParams.get('sid') ?? '';
  1340. let spx = url.searchParams.get('spx') ?? '';
  1341. let pqv = url.searchParams.get('pqv') ?? '';
  1342. stream.reality = new RealityStreamSettings(pbk, fp, sni, sid, spx, pqv);
  1343. }
  1344. const regex = /([^@]+):\/\/([^@]+)@(.+):(\d+)(.*)$/;
  1345. const match = link.match(regex);
  1346. if (!match) return null;
  1347. let [, protocol, userData, address, port,] = match;
  1348. port *= 1;
  1349. if (protocol == 'ss') {
  1350. protocol = 'shadowsocks';
  1351. userData = atob(userData).split(':');
  1352. }
  1353. var settings;
  1354. switch (protocol) {
  1355. case Protocols.VLESS:
  1356. settings = new Outbound.VLESSSettings(address, port, userData, url.searchParams.get('flow') ?? '', url.searchParams.get('encryption') ?? 'none');
  1357. break;
  1358. case Protocols.Trojan:
  1359. settings = new Outbound.TrojanSettings(address, port, userData);
  1360. break;
  1361. case Protocols.Shadowsocks:
  1362. let method = userData.splice(0, 1)[0];
  1363. settings = new Outbound.ShadowsocksSettings(address, port, userData.join(":"), method, true);
  1364. break;
  1365. default:
  1366. return null;
  1367. }
  1368. let remark = decodeURIComponent(url.hash);
  1369. // Remove '#' from url.hash
  1370. remark = remark.length > 0 ? remark.substring(1) : 'out-' + protocol + '-' + port;
  1371. return new Outbound(remark, protocol, settings, stream);
  1372. }
  1373. static fromHysteriaLink(link) {
  1374. // Parse hysteria2://password@address:port[?param1=value1&param2=value2...][#remarks]
  1375. const regex = /^hysteria2?:\/\/([^@]+)@([^:?#]+):(\d+)([^#]*)(#.*)?$/;
  1376. const match = link.match(regex);
  1377. if (!match) return null;
  1378. let [, password, address, port, params, hash] = match;
  1379. port = parseInt(port);
  1380. // Parse URL parameters if present
  1381. let urlParams = new URLSearchParams(params);
  1382. // Create stream settings with hysteria network
  1383. let stream = new StreamSettings('hysteria', 'none');
  1384. // Set hysteria stream settings
  1385. stream.hysteria.auth = password;
  1386. stream.hysteria.congestion = urlParams.get('congestion') ?? '';
  1387. stream.hysteria.up = urlParams.get('up') ?? '0';
  1388. stream.hysteria.down = urlParams.get('down') ?? '0';
  1389. stream.hysteria.udphopPort = urlParams.get('udphopPort') ?? '';
  1390. // Support both old single interval and new min/max range
  1391. if (urlParams.has('udphopInterval')) {
  1392. const interval = parseInt(urlParams.get('udphopInterval'));
  1393. stream.hysteria.udphopIntervalMin = interval;
  1394. stream.hysteria.udphopIntervalMax = interval;
  1395. } else {
  1396. stream.hysteria.udphopIntervalMin = parseInt(urlParams.get('udphopIntervalMin') ?? '30');
  1397. stream.hysteria.udphopIntervalMax = parseInt(urlParams.get('udphopIntervalMax') ?? '30');
  1398. }
  1399. // Optional QUIC parameters
  1400. if (urlParams.has('initStreamReceiveWindow')) {
  1401. stream.hysteria.initStreamReceiveWindow = parseInt(urlParams.get('initStreamReceiveWindow'));
  1402. }
  1403. if (urlParams.has('maxStreamReceiveWindow')) {
  1404. stream.hysteria.maxStreamReceiveWindow = parseInt(urlParams.get('maxStreamReceiveWindow'));
  1405. }
  1406. if (urlParams.has('initConnectionReceiveWindow')) {
  1407. stream.hysteria.initConnectionReceiveWindow = parseInt(urlParams.get('initConnectionReceiveWindow'));
  1408. }
  1409. if (urlParams.has('maxConnectionReceiveWindow')) {
  1410. stream.hysteria.maxConnectionReceiveWindow = parseInt(urlParams.get('maxConnectionReceiveWindow'));
  1411. }
  1412. if (urlParams.has('maxIdleTimeout')) {
  1413. stream.hysteria.maxIdleTimeout = parseInt(urlParams.get('maxIdleTimeout'));
  1414. }
  1415. if (urlParams.has('keepAlivePeriod')) {
  1416. stream.hysteria.keepAlivePeriod = parseInt(urlParams.get('keepAlivePeriod'));
  1417. }
  1418. if (urlParams.has('disablePathMTUDiscovery')) {
  1419. stream.hysteria.disablePathMTUDiscovery = urlParams.get('disablePathMTUDiscovery') === 'true';
  1420. }
  1421. // Create settings
  1422. let settings = new Outbound.HysteriaSettings(address, port, 2);
  1423. // Extract remark from hash
  1424. let remark = hash ? decodeURIComponent(hash.substring(1)) : `out-hysteria-${port}`;
  1425. return new Outbound(remark, Protocols.Hysteria, settings, stream);
  1426. }
  1427. }
  1428. Outbound.Settings = class extends CommonClass {
  1429. constructor(protocol) {
  1430. super();
  1431. this.protocol = protocol;
  1432. }
  1433. static getSettings(protocol) {
  1434. switch (protocol) {
  1435. case Protocols.Freedom: return new Outbound.FreedomSettings();
  1436. case Protocols.Blackhole: return new Outbound.BlackholeSettings();
  1437. case Protocols.DNS: return new Outbound.DNSSettings();
  1438. case Protocols.VMess: return new Outbound.VmessSettings();
  1439. case Protocols.VLESS: return new Outbound.VLESSSettings();
  1440. case Protocols.Trojan: return new Outbound.TrojanSettings();
  1441. case Protocols.Shadowsocks: return new Outbound.ShadowsocksSettings();
  1442. case Protocols.Socks: return new Outbound.SocksSettings();
  1443. case Protocols.HTTP: return new Outbound.HttpSettings();
  1444. case Protocols.Wireguard: return new Outbound.WireguardSettings();
  1445. case Protocols.Hysteria: return new Outbound.HysteriaSettings();
  1446. default: return null;
  1447. }
  1448. }
  1449. static fromJson(protocol, json) {
  1450. switch (protocol) {
  1451. case Protocols.Freedom: return Outbound.FreedomSettings.fromJson(json);
  1452. case Protocols.Blackhole: return Outbound.BlackholeSettings.fromJson(json);
  1453. case Protocols.DNS: return Outbound.DNSSettings.fromJson(json);
  1454. case Protocols.VMess: return Outbound.VmessSettings.fromJson(json);
  1455. case Protocols.VLESS: return Outbound.VLESSSettings.fromJson(json);
  1456. case Protocols.Trojan: return Outbound.TrojanSettings.fromJson(json);
  1457. case Protocols.Shadowsocks: return Outbound.ShadowsocksSettings.fromJson(json);
  1458. case Protocols.Socks: return Outbound.SocksSettings.fromJson(json);
  1459. case Protocols.HTTP: return Outbound.HttpSettings.fromJson(json);
  1460. case Protocols.Wireguard: return Outbound.WireguardSettings.fromJson(json);
  1461. case Protocols.Hysteria: return Outbound.HysteriaSettings.fromJson(json);
  1462. default: return null;
  1463. }
  1464. }
  1465. toJson() {
  1466. return {};
  1467. }
  1468. };
  1469. Outbound.FreedomSettings = class extends CommonClass {
  1470. constructor(
  1471. domainStrategy = '',
  1472. redirect = '',
  1473. fragment = {},
  1474. noises = [],
  1475. finalRules = [],
  1476. ) {
  1477. super();
  1478. this.domainStrategy = domainStrategy;
  1479. this.redirect = redirect;
  1480. this.fragment = fragment || {};
  1481. this.noises = Array.isArray(noises) ? noises : [];
  1482. this.finalRules = Array.isArray(finalRules)
  1483. ? finalRules.map(rule => rule instanceof Outbound.FreedomSettings.FinalRule ? rule : Outbound.FreedomSettings.FinalRule.fromJson(rule))
  1484. : [];
  1485. }
  1486. addNoise() {
  1487. this.noises.push(new Outbound.FreedomSettings.Noise());
  1488. }
  1489. delNoise(index) {
  1490. this.noises.splice(index, 1);
  1491. }
  1492. addFinalRule(action = 'block') {
  1493. this.finalRules.push(new Outbound.FreedomSettings.FinalRule(action));
  1494. }
  1495. delFinalRule(index) {
  1496. this.finalRules.splice(index, 1);
  1497. }
  1498. static fromJson(json = {}) {
  1499. const finalRules = Array.isArray(json.finalRules)
  1500. ? json.finalRules.map(rule => Outbound.FreedomSettings.FinalRule.fromJson(rule))
  1501. : [];
  1502. // Backward compatibility: map legacy ipsBlocked entries to blocking finalRules.
  1503. if (finalRules.length === 0 && Array.isArray(json.ipsBlocked) && json.ipsBlocked.length > 0) {
  1504. finalRules.push(new Outbound.FreedomSettings.FinalRule('block', '', '', json.ipsBlocked, ''));
  1505. }
  1506. return new Outbound.FreedomSettings(
  1507. json.domainStrategy,
  1508. json.redirect,
  1509. json.fragment ? Outbound.FreedomSettings.Fragment.fromJson(json.fragment) : {},
  1510. json.noises ? json.noises.map(noise => Outbound.FreedomSettings.Noise.fromJson(noise)) : [],
  1511. finalRules,
  1512. );
  1513. }
  1514. toJson() {
  1515. return {
  1516. domainStrategy: ObjectUtil.isEmpty(this.domainStrategy) ? undefined : this.domainStrategy,
  1517. redirect: ObjectUtil.isEmpty(this.redirect) ? undefined : this.redirect,
  1518. fragment: Object.keys(this.fragment).length === 0 ? undefined : this.fragment,
  1519. noises: this.noises.length === 0 ? undefined : Outbound.FreedomSettings.Noise.toJsonArray(this.noises),
  1520. finalRules: this.finalRules.length === 0 ? undefined : Outbound.FreedomSettings.FinalRule.toJsonArray(this.finalRules),
  1521. };
  1522. }
  1523. };
  1524. Outbound.FreedomSettings.Fragment = class extends CommonClass {
  1525. constructor(
  1526. packets = '1-3',
  1527. length = '',
  1528. interval = '',
  1529. maxSplit = ''
  1530. ) {
  1531. super();
  1532. this.packets = packets;
  1533. this.length = length;
  1534. this.interval = interval;
  1535. this.maxSplit = maxSplit;
  1536. }
  1537. static fromJson(json = {}) {
  1538. return new Outbound.FreedomSettings.Fragment(
  1539. json.packets,
  1540. json.length,
  1541. json.interval,
  1542. json.maxSplit
  1543. );
  1544. }
  1545. };
  1546. Outbound.FreedomSettings.Noise = class extends CommonClass {
  1547. constructor(
  1548. type = 'rand',
  1549. packet = '10-20',
  1550. delay = '10-16',
  1551. applyTo = 'ip'
  1552. ) {
  1553. super();
  1554. this.type = type;
  1555. this.packet = packet;
  1556. this.delay = delay;
  1557. this.applyTo = applyTo;
  1558. }
  1559. static fromJson(json = {}) {
  1560. return new Outbound.FreedomSettings.Noise(
  1561. json.type,
  1562. json.packet,
  1563. json.delay,
  1564. json.applyTo
  1565. );
  1566. }
  1567. toJson() {
  1568. return {
  1569. type: this.type,
  1570. packet: this.packet,
  1571. delay: this.delay,
  1572. applyTo: this.applyTo
  1573. };
  1574. }
  1575. };
  1576. Outbound.FreedomSettings.FinalRule = class extends CommonClass {
  1577. constructor(action = 'block', network = '', port = '', ip = [], blockDelay = '') {
  1578. super();
  1579. this.action = action;
  1580. this.network = network;
  1581. this.port = port;
  1582. this.ip = Array.isArray(ip) ? ip : [];
  1583. this.blockDelay = blockDelay;
  1584. }
  1585. static fromJson(json = {}) {
  1586. return new Outbound.FreedomSettings.FinalRule(
  1587. json.action,
  1588. Array.isArray(json.network) ? json.network.join(',') : json.network,
  1589. json.port,
  1590. json.ip || [],
  1591. json.blockDelay,
  1592. );
  1593. }
  1594. toJson() {
  1595. return {
  1596. action: ['allow', 'block'].includes(this.action) ? this.action : 'block',
  1597. network: ObjectUtil.isEmpty(this.network) ? undefined : this.network,
  1598. port: ObjectUtil.isEmpty(this.port) ? undefined : this.port,
  1599. ip: this.ip.length === 0 ? undefined : this.ip,
  1600. blockDelay: this.action === 'block' && !ObjectUtil.isEmpty(this.blockDelay) ? this.blockDelay : undefined,
  1601. };
  1602. }
  1603. };
  1604. Outbound.BlackholeSettings = class extends CommonClass {
  1605. constructor(type) {
  1606. super();
  1607. this.type = type;
  1608. }
  1609. static fromJson(json = {}) {
  1610. return new Outbound.BlackholeSettings(
  1611. json.response ? json.response.type : undefined,
  1612. );
  1613. }
  1614. toJson() {
  1615. return {
  1616. response: ObjectUtil.isEmpty(this.type) ? undefined : { type: this.type },
  1617. };
  1618. }
  1619. };
  1620. Outbound.DNSRule = class extends CommonClass {
  1621. constructor(action = 'direct', qtype = '', domain = '') {
  1622. super();
  1623. this.action = action;
  1624. this.qtype = qtype;
  1625. this.domain = domain;
  1626. }
  1627. static fromJson(json = {}) {
  1628. return new Outbound.DNSRule(
  1629. json.action,
  1630. normalizeDNSRuleField(json.qtype),
  1631. normalizeDNSRuleField(json.domain),
  1632. );
  1633. }
  1634. toJson() {
  1635. const rule = {
  1636. action: normalizeDNSRuleAction(this.action),
  1637. };
  1638. const qtype = normalizeDNSRuleField(this.qtype);
  1639. if (!ObjectUtil.isEmpty(qtype)) {
  1640. if (/^\d+$/.test(qtype)) {
  1641. rule.qtype = Number(qtype);
  1642. } else {
  1643. rule.qtype = qtype;
  1644. }
  1645. }
  1646. const domains = normalizeDNSRuleField(this.domain)
  1647. .split(',')
  1648. .map(d => d.trim())
  1649. .filter(d => d.length > 0);
  1650. if (domains.length > 0) {
  1651. rule.domain = domains;
  1652. }
  1653. return rule;
  1654. }
  1655. };
  1656. Outbound.DNSSettings = class extends CommonClass {
  1657. constructor(
  1658. network = 'udp',
  1659. address = '',
  1660. port = 53,
  1661. rules = []
  1662. ) {
  1663. super();
  1664. this.network = network;
  1665. this.address = address;
  1666. this.port = port;
  1667. this.rules = Array.isArray(rules) ? rules.map(rule => rule instanceof Outbound.DNSRule ? rule : Outbound.DNSRule.fromJson(rule)) : [];
  1668. }
  1669. addRule(action = 'direct') {
  1670. this.rules.push(new Outbound.DNSRule(action));
  1671. }
  1672. delRule(index) {
  1673. this.rules.splice(index, 1);
  1674. }
  1675. static fromJson(json = {}) {
  1676. return new Outbound.DNSSettings(
  1677. json.network,
  1678. json.address,
  1679. json.port,
  1680. getDNSRulesFromJson(json),
  1681. );
  1682. }
  1683. toJson() {
  1684. const json = {
  1685. network: this.network,
  1686. address: this.address,
  1687. port: this.port,
  1688. };
  1689. if (this.rules.length > 0) {
  1690. json.rules = Outbound.DNSRule.toJsonArray(this.rules);
  1691. }
  1692. return json;
  1693. }
  1694. };
  1695. Outbound.VmessSettings = class extends CommonClass {
  1696. constructor(address, port, id, security) {
  1697. super();
  1698. this.address = address;
  1699. this.port = port;
  1700. this.id = id;
  1701. this.security = security;
  1702. }
  1703. static fromJson(json = {}) {
  1704. if (!ObjectUtil.isArrEmpty(json.vnext)) {
  1705. const v = json.vnext[0] || {};
  1706. const u = ObjectUtil.isArrEmpty(v.users) ? {} : v.users[0];
  1707. return new Outbound.VmessSettings(
  1708. v.address,
  1709. v.port,
  1710. u.id,
  1711. u.security,
  1712. );
  1713. }
  1714. }
  1715. toJson() {
  1716. return {
  1717. vnext: [{
  1718. address: this.address,
  1719. port: this.port,
  1720. users: [{
  1721. id: this.id,
  1722. security: this.security
  1723. }]
  1724. }]
  1725. };
  1726. }
  1727. };
  1728. Outbound.VLESSSettings = class extends CommonClass {
  1729. constructor(address, port, id, flow, encryption, reverseTag = '', reverseSniffing = new ReverseSniffing(), testpre = 0, testseed = []) {
  1730. super();
  1731. this.address = address;
  1732. this.port = port;
  1733. this.id = id;
  1734. this.flow = flow;
  1735. this.encryption = encryption;
  1736. this.reverseTag = reverseTag;
  1737. this.reverseSniffing = reverseSniffing;
  1738. this.testpre = testpre;
  1739. this.testseed = testseed;
  1740. }
  1741. static fromJson(json = {}) {
  1742. if (ObjectUtil.isEmpty(json.address) || ObjectUtil.isEmpty(json.port)) return new Outbound.VLESSSettings();
  1743. const saved = json.testseed;
  1744. const testseed = (Array.isArray(saved)
  1745. && saved.length === 4
  1746. && saved.every(v => Number.isInteger(v) && v > 0))
  1747. ? saved
  1748. : [];
  1749. return new Outbound.VLESSSettings(
  1750. json.address,
  1751. json.port,
  1752. json.id,
  1753. json.flow,
  1754. json.encryption,
  1755. json.reverse?.tag || '',
  1756. ReverseSniffing.fromJson(json.reverse?.sniffing || {}),
  1757. json.testpre || 0,
  1758. testseed,
  1759. );
  1760. }
  1761. toJson() {
  1762. const result = {
  1763. address: this.address,
  1764. port: this.port,
  1765. id: this.id,
  1766. flow: this.flow,
  1767. encryption: this.encryption,
  1768. };
  1769. if (!ObjectUtil.isEmpty(this.reverseTag)) {
  1770. const reverseSniffing = this.reverseSniffing ? this.reverseSniffing.toJson() : {};
  1771. const defaultReverseSniffing = new ReverseSniffing().toJson();
  1772. result.reverse = {
  1773. tag: this.reverseTag,
  1774. sniffing: JSON.stringify(reverseSniffing) === JSON.stringify(defaultReverseSniffing) ? {} : reverseSniffing,
  1775. };
  1776. }
  1777. // Vision-specific knobs are only meaningful for the exact xtls-rprx-vision flow.
  1778. if (this.flow === TLS_FLOW_CONTROL.VISION) {
  1779. if (this.testpre > 0) {
  1780. result.testpre = this.testpre;
  1781. }
  1782. if (Array.isArray(this.testseed)
  1783. && this.testseed.length === 4
  1784. && this.testseed.every(v => Number.isInteger(v) && v > 0)) {
  1785. result.testseed = this.testseed;
  1786. }
  1787. }
  1788. return result;
  1789. }
  1790. };
  1791. Outbound.TrojanSettings = class extends CommonClass {
  1792. constructor(address, port, password) {
  1793. super();
  1794. this.address = address;
  1795. this.port = port;
  1796. this.password = password;
  1797. }
  1798. static fromJson(json = {}) {
  1799. if (ObjectUtil.isArrEmpty(json.servers)) return new Outbound.TrojanSettings();
  1800. return new Outbound.TrojanSettings(
  1801. json.servers[0].address,
  1802. json.servers[0].port,
  1803. json.servers[0].password,
  1804. );
  1805. }
  1806. toJson() {
  1807. return {
  1808. servers: [{
  1809. address: this.address,
  1810. port: this.port,
  1811. password: this.password,
  1812. }],
  1813. };
  1814. }
  1815. };
  1816. Outbound.ShadowsocksSettings = class extends CommonClass {
  1817. constructor(address, port, password, method, uot, UoTVersion) {
  1818. super();
  1819. this.address = address;
  1820. this.port = port;
  1821. this.password = password;
  1822. this.method = method;
  1823. this.uot = uot;
  1824. this.UoTVersion = UoTVersion;
  1825. }
  1826. static fromJson(json = {}) {
  1827. let servers = json.servers;
  1828. if (ObjectUtil.isArrEmpty(servers)) servers = [{}];
  1829. return new Outbound.ShadowsocksSettings(
  1830. servers[0].address,
  1831. servers[0].port,
  1832. servers[0].password,
  1833. servers[0].method,
  1834. servers[0].uot,
  1835. servers[0].UoTVersion,
  1836. );
  1837. }
  1838. toJson() {
  1839. return {
  1840. servers: [{
  1841. address: this.address,
  1842. port: this.port,
  1843. password: this.password,
  1844. method: this.method,
  1845. uot: this.uot,
  1846. UoTVersion: this.UoTVersion,
  1847. }],
  1848. };
  1849. }
  1850. };
  1851. Outbound.SocksSettings = class extends CommonClass {
  1852. constructor(address, port, user, pass) {
  1853. super();
  1854. this.address = address;
  1855. this.port = port;
  1856. this.user = user;
  1857. this.pass = pass;
  1858. }
  1859. static fromJson(json = {}) {
  1860. let servers = json.servers;
  1861. if (ObjectUtil.isArrEmpty(servers)) servers = [{ users: [{}] }];
  1862. return new Outbound.SocksSettings(
  1863. servers[0].address,
  1864. servers[0].port,
  1865. ObjectUtil.isArrEmpty(servers[0].users) ? '' : servers[0].users[0].user,
  1866. ObjectUtil.isArrEmpty(servers[0].users) ? '' : servers[0].users[0].pass,
  1867. );
  1868. }
  1869. toJson() {
  1870. return {
  1871. servers: [{
  1872. address: this.address,
  1873. port: this.port,
  1874. users: ObjectUtil.isEmpty(this.user) ? [] : [{ user: this.user, pass: this.pass }],
  1875. }],
  1876. };
  1877. }
  1878. };
  1879. Outbound.HttpSettings = class extends CommonClass {
  1880. constructor(address, port, user, pass) {
  1881. super();
  1882. this.address = address;
  1883. this.port = port;
  1884. this.user = user;
  1885. this.pass = pass;
  1886. }
  1887. static fromJson(json = {}) {
  1888. let servers = json.servers;
  1889. if (ObjectUtil.isArrEmpty(servers)) servers = [{ users: [{}] }];
  1890. return new Outbound.HttpSettings(
  1891. servers[0].address,
  1892. servers[0].port,
  1893. ObjectUtil.isArrEmpty(servers[0].users) ? '' : servers[0].users[0].user,
  1894. ObjectUtil.isArrEmpty(servers[0].users) ? '' : servers[0].users[0].pass,
  1895. );
  1896. }
  1897. toJson() {
  1898. return {
  1899. servers: [{
  1900. address: this.address,
  1901. port: this.port,
  1902. users: ObjectUtil.isEmpty(this.user) ? [] : [{ user: this.user, pass: this.pass }],
  1903. }],
  1904. };
  1905. }
  1906. };
  1907. Outbound.WireguardSettings = class extends CommonClass {
  1908. constructor(
  1909. mtu = 1420,
  1910. secretKey = '',
  1911. address = [''],
  1912. workers = 2,
  1913. domainStrategy = '',
  1914. reserved = '',
  1915. peers = [new Outbound.WireguardSettings.Peer()],
  1916. noKernelTun = false,
  1917. ) {
  1918. super();
  1919. this.mtu = mtu;
  1920. this.secretKey = secretKey;
  1921. this.pubKey = secretKey.length > 0 ? Wireguard.generateKeypair(secretKey).publicKey : '';
  1922. this.address = Array.isArray(address) ? address.join(',') : address;
  1923. this.workers = workers;
  1924. this.domainStrategy = domainStrategy;
  1925. this.reserved = Array.isArray(reserved) ? reserved.join(',') : reserved;
  1926. this.peers = peers;
  1927. this.noKernelTun = noKernelTun;
  1928. }
  1929. addPeer() {
  1930. this.peers.push(new Outbound.WireguardSettings.Peer());
  1931. }
  1932. delPeer(index) {
  1933. this.peers.splice(index, 1);
  1934. }
  1935. static fromJson(json = {}) {
  1936. return new Outbound.WireguardSettings(
  1937. json.mtu,
  1938. json.secretKey,
  1939. json.address,
  1940. json.workers,
  1941. json.domainStrategy,
  1942. json.reserved,
  1943. json.peers.map(peer => Outbound.WireguardSettings.Peer.fromJson(peer)),
  1944. json.noKernelTun,
  1945. );
  1946. }
  1947. toJson() {
  1948. return {
  1949. mtu: this.mtu ?? undefined,
  1950. secretKey: this.secretKey,
  1951. address: this.address ? this.address.split(",") : [],
  1952. workers: this.workers ?? undefined,
  1953. domainStrategy: WireguardDomainStrategy.includes(this.domainStrategy) ? this.domainStrategy : undefined,
  1954. reserved: this.reserved ? this.reserved.split(",").map(Number) : undefined,
  1955. peers: Outbound.WireguardSettings.Peer.toJsonArray(this.peers),
  1956. noKernelTun: this.noKernelTun,
  1957. };
  1958. }
  1959. };
  1960. Outbound.WireguardSettings.Peer = class extends CommonClass {
  1961. constructor(
  1962. publicKey = '',
  1963. psk = '',
  1964. allowedIPs = ['0.0.0.0/0', '::/0'],
  1965. endpoint = '',
  1966. keepAlive = 0
  1967. ) {
  1968. super();
  1969. this.publicKey = publicKey;
  1970. this.psk = psk;
  1971. this.allowedIPs = allowedIPs;
  1972. this.endpoint = endpoint;
  1973. this.keepAlive = keepAlive;
  1974. }
  1975. static fromJson(json = {}) {
  1976. return new Outbound.WireguardSettings.Peer(
  1977. json.publicKey,
  1978. json.preSharedKey,
  1979. json.allowedIPs,
  1980. json.endpoint,
  1981. json.keepAlive
  1982. );
  1983. }
  1984. toJson() {
  1985. return {
  1986. publicKey: this.publicKey,
  1987. preSharedKey: this.psk.length > 0 ? this.psk : undefined,
  1988. allowedIPs: this.allowedIPs ? this.allowedIPs : undefined,
  1989. endpoint: this.endpoint,
  1990. keepAlive: this.keepAlive ?? undefined,
  1991. };
  1992. }
  1993. };
  1994. Outbound.HysteriaSettings = class extends CommonClass {
  1995. constructor(address = '', port = 443, version = 2) {
  1996. super();
  1997. this.address = address;
  1998. this.port = port;
  1999. this.version = version;
  2000. }
  2001. static fromJson(json = {}) {
  2002. if (Object.keys(json).length === 0) return new Outbound.HysteriaSettings();
  2003. return new Outbound.HysteriaSettings(
  2004. json.address,
  2005. json.port,
  2006. json.version
  2007. );
  2008. }
  2009. toJson() {
  2010. return {
  2011. address: this.address,
  2012. port: this.port,
  2013. version: this.version
  2014. };
  2015. }
  2016. };