outbound.js 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804
  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. Socks: "socks",
  10. HTTP: "http",
  11. Wireguard: "wireguard",
  12. Hysteria: "hysteria"
  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 OutboundDomainStrategies = [
  49. "AsIs",
  50. "UseIP",
  51. "UseIPv4",
  52. "UseIPv6",
  53. "UseIPv6v4",
  54. "UseIPv4v6",
  55. "ForceIP",
  56. "ForceIPv6v4",
  57. "ForceIPv6",
  58. "ForceIPv4v6",
  59. "ForceIPv4"
  60. ];
  61. const WireguardDomainStrategy = [
  62. "ForceIP",
  63. "ForceIPv4",
  64. "ForceIPv4v6",
  65. "ForceIPv6",
  66. "ForceIPv6v4"
  67. ];
  68. const USERS_SECURITY = {
  69. AES_128_GCM: "aes-128-gcm",
  70. CHACHA20_POLY1305: "chacha20-poly1305",
  71. AUTO: "auto",
  72. NONE: "none",
  73. ZERO: "zero",
  74. };
  75. const MODE_OPTION = {
  76. AUTO: "auto",
  77. PACKET_UP: "packet-up",
  78. STREAM_UP: "stream-up",
  79. STREAM_ONE: "stream-one",
  80. };
  81. const Address_Port_Strategy = {
  82. NONE: "none",
  83. SrvPortOnly: "srvportonly",
  84. SrvAddressOnly: "srvaddressonly",
  85. SrvPortAndAddress: "srvportandaddress",
  86. TxtPortOnly: "txtportonly",
  87. TxtAddressOnly: "txtaddressonly",
  88. TxtPortAndAddress: "txtportandaddress"
  89. };
  90. const DNSRuleActions = ['direct', 'drop', 'reject', 'hijack'];
  91. function normalizeDNSRuleField(value) {
  92. if (value === null || value === undefined) {
  93. return '';
  94. }
  95. if (Array.isArray(value)) {
  96. return value.map(item => item.toString().trim()).filter(item => item.length > 0).join(',');
  97. }
  98. return value.toString().trim();
  99. }
  100. function normalizeDNSRuleAction(action) {
  101. action = ObjectUtil.isEmpty(action) ? 'direct' : action.toString().toLowerCase().trim();
  102. return DNSRuleActions.includes(action) ? action : 'direct';
  103. }
  104. function parseLegacyDNSBlockTypes(blockTypes) {
  105. if (blockTypes === null || blockTypes === undefined || blockTypes === '') {
  106. return [];
  107. }
  108. if (Array.isArray(blockTypes)) {
  109. return blockTypes
  110. .map(item => Number(item))
  111. .filter(item => Number.isInteger(item) && item >= 0 && item <= 65535);
  112. }
  113. if (typeof blockTypes === 'number') {
  114. return Number.isInteger(blockTypes) && blockTypes >= 0 && blockTypes <= 65535 ? [blockTypes] : [];
  115. }
  116. return blockTypes
  117. .toString()
  118. .split(',')
  119. .map(item => item.trim())
  120. .filter(item => /^\d+$/.test(item))
  121. .map(item => Number(item))
  122. .filter(item => item >= 0 && item <= 65535);
  123. }
  124. function buildLegacyDNSRules(nonIPQuery, blockTypes) {
  125. const mode = ['reject', 'drop', 'skip'].includes(nonIPQuery) ? nonIPQuery : 'reject';
  126. const rules = [];
  127. const parsedBlockTypes = parseLegacyDNSBlockTypes(blockTypes);
  128. if (parsedBlockTypes.length > 0) {
  129. rules.push(new Outbound.DNSRule(mode === 'reject' ? 'reject' : 'drop', parsedBlockTypes.join(',')));
  130. }
  131. rules.push(new Outbound.DNSRule('hijack', '1,28'));
  132. rules.push(new Outbound.DNSRule(mode === 'skip' ? 'direct' : mode));
  133. return rules;
  134. }
  135. function getDNSRulesFromJson(json = {}) {
  136. if (Array.isArray(json.rules) && json.rules.length > 0) {
  137. return json.rules.map(rule => Outbound.DNSRule.fromJson(rule));
  138. }
  139. if (json.nonIPQuery !== undefined || json.blockTypes !== undefined) {
  140. return buildLegacyDNSRules(json.nonIPQuery, json.blockTypes);
  141. }
  142. return [];
  143. }
  144. Object.freeze(Protocols);
  145. Object.freeze(SSMethods);
  146. Object.freeze(TLS_FLOW_CONTROL);
  147. Object.freeze(UTLS_FINGERPRINT);
  148. Object.freeze(ALPN_OPTION);
  149. Object.freeze(OutboundDomainStrategies);
  150. Object.freeze(WireguardDomainStrategy);
  151. Object.freeze(USERS_SECURITY);
  152. Object.freeze(MODE_OPTION);
  153. Object.freeze(Address_Port_Strategy);
  154. Object.freeze(DNSRuleActions);
  155. class CommonClass {
  156. static toJsonArray(arr) {
  157. return arr.map(obj => obj.toJson());
  158. }
  159. static fromJson() {
  160. return new CommonClass();
  161. }
  162. toJson() {
  163. return this;
  164. }
  165. toString(format = true) {
  166. return format ? JSON.stringify(this.toJson(), null, 2) : JSON.stringify(this.toJson());
  167. }
  168. }
  169. class TcpStreamSettings extends CommonClass {
  170. constructor(type = 'none', host, path) {
  171. super();
  172. this.type = type;
  173. this.host = host;
  174. this.path = path;
  175. }
  176. static fromJson(json = {}) {
  177. let header = json.header;
  178. if (!header) return new TcpStreamSettings();
  179. if (header.type == 'http' && header.request) {
  180. return new TcpStreamSettings(
  181. header.type,
  182. header.request.headers.Host.join(','),
  183. header.request.path.join(','),
  184. );
  185. }
  186. return new TcpStreamSettings(header.type, '', '');
  187. }
  188. toJson() {
  189. return {
  190. header: {
  191. type: this.type,
  192. request: this.type === 'http' ? {
  193. headers: {
  194. Host: ObjectUtil.isEmpty(this.host) ? [] : this.host.split(',')
  195. },
  196. path: ObjectUtil.isEmpty(this.path) ? ["/"] : this.path.split(',')
  197. } : undefined,
  198. }
  199. };
  200. }
  201. }
  202. class KcpStreamSettings extends CommonClass {
  203. constructor(
  204. mtu = 1350,
  205. tti = 20,
  206. uplinkCapacity = 5,
  207. downlinkCapacity = 20,
  208. cwndMultiplier = 1,
  209. maxSendingWindow = 1350,
  210. ) {
  211. super();
  212. this.mtu = mtu;
  213. this.tti = tti;
  214. this.upCap = uplinkCapacity;
  215. this.downCap = downlinkCapacity;
  216. this.cwndMultiplier = cwndMultiplier;
  217. this.maxSendingWindow = maxSendingWindow;
  218. }
  219. static fromJson(json = {}) {
  220. return new KcpStreamSettings(
  221. json.mtu,
  222. json.tti,
  223. json.uplinkCapacity,
  224. json.downlinkCapacity,
  225. json.cwndMultiplier,
  226. json.maxSendingWindow,
  227. );
  228. }
  229. toJson() {
  230. return {
  231. mtu: this.mtu,
  232. tti: this.tti,
  233. uplinkCapacity: this.upCap,
  234. downlinkCapacity: this.downCap,
  235. cwndMultiplier: this.cwndMultiplier,
  236. maxSendingWindow: this.maxSendingWindow,
  237. };
  238. }
  239. }
  240. class WsStreamSettings extends CommonClass {
  241. constructor(
  242. path = '/',
  243. host = '',
  244. heartbeatPeriod = 0,
  245. ) {
  246. super();
  247. this.path = path;
  248. this.host = host;
  249. this.heartbeatPeriod = heartbeatPeriod;
  250. }
  251. static fromJson(json = {}) {
  252. return new WsStreamSettings(
  253. json.path,
  254. json.host,
  255. json.heartbeatPeriod,
  256. );
  257. }
  258. toJson() {
  259. return {
  260. path: this.path,
  261. host: this.host,
  262. heartbeatPeriod: this.heartbeatPeriod
  263. };
  264. }
  265. }
  266. class GrpcStreamSettings extends CommonClass {
  267. constructor(
  268. serviceName = "",
  269. authority = "",
  270. multiMode = false
  271. ) {
  272. super();
  273. this.serviceName = serviceName;
  274. this.authority = authority;
  275. this.multiMode = multiMode;
  276. }
  277. static fromJson(json = {}) {
  278. return new GrpcStreamSettings(json.serviceName, json.authority, json.multiMode);
  279. }
  280. toJson() {
  281. return {
  282. serviceName: this.serviceName,
  283. authority: this.authority,
  284. multiMode: this.multiMode
  285. }
  286. }
  287. }
  288. class HttpUpgradeStreamSettings extends CommonClass {
  289. constructor(path = '/', host = '') {
  290. super();
  291. this.path = path;
  292. this.host = host;
  293. }
  294. static fromJson(json = {}) {
  295. return new HttpUpgradeStreamSettings(
  296. json.path,
  297. json.host,
  298. );
  299. }
  300. toJson() {
  301. return {
  302. path: this.path,
  303. host: this.host,
  304. };
  305. }
  306. }
  307. class xHTTPStreamSettings extends CommonClass {
  308. constructor(
  309. path = '/',
  310. host = '',
  311. mode = '',
  312. noGRPCHeader = false,
  313. scMinPostsIntervalMs = "30",
  314. xmux = {
  315. maxConcurrency: "16-32",
  316. maxConnections: 0,
  317. cMaxReuseTimes: 0,
  318. hMaxRequestTimes: "600-900",
  319. hMaxReusableSecs: "1800-3000",
  320. hKeepAlivePeriod: 0,
  321. },
  322. ) {
  323. super();
  324. this.path = path;
  325. this.host = host;
  326. this.mode = mode;
  327. this.noGRPCHeader = noGRPCHeader;
  328. this.scMinPostsIntervalMs = scMinPostsIntervalMs;
  329. this.xmux = xmux;
  330. }
  331. static fromJson(json = {}) {
  332. return new xHTTPStreamSettings(
  333. json.path,
  334. json.host,
  335. json.mode,
  336. json.noGRPCHeader,
  337. json.scMinPostsIntervalMs,
  338. json.xmux
  339. );
  340. }
  341. toJson() {
  342. return {
  343. path: this.path,
  344. host: this.host,
  345. mode: this.mode,
  346. noGRPCHeader: this.noGRPCHeader,
  347. scMinPostsIntervalMs: this.scMinPostsIntervalMs,
  348. xmux: {
  349. maxConcurrency: this.xmux.maxConcurrency,
  350. maxConnections: this.xmux.maxConnections,
  351. cMaxReuseTimes: this.xmux.cMaxReuseTimes,
  352. hMaxRequestTimes: this.xmux.hMaxRequestTimes,
  353. hMaxReusableSecs: this.xmux.hMaxReusableSecs,
  354. hKeepAlivePeriod: this.xmux.hKeepAlivePeriod,
  355. },
  356. };
  357. }
  358. }
  359. class TlsStreamSettings extends CommonClass {
  360. constructor(
  361. serverName = '',
  362. alpn = [],
  363. fingerprint = '',
  364. echConfigList = '',
  365. verifyPeerCertByName = '',
  366. pinnedPeerCertSha256 = '',
  367. ) {
  368. super();
  369. this.serverName = serverName;
  370. this.alpn = alpn;
  371. this.fingerprint = fingerprint;
  372. this.echConfigList = echConfigList;
  373. this.verifyPeerCertByName = verifyPeerCertByName;
  374. this.pinnedPeerCertSha256 = pinnedPeerCertSha256;
  375. }
  376. static fromJson(json = {}) {
  377. return new TlsStreamSettings(
  378. json.serverName,
  379. json.alpn,
  380. json.fingerprint,
  381. json.echConfigList,
  382. json.verifyPeerCertByName,
  383. json.pinnedPeerCertSha256,
  384. );
  385. }
  386. toJson() {
  387. return {
  388. serverName: this.serverName,
  389. alpn: this.alpn,
  390. fingerprint: this.fingerprint,
  391. echConfigList: this.echConfigList,
  392. verifyPeerCertByName: this.verifyPeerCertByName,
  393. pinnedPeerCertSha256: this.pinnedPeerCertSha256
  394. };
  395. }
  396. }
  397. class RealityStreamSettings extends CommonClass {
  398. constructor(
  399. publicKey = '',
  400. fingerprint = '',
  401. serverName = '',
  402. shortId = '',
  403. spiderX = '',
  404. mldsa65Verify = ''
  405. ) {
  406. super();
  407. this.publicKey = publicKey;
  408. this.fingerprint = fingerprint;
  409. this.serverName = serverName;
  410. this.shortId = shortId
  411. this.spiderX = spiderX;
  412. this.mldsa65Verify = mldsa65Verify;
  413. }
  414. static fromJson(json = {}) {
  415. return new RealityStreamSettings(
  416. json.publicKey,
  417. json.fingerprint,
  418. json.serverName,
  419. json.shortId,
  420. json.spiderX,
  421. json.mldsa65Verify
  422. );
  423. }
  424. toJson() {
  425. return {
  426. publicKey: this.publicKey,
  427. fingerprint: this.fingerprint,
  428. serverName: this.serverName,
  429. shortId: this.shortId,
  430. spiderX: this.spiderX,
  431. mldsa65Verify: this.mldsa65Verify
  432. };
  433. }
  434. };
  435. class HysteriaStreamSettings extends CommonClass {
  436. constructor(
  437. version = 2,
  438. auth = '',
  439. congestion = '',
  440. up = '0',
  441. down = '0',
  442. udphopPort = '',
  443. udphopIntervalMin = 30,
  444. udphopIntervalMax = 30,
  445. initStreamReceiveWindow = 8388608,
  446. maxStreamReceiveWindow = 8388608,
  447. initConnectionReceiveWindow = 20971520,
  448. maxConnectionReceiveWindow = 20971520,
  449. maxIdleTimeout = 30,
  450. keepAlivePeriod = 0,
  451. disablePathMTUDiscovery = false
  452. ) {
  453. super();
  454. this.version = version;
  455. this.auth = auth;
  456. this.congestion = congestion;
  457. this.up = up;
  458. this.down = down;
  459. this.udphopPort = udphopPort;
  460. this.udphopIntervalMin = udphopIntervalMin;
  461. this.udphopIntervalMax = udphopIntervalMax;
  462. this.initStreamReceiveWindow = initStreamReceiveWindow;
  463. this.maxStreamReceiveWindow = maxStreamReceiveWindow;
  464. this.initConnectionReceiveWindow = initConnectionReceiveWindow;
  465. this.maxConnectionReceiveWindow = maxConnectionReceiveWindow;
  466. this.maxIdleTimeout = maxIdleTimeout;
  467. this.keepAlivePeriod = keepAlivePeriod;
  468. this.disablePathMTUDiscovery = disablePathMTUDiscovery;
  469. }
  470. static fromJson(json = {}) {
  471. let udphopPort = '';
  472. let udphopIntervalMin = 30;
  473. let udphopIntervalMax = 30;
  474. if (json.udphop) {
  475. udphopPort = json.udphop.port || '';
  476. // Backward compatibility: if old 'interval' exists, use it for both min/max
  477. if (json.udphop.interval !== undefined) {
  478. udphopIntervalMin = json.udphop.interval;
  479. udphopIntervalMax = json.udphop.interval;
  480. } else {
  481. udphopIntervalMin = json.udphop.intervalMin || 30;
  482. udphopIntervalMax = json.udphop.intervalMax || 30;
  483. }
  484. }
  485. return new HysteriaStreamSettings(
  486. json.version,
  487. json.auth,
  488. json.congestion,
  489. json.up,
  490. json.down,
  491. udphopPort,
  492. udphopIntervalMin,
  493. udphopIntervalMax,
  494. json.initStreamReceiveWindow,
  495. json.maxStreamReceiveWindow,
  496. json.initConnectionReceiveWindow,
  497. json.maxConnectionReceiveWindow,
  498. json.maxIdleTimeout,
  499. json.keepAlivePeriod,
  500. json.disablePathMTUDiscovery
  501. );
  502. }
  503. toJson() {
  504. const result = {
  505. version: this.version,
  506. auth: this.auth,
  507. congestion: this.congestion,
  508. up: this.up,
  509. down: this.down,
  510. initStreamReceiveWindow: this.initStreamReceiveWindow,
  511. maxStreamReceiveWindow: this.maxStreamReceiveWindow,
  512. initConnectionReceiveWindow: this.initConnectionReceiveWindow,
  513. maxConnectionReceiveWindow: this.maxConnectionReceiveWindow,
  514. maxIdleTimeout: this.maxIdleTimeout,
  515. keepAlivePeriod: this.keepAlivePeriod,
  516. disablePathMTUDiscovery: this.disablePathMTUDiscovery
  517. };
  518. if (this.udphopPort) {
  519. result.udphop = {
  520. port: this.udphopPort,
  521. intervalMin: this.udphopIntervalMin,
  522. intervalMax: this.udphopIntervalMax
  523. };
  524. }
  525. return result;
  526. }
  527. };
  528. class SockoptStreamSettings extends CommonClass {
  529. constructor(
  530. dialerProxy = "",
  531. tcpFastOpen = false,
  532. tcpKeepAliveInterval = 0,
  533. tcpMptcp = false,
  534. penetrate = false,
  535. addressPortStrategy = Address_Port_Strategy.NONE,
  536. trustedXForwardedFor = [],
  537. ) {
  538. super();
  539. this.dialerProxy = dialerProxy;
  540. this.tcpFastOpen = tcpFastOpen;
  541. this.tcpKeepAliveInterval = tcpKeepAliveInterval;
  542. this.tcpMptcp = tcpMptcp;
  543. this.penetrate = penetrate;
  544. this.addressPortStrategy = addressPortStrategy;
  545. this.trustedXForwardedFor = trustedXForwardedFor;
  546. }
  547. static fromJson(json = {}) {
  548. if (Object.keys(json).length === 0) return undefined;
  549. return new SockoptStreamSettings(
  550. json.dialerProxy,
  551. json.tcpFastOpen,
  552. json.tcpKeepAliveInterval,
  553. json.tcpMptcp,
  554. json.penetrate,
  555. json.addressPortStrategy,
  556. json.trustedXForwardedFor || []
  557. );
  558. }
  559. toJson() {
  560. const result = {
  561. dialerProxy: this.dialerProxy,
  562. tcpFastOpen: this.tcpFastOpen,
  563. tcpKeepAliveInterval: this.tcpKeepAliveInterval,
  564. tcpMptcp: this.tcpMptcp,
  565. penetrate: this.penetrate,
  566. addressPortStrategy: this.addressPortStrategy
  567. };
  568. if (this.trustedXForwardedFor && this.trustedXForwardedFor.length > 0) {
  569. result.trustedXForwardedFor = this.trustedXForwardedFor;
  570. }
  571. return result;
  572. }
  573. }
  574. class UdpMask extends CommonClass {
  575. constructor(type = 'salamander', settings = {}) {
  576. super();
  577. this.type = type;
  578. this.settings = this._getDefaultSettings(type, settings);
  579. }
  580. _getDefaultSettings(type, settings = {}) {
  581. switch (type) {
  582. case 'salamander':
  583. case 'mkcp-aes128gcm':
  584. return { password: settings.password || '' };
  585. case 'header-dns':
  586. return { domain: settings.domain || '' };
  587. case 'xdns':
  588. return { resolvers: Array.isArray(settings.resolvers) ? settings.resolvers : [] };
  589. case 'xicmp':
  590. return { ip: settings.ip || '', id: settings.id ?? 0 };
  591. case 'mkcp-original':
  592. case 'header-dtls':
  593. case 'header-srtp':
  594. case 'header-utp':
  595. case 'header-wechat':
  596. case 'header-wireguard':
  597. return {}; // No settings needed
  598. case 'header-custom':
  599. return {
  600. client: Array.isArray(settings.client) ? settings.client : [],
  601. server: Array.isArray(settings.server) ? settings.server : [],
  602. };
  603. case 'noise':
  604. return {
  605. reset: settings.reset ?? 0,
  606. noise: Array.isArray(settings.noise) ? settings.noise : [],
  607. };
  608. case 'sudoku':
  609. return {
  610. ascii: settings.ascii || '',
  611. customTable: settings.customTable || '',
  612. customTables: Array.isArray(settings.customTables) ? settings.customTables : [],
  613. paddingMin: settings.paddingMin ?? 0,
  614. paddingMax: settings.paddingMax ?? 0
  615. };
  616. default:
  617. return settings;
  618. }
  619. }
  620. static fromJson(json = {}) {
  621. return new UdpMask(
  622. json.type || 'salamander',
  623. json.settings || {}
  624. );
  625. }
  626. toJson() {
  627. const cleanItem = item => {
  628. const out = { ...item };
  629. if (out.type === 'array') {
  630. delete out.packet;
  631. } else {
  632. out.rand = 0;
  633. }
  634. return out;
  635. };
  636. let settings = this.settings;
  637. if (this.type === 'noise' && settings && Array.isArray(settings.noise)) {
  638. settings = { ...settings, noise: settings.noise.map(cleanItem) };
  639. } else if (this.type === 'header-custom' && settings) {
  640. settings = {
  641. ...settings,
  642. client: Array.isArray(settings.client) ? settings.client.map(cleanItem) : settings.client,
  643. server: Array.isArray(settings.server) ? settings.server.map(cleanItem) : settings.server,
  644. };
  645. }
  646. return {
  647. type: this.type,
  648. settings: (settings && Object.keys(settings).length > 0) ? settings : undefined
  649. };
  650. }
  651. }
  652. class FinalMaskStreamSettings extends CommonClass {
  653. constructor(udp = []) {
  654. super();
  655. this.udp = Array.isArray(udp) ? udp.map(u => new UdpMask(u.type, u.settings)) : [new UdpMask(udp.type, udp.settings)];
  656. }
  657. static fromJson(json = {}) {
  658. return new FinalMaskStreamSettings(json.udp || []);
  659. }
  660. toJson() {
  661. return {
  662. udp: this.udp.map(udp => udp.toJson())
  663. };
  664. }
  665. }
  666. class StreamSettings extends CommonClass {
  667. constructor(
  668. network = 'tcp',
  669. security = 'none',
  670. tlsSettings = new TlsStreamSettings(),
  671. realitySettings = new RealityStreamSettings(),
  672. tcpSettings = new TcpStreamSettings(),
  673. kcpSettings = new KcpStreamSettings(),
  674. wsSettings = new WsStreamSettings(),
  675. grpcSettings = new GrpcStreamSettings(),
  676. httpupgradeSettings = new HttpUpgradeStreamSettings(),
  677. xhttpSettings = new xHTTPStreamSettings(),
  678. hysteriaSettings = new HysteriaStreamSettings(),
  679. finalmask = new FinalMaskStreamSettings(),
  680. sockopt = undefined,
  681. ) {
  682. super();
  683. this.network = network;
  684. this.security = security;
  685. this.tls = tlsSettings;
  686. this.reality = realitySettings;
  687. this.tcp = tcpSettings;
  688. this.kcp = kcpSettings;
  689. this.ws = wsSettings;
  690. this.grpc = grpcSettings;
  691. this.httpupgrade = httpupgradeSettings;
  692. this.xhttp = xhttpSettings;
  693. this.hysteria = hysteriaSettings;
  694. this.finalmask = finalmask;
  695. this.sockopt = sockopt;
  696. }
  697. addUdpMask(type = 'salamander') {
  698. this.finalmask.udp.push(new UdpMask(type));
  699. }
  700. delUdpMask(index) {
  701. if (this.finalmask.udp) {
  702. this.finalmask.udp.splice(index, 1);
  703. }
  704. }
  705. get hasFinalMask() {
  706. return this.finalmask.udp && this.finalmask.udp.length > 0;
  707. }
  708. get isTls() {
  709. return this.security === 'tls';
  710. }
  711. get isReality() {
  712. return this.security === "reality";
  713. }
  714. get sockoptSwitch() {
  715. return this.sockopt != undefined;
  716. }
  717. set sockoptSwitch(value) {
  718. this.sockopt = value ? new SockoptStreamSettings() : undefined;
  719. }
  720. static fromJson(json = {}) {
  721. return new StreamSettings(
  722. json.network,
  723. json.security,
  724. TlsStreamSettings.fromJson(json.tlsSettings),
  725. RealityStreamSettings.fromJson(json.realitySettings),
  726. TcpStreamSettings.fromJson(json.tcpSettings),
  727. KcpStreamSettings.fromJson(json.kcpSettings),
  728. WsStreamSettings.fromJson(json.wsSettings),
  729. GrpcStreamSettings.fromJson(json.grpcSettings),
  730. HttpUpgradeStreamSettings.fromJson(json.httpupgradeSettings),
  731. xHTTPStreamSettings.fromJson(json.xhttpSettings),
  732. HysteriaStreamSettings.fromJson(json.hysteriaSettings),
  733. FinalMaskStreamSettings.fromJson(json.finalmask),
  734. SockoptStreamSettings.fromJson(json.sockopt),
  735. );
  736. }
  737. toJson() {
  738. const network = this.network;
  739. return {
  740. network: network,
  741. security: this.security,
  742. tlsSettings: this.security == 'tls' ? this.tls.toJson() : undefined,
  743. realitySettings: this.security == 'reality' ? this.reality.toJson() : undefined,
  744. tcpSettings: network === 'tcp' ? this.tcp.toJson() : undefined,
  745. kcpSettings: network === 'kcp' ? this.kcp.toJson() : undefined,
  746. wsSettings: network === 'ws' ? this.ws.toJson() : undefined,
  747. grpcSettings: network === 'grpc' ? this.grpc.toJson() : undefined,
  748. httpupgradeSettings: network === 'httpupgrade' ? this.httpupgrade.toJson() : undefined,
  749. xhttpSettings: network === 'xhttp' ? this.xhttp.toJson() : undefined,
  750. hysteriaSettings: network === 'hysteria' ? this.hysteria.toJson() : undefined,
  751. finalmask: this.hasFinalMask ? this.finalmask.toJson() : undefined,
  752. sockopt: this.sockopt != undefined ? this.sockopt.toJson() : undefined,
  753. };
  754. }
  755. }
  756. class Mux extends CommonClass {
  757. constructor(enabled = false, concurrency = 8, xudpConcurrency = 16, xudpProxyUDP443 = "reject") {
  758. super();
  759. this.enabled = enabled;
  760. this.concurrency = concurrency;
  761. this.xudpConcurrency = xudpConcurrency;
  762. this.xudpProxyUDP443 = xudpProxyUDP443;
  763. }
  764. static fromJson(json = {}) {
  765. if (Object.keys(json).length === 0) return undefined;
  766. return new Mux(
  767. json.enabled,
  768. json.concurrency,
  769. json.xudpConcurrency,
  770. json.xudpProxyUDP443,
  771. );
  772. }
  773. toJson() {
  774. return {
  775. enabled: this.enabled,
  776. concurrency: this.concurrency,
  777. xudpConcurrency: this.xudpConcurrency,
  778. xudpProxyUDP443: this.xudpProxyUDP443,
  779. };
  780. }
  781. }
  782. class Outbound extends CommonClass {
  783. constructor(
  784. tag = '',
  785. protocol = Protocols.VLESS,
  786. settings = null,
  787. streamSettings = new StreamSettings(),
  788. sendThrough,
  789. mux = new Mux(),
  790. ) {
  791. super();
  792. this.tag = tag;
  793. this._protocol = protocol;
  794. this.settings = settings == null ? Outbound.Settings.getSettings(protocol) : settings;
  795. this.stream = streamSettings;
  796. this.sendThrough = sendThrough;
  797. this.mux = mux;
  798. }
  799. get protocol() {
  800. return this._protocol;
  801. }
  802. set protocol(protocol) {
  803. this._protocol = protocol;
  804. this.settings = Outbound.Settings.getSettings(protocol);
  805. this.stream = new StreamSettings();
  806. }
  807. canEnableTls() {
  808. if (this.protocol === Protocols.Hysteria) return true;
  809. if (![Protocols.VMess, Protocols.VLESS, Protocols.Trojan, Protocols.Shadowsocks].includes(this.protocol)) return false;
  810. return ["tcp", "ws", "http", "grpc", "httpupgrade", "xhttp"].includes(this.stream.network);
  811. }
  812. //this is used for xtls-rprx-vision
  813. canEnableTlsFlow() {
  814. if ((this.stream.security != 'none') && (this.stream.network === "tcp")) {
  815. return this.protocol === Protocols.VLESS;
  816. }
  817. return false;
  818. }
  819. // Vision seed applies only when vision flow is selected
  820. canEnableVisionSeed() {
  821. if (!this.canEnableTlsFlow()) return false;
  822. const flow = this.settings?.flow;
  823. return flow === TLS_FLOW_CONTROL.VISION || flow === TLS_FLOW_CONTROL.VISION_UDP443;
  824. }
  825. canEnableReality() {
  826. if (![Protocols.VLESS, Protocols.Trojan].includes(this.protocol)) return false;
  827. return ["tcp", "http", "grpc", "xhttp"].includes(this.stream.network);
  828. }
  829. canEnableStream() {
  830. return [Protocols.VMess, Protocols.VLESS, Protocols.Trojan, Protocols.Shadowsocks, Protocols.Hysteria].includes(this.protocol);
  831. }
  832. canEnableMux() {
  833. // Disable Mux if flow is set
  834. if (this.settings.flow && this.settings.flow !== '') {
  835. this.mux.enabled = false;
  836. return false;
  837. }
  838. // Disable Mux if network is xhttp
  839. if (this.stream.network === 'xhttp') {
  840. this.mux.enabled = false;
  841. return false;
  842. }
  843. // Allow Mux only for these protocols
  844. return [
  845. Protocols.VMess,
  846. Protocols.VLESS,
  847. Protocols.Trojan,
  848. Protocols.Shadowsocks,
  849. Protocols.HTTP,
  850. Protocols.Socks
  851. ].includes(this.protocol);
  852. }
  853. hasServers() {
  854. return [Protocols.Trojan, Protocols.Shadowsocks, Protocols.Socks, Protocols.HTTP].includes(this.protocol);
  855. }
  856. hasAddressPort() {
  857. return [
  858. Protocols.DNS,
  859. Protocols.VMess,
  860. Protocols.VLESS,
  861. Protocols.Trojan,
  862. Protocols.Shadowsocks,
  863. Protocols.Socks,
  864. Protocols.HTTP,
  865. Protocols.Hysteria
  866. ].includes(this.protocol);
  867. }
  868. hasUsername() {
  869. return [Protocols.Socks, Protocols.HTTP].includes(this.protocol);
  870. }
  871. static fromJson(json = {}) {
  872. return new Outbound(
  873. json.tag,
  874. json.protocol,
  875. Outbound.Settings.fromJson(json.protocol, json.settings),
  876. StreamSettings.fromJson(json.streamSettings),
  877. json.sendThrough,
  878. Mux.fromJson(json.mux),
  879. )
  880. }
  881. toJson() {
  882. var stream;
  883. if (this.canEnableStream()) {
  884. stream = this.stream.toJson();
  885. } else {
  886. if (this.stream?.sockopt)
  887. stream = { sockopt: this.stream.sockopt.toJson() };
  888. }
  889. let settingsOut = this.settings instanceof CommonClass ? this.settings.toJson() : this.settings;
  890. return {
  891. protocol: this.protocol,
  892. settings: settingsOut,
  893. // Only include tag, streamSettings, sendThrough, mux if present and not empty
  894. ...(this.tag ? { tag: this.tag } : {}),
  895. ...(stream ? { streamSettings: stream } : {}),
  896. ...(this.sendThrough ? { sendThrough: this.sendThrough } : {}),
  897. ...(this.mux?.enabled ? { mux: this.mux } : {}),
  898. };
  899. }
  900. static fromLink(link) {
  901. data = link.split('://');
  902. if (data.length != 2) return null;
  903. switch (data[0].toLowerCase()) {
  904. case Protocols.VMess:
  905. return this.fromVmessLink(JSON.parse(Base64.decode(data[1])));
  906. case Protocols.VLESS:
  907. case Protocols.Trojan:
  908. case 'ss':
  909. return this.fromParamLink(link);
  910. case 'hysteria2':
  911. case Protocols.Hysteria:
  912. return this.fromHysteriaLink(link);
  913. default:
  914. return null;
  915. }
  916. }
  917. static fromVmessLink(json = {}) {
  918. let stream = new StreamSettings(json.net, json.tls);
  919. let network = json.net;
  920. if (network === 'tcp') {
  921. stream.tcp = new TcpStreamSettings(
  922. json.type,
  923. json.host ?? '',
  924. json.path ?? '');
  925. } else if (network === 'kcp') {
  926. stream.kcp = new KcpStreamSettings();
  927. stream.type = json.type;
  928. stream.seed = json.path;
  929. const mtu = Number(json.mtu);
  930. if (Number.isFinite(mtu) && mtu > 0) stream.kcp.mtu = mtu;
  931. const tti = Number(json.tti);
  932. if (Number.isFinite(tti) && tti > 0) stream.kcp.tti = tti;
  933. } else if (network === 'ws') {
  934. stream.ws = new WsStreamSettings(json.path, json.host);
  935. } else if (network === 'grpc') {
  936. stream.grpc = new GrpcStreamSettings(json.path, json.authority, json.type == 'multi');
  937. } else if (network === 'httpupgrade') {
  938. stream.httpupgrade = new HttpUpgradeStreamSettings(json.path, json.host);
  939. } else if (network === 'xhttp') {
  940. // xHTTPStreamSettings positional args are (path, host, headers, ..., mode);
  941. // passing `json.mode` as the 3rd argument used to land in the `headers`
  942. // slot, dropping the mode on the floor. Build the object and set mode
  943. // explicitly to avoid that.
  944. const xh = new xHTTPStreamSettings(json.path, json.host);
  945. if (json.mode) xh.mode = json.mode;
  946. stream.xhttp = xh;
  947. }
  948. if (json.tls && json.tls == 'tls') {
  949. stream.tls = new TlsStreamSettings(
  950. json.sni,
  951. json.alpn ? json.alpn.split(',') : [],
  952. json.fp);
  953. }
  954. const port = json.port * 1;
  955. return new Outbound(json.ps, Protocols.VMess, new Outbound.VmessSettings(json.add, port, json.id, json.scy), stream);
  956. }
  957. static fromParamLink(link) {
  958. const url = new URL(link);
  959. let type = url.searchParams.get('type') ?? 'tcp';
  960. let security = url.searchParams.get('security') ?? 'none';
  961. let stream = new StreamSettings(type, security);
  962. let headerType = url.searchParams.get('headerType') ?? undefined;
  963. let host = url.searchParams.get('host') ?? undefined;
  964. let path = url.searchParams.get('path') ?? undefined;
  965. let seed = url.searchParams.get('seed') ?? path ?? undefined;
  966. let mode = url.searchParams.get('mode') ?? undefined;
  967. if (type === 'tcp' || type === 'none') {
  968. stream.tcp = new TcpStreamSettings(headerType ?? 'none', host, path);
  969. } else if (type === 'kcp') {
  970. stream.kcp = new KcpStreamSettings();
  971. stream.kcp.type = headerType ?? 'none';
  972. stream.kcp.seed = seed;
  973. const mtu = Number(url.searchParams.get('mtu'));
  974. if (Number.isFinite(mtu) && mtu > 0) stream.kcp.mtu = mtu;
  975. const tti = Number(url.searchParams.get('tti'));
  976. if (Number.isFinite(tti) && tti > 0) stream.kcp.tti = tti;
  977. } else if (type === 'ws') {
  978. stream.ws = new WsStreamSettings(path, host);
  979. } else if (type === 'grpc') {
  980. stream.grpc = new GrpcStreamSettings(
  981. url.searchParams.get('serviceName') ?? '',
  982. url.searchParams.get('authority') ?? '',
  983. url.searchParams.get('mode') == 'multi');
  984. } else if (type === 'httpupgrade') {
  985. stream.httpupgrade = new HttpUpgradeStreamSettings(path, host);
  986. } else if (type === 'xhttp') {
  987. // Same positional bug as in the VMess-JSON branch above:
  988. // passing `mode` as the 3rd positional arg put it into the
  989. // `headers` slot. Build explicitly instead.
  990. const xh = new xHTTPStreamSettings(path, host);
  991. if (mode) xh.mode = mode;
  992. const xpb = url.searchParams.get('x_padding_bytes');
  993. if (xpb) xh.xPaddingBytes = xpb;
  994. const extraRaw = url.searchParams.get('extra');
  995. if (extraRaw) {
  996. try {
  997. const extra = JSON.parse(extraRaw);
  998. if (typeof extra.xPaddingBytes === 'string' && extra.xPaddingBytes) xh.xPaddingBytes = extra.xPaddingBytes;
  999. if (extra.xPaddingObfsMode === true) xh.xPaddingObfsMode = true;
  1000. ["xPaddingKey", "xPaddingHeader", "xPaddingPlacement", "xPaddingMethod"].forEach(k => {
  1001. if (typeof extra[k] === 'string' && extra[k]) xh[k] = extra[k];
  1002. });
  1003. } catch (_) { /* ignore malformed extra */ }
  1004. }
  1005. stream.xhttp = xh;
  1006. }
  1007. if (security == 'tls') {
  1008. let fp = url.searchParams.get('fp') ?? 'none';
  1009. let alpn = url.searchParams.get('alpn');
  1010. let sni = url.searchParams.get('sni') ?? '';
  1011. let ech = url.searchParams.get('ech') ?? '';
  1012. stream.tls = new TlsStreamSettings(sni, alpn ? alpn.split(',') : [], fp, ech);
  1013. }
  1014. if (security == 'reality') {
  1015. let pbk = url.searchParams.get('pbk');
  1016. let fp = url.searchParams.get('fp');
  1017. let sni = url.searchParams.get('sni') ?? '';
  1018. let sid = url.searchParams.get('sid') ?? '';
  1019. let spx = url.searchParams.get('spx') ?? '';
  1020. let pqv = url.searchParams.get('pqv') ?? '';
  1021. stream.reality = new RealityStreamSettings(pbk, fp, sni, sid, spx, pqv);
  1022. }
  1023. const regex = /([^@]+):\/\/([^@]+)@(.+):(\d+)(.*)$/;
  1024. const match = link.match(regex);
  1025. if (!match) return null;
  1026. let [, protocol, userData, address, port,] = match;
  1027. port *= 1;
  1028. if (protocol == 'ss') {
  1029. protocol = 'shadowsocks';
  1030. userData = atob(userData).split(':');
  1031. }
  1032. var settings;
  1033. switch (protocol) {
  1034. case Protocols.VLESS:
  1035. settings = new Outbound.VLESSSettings(address, port, userData, url.searchParams.get('flow') ?? '', url.searchParams.get('encryption') ?? 'none');
  1036. break;
  1037. case Protocols.Trojan:
  1038. settings = new Outbound.TrojanSettings(address, port, userData);
  1039. break;
  1040. case Protocols.Shadowsocks:
  1041. let method = userData.splice(0, 1)[0];
  1042. settings = new Outbound.ShadowsocksSettings(address, port, userData.join(":"), method, true);
  1043. break;
  1044. default:
  1045. return null;
  1046. }
  1047. let remark = decodeURIComponent(url.hash);
  1048. // Remove '#' from url.hash
  1049. remark = remark.length > 0 ? remark.substring(1) : 'out-' + protocol + '-' + port;
  1050. return new Outbound(remark, protocol, settings, stream);
  1051. }
  1052. static fromHysteriaLink(link) {
  1053. // Parse hysteria2://password@address:port[?param1=value1&param2=value2...][#remarks]
  1054. const regex = /^hysteria2?:\/\/([^@]+)@([^:?#]+):(\d+)([^#]*)(#.*)?$/;
  1055. const match = link.match(regex);
  1056. if (!match) return null;
  1057. let [, password, address, port, params, hash] = match;
  1058. port = parseInt(port);
  1059. // Parse URL parameters if present
  1060. let urlParams = new URLSearchParams(params);
  1061. // Create stream settings with hysteria network
  1062. let stream = new StreamSettings('hysteria', 'none');
  1063. // Set hysteria stream settings
  1064. stream.hysteria.auth = password;
  1065. stream.hysteria.congestion = urlParams.get('congestion') ?? '';
  1066. stream.hysteria.up = urlParams.get('up') ?? '0';
  1067. stream.hysteria.down = urlParams.get('down') ?? '0';
  1068. stream.hysteria.udphopPort = urlParams.get('udphopPort') ?? '';
  1069. // Support both old single interval and new min/max range
  1070. if (urlParams.has('udphopInterval')) {
  1071. const interval = parseInt(urlParams.get('udphopInterval'));
  1072. stream.hysteria.udphopIntervalMin = interval;
  1073. stream.hysteria.udphopIntervalMax = interval;
  1074. } else {
  1075. stream.hysteria.udphopIntervalMin = parseInt(urlParams.get('udphopIntervalMin') ?? '30');
  1076. stream.hysteria.udphopIntervalMax = parseInt(urlParams.get('udphopIntervalMax') ?? '30');
  1077. }
  1078. // Optional QUIC parameters
  1079. if (urlParams.has('initStreamReceiveWindow')) {
  1080. stream.hysteria.initStreamReceiveWindow = parseInt(urlParams.get('initStreamReceiveWindow'));
  1081. }
  1082. if (urlParams.has('maxStreamReceiveWindow')) {
  1083. stream.hysteria.maxStreamReceiveWindow = parseInt(urlParams.get('maxStreamReceiveWindow'));
  1084. }
  1085. if (urlParams.has('initConnectionReceiveWindow')) {
  1086. stream.hysteria.initConnectionReceiveWindow = parseInt(urlParams.get('initConnectionReceiveWindow'));
  1087. }
  1088. if (urlParams.has('maxConnectionReceiveWindow')) {
  1089. stream.hysteria.maxConnectionReceiveWindow = parseInt(urlParams.get('maxConnectionReceiveWindow'));
  1090. }
  1091. if (urlParams.has('maxIdleTimeout')) {
  1092. stream.hysteria.maxIdleTimeout = parseInt(urlParams.get('maxIdleTimeout'));
  1093. }
  1094. if (urlParams.has('keepAlivePeriod')) {
  1095. stream.hysteria.keepAlivePeriod = parseInt(urlParams.get('keepAlivePeriod'));
  1096. }
  1097. if (urlParams.has('disablePathMTUDiscovery')) {
  1098. stream.hysteria.disablePathMTUDiscovery = urlParams.get('disablePathMTUDiscovery') === 'true';
  1099. }
  1100. // Create settings
  1101. let settings = new Outbound.HysteriaSettings(address, port, 2);
  1102. // Extract remark from hash
  1103. let remark = hash ? decodeURIComponent(hash.substring(1)) : `out-hysteria-${port}`;
  1104. return new Outbound(remark, Protocols.Hysteria, settings, stream);
  1105. }
  1106. }
  1107. Outbound.Settings = class extends CommonClass {
  1108. constructor(protocol) {
  1109. super();
  1110. this.protocol = protocol;
  1111. }
  1112. static getSettings(protocol) {
  1113. switch (protocol) {
  1114. case Protocols.Freedom: return new Outbound.FreedomSettings();
  1115. case Protocols.Blackhole: return new Outbound.BlackholeSettings();
  1116. case Protocols.DNS: return new Outbound.DNSSettings();
  1117. case Protocols.VMess: return new Outbound.VmessSettings();
  1118. case Protocols.VLESS: return new Outbound.VLESSSettings();
  1119. case Protocols.Trojan: return new Outbound.TrojanSettings();
  1120. case Protocols.Shadowsocks: return new Outbound.ShadowsocksSettings();
  1121. case Protocols.Socks: return new Outbound.SocksSettings();
  1122. case Protocols.HTTP: return new Outbound.HttpSettings();
  1123. case Protocols.Wireguard: return new Outbound.WireguardSettings();
  1124. case Protocols.Hysteria: return new Outbound.HysteriaSettings();
  1125. default: return null;
  1126. }
  1127. }
  1128. static fromJson(protocol, json) {
  1129. switch (protocol) {
  1130. case Protocols.Freedom: return Outbound.FreedomSettings.fromJson(json);
  1131. case Protocols.Blackhole: return Outbound.BlackholeSettings.fromJson(json);
  1132. case Protocols.DNS: return Outbound.DNSSettings.fromJson(json);
  1133. case Protocols.VMess: return Outbound.VmessSettings.fromJson(json);
  1134. case Protocols.VLESS: return Outbound.VLESSSettings.fromJson(json);
  1135. case Protocols.Trojan: return Outbound.TrojanSettings.fromJson(json);
  1136. case Protocols.Shadowsocks: return Outbound.ShadowsocksSettings.fromJson(json);
  1137. case Protocols.Socks: return Outbound.SocksSettings.fromJson(json);
  1138. case Protocols.HTTP: return Outbound.HttpSettings.fromJson(json);
  1139. case Protocols.Wireguard: return Outbound.WireguardSettings.fromJson(json);
  1140. case Protocols.Hysteria: return Outbound.HysteriaSettings.fromJson(json);
  1141. default: return null;
  1142. }
  1143. }
  1144. toJson() {
  1145. return {};
  1146. }
  1147. };
  1148. Outbound.FreedomSettings = class extends CommonClass {
  1149. constructor(
  1150. domainStrategy = '',
  1151. redirect = '',
  1152. fragment = {},
  1153. noises = [],
  1154. ipsBlocked = [],
  1155. ) {
  1156. super();
  1157. this.domainStrategy = domainStrategy;
  1158. this.redirect = redirect;
  1159. this.fragment = fragment || {};
  1160. this.noises = Array.isArray(noises) ? noises : [];
  1161. this.ipsBlocked = Array.isArray(ipsBlocked) ? ipsBlocked : [];
  1162. }
  1163. addNoise() {
  1164. this.noises.push(new Outbound.FreedomSettings.Noise());
  1165. }
  1166. delNoise(index) {
  1167. this.noises.splice(index, 1);
  1168. }
  1169. static fromJson(json = {}) {
  1170. return new Outbound.FreedomSettings(
  1171. json.domainStrategy,
  1172. json.redirect,
  1173. json.fragment ? Outbound.FreedomSettings.Fragment.fromJson(json.fragment) : {},
  1174. json.noises ? json.noises.map(noise => Outbound.FreedomSettings.Noise.fromJson(noise)) : [],
  1175. json.ipsBlocked || [],
  1176. );
  1177. }
  1178. toJson() {
  1179. return {
  1180. domainStrategy: ObjectUtil.isEmpty(this.domainStrategy) ? undefined : this.domainStrategy,
  1181. redirect: ObjectUtil.isEmpty(this.redirect) ? undefined : this.redirect,
  1182. fragment: Object.keys(this.fragment).length === 0 ? undefined : this.fragment,
  1183. noises: this.noises.length === 0 ? undefined : Outbound.FreedomSettings.Noise.toJsonArray(this.noises),
  1184. ipsBlocked: this.ipsBlocked.length === 0 ? undefined : this.ipsBlocked,
  1185. };
  1186. }
  1187. };
  1188. Outbound.FreedomSettings.Fragment = class extends CommonClass {
  1189. constructor(
  1190. packets = '1-3',
  1191. length = '',
  1192. interval = '',
  1193. maxSplit = ''
  1194. ) {
  1195. super();
  1196. this.packets = packets;
  1197. this.length = length;
  1198. this.interval = interval;
  1199. this.maxSplit = maxSplit;
  1200. }
  1201. static fromJson(json = {}) {
  1202. return new Outbound.FreedomSettings.Fragment(
  1203. json.packets,
  1204. json.length,
  1205. json.interval,
  1206. json.maxSplit
  1207. );
  1208. }
  1209. };
  1210. Outbound.FreedomSettings.Noise = class extends CommonClass {
  1211. constructor(
  1212. type = 'rand',
  1213. packet = '10-20',
  1214. delay = '10-16',
  1215. applyTo = 'ip'
  1216. ) {
  1217. super();
  1218. this.type = type;
  1219. this.packet = packet;
  1220. this.delay = delay;
  1221. this.applyTo = applyTo;
  1222. }
  1223. static fromJson(json = {}) {
  1224. return new Outbound.FreedomSettings.Noise(
  1225. json.type,
  1226. json.packet,
  1227. json.delay,
  1228. json.applyTo
  1229. );
  1230. }
  1231. toJson() {
  1232. return {
  1233. type: this.type,
  1234. packet: this.packet,
  1235. delay: this.delay,
  1236. applyTo: this.applyTo
  1237. };
  1238. }
  1239. };
  1240. Outbound.BlackholeSettings = class extends CommonClass {
  1241. constructor(type) {
  1242. super();
  1243. this.type = type;
  1244. }
  1245. static fromJson(json = {}) {
  1246. return new Outbound.BlackholeSettings(
  1247. json.response ? json.response.type : undefined,
  1248. );
  1249. }
  1250. toJson() {
  1251. return {
  1252. response: ObjectUtil.isEmpty(this.type) ? undefined : { type: this.type },
  1253. };
  1254. }
  1255. };
  1256. Outbound.DNSRule = class extends CommonClass {
  1257. constructor(action = 'direct', qtype = '', domain = '') {
  1258. super();
  1259. this.action = action;
  1260. this.qtype = qtype;
  1261. this.domain = domain;
  1262. }
  1263. static fromJson(json = {}) {
  1264. return new Outbound.DNSRule(
  1265. json.action,
  1266. normalizeDNSRuleField(json.qtype),
  1267. normalizeDNSRuleField(json.domain),
  1268. );
  1269. }
  1270. toJson() {
  1271. const rule = {
  1272. action: normalizeDNSRuleAction(this.action),
  1273. };
  1274. const qtype = normalizeDNSRuleField(this.qtype);
  1275. if (!ObjectUtil.isEmpty(qtype)) {
  1276. if (/^\d+$/.test(qtype)) {
  1277. rule.qtype = Number(qtype);
  1278. } else {
  1279. rule.qtype = qtype;
  1280. }
  1281. }
  1282. const domains = normalizeDNSRuleField(this.domain)
  1283. .split(',')
  1284. .map(d => d.trim())
  1285. .filter(d => d.length > 0);
  1286. if (domains.length > 0) {
  1287. rule.domain = domains;
  1288. }
  1289. return rule;
  1290. }
  1291. };
  1292. Outbound.DNSSettings = class extends CommonClass {
  1293. constructor(
  1294. network = 'udp',
  1295. address = '',
  1296. port = 53,
  1297. rules = []
  1298. ) {
  1299. super();
  1300. this.network = network;
  1301. this.address = address;
  1302. this.port = port;
  1303. this.rules = Array.isArray(rules) ? rules.map(rule => rule instanceof Outbound.DNSRule ? rule : Outbound.DNSRule.fromJson(rule)) : [];
  1304. }
  1305. addRule(action = 'direct') {
  1306. this.rules.push(new Outbound.DNSRule(action));
  1307. }
  1308. delRule(index) {
  1309. this.rules.splice(index, 1);
  1310. }
  1311. static fromJson(json = {}) {
  1312. return new Outbound.DNSSettings(
  1313. json.network,
  1314. json.address,
  1315. json.port,
  1316. getDNSRulesFromJson(json),
  1317. );
  1318. }
  1319. toJson() {
  1320. const json = {
  1321. network: this.network,
  1322. address: this.address,
  1323. port: this.port,
  1324. };
  1325. if (this.rules.length > 0) {
  1326. json.rules = Outbound.DNSRule.toJsonArray(this.rules);
  1327. }
  1328. return json;
  1329. }
  1330. };
  1331. Outbound.VmessSettings = class extends CommonClass {
  1332. constructor(address, port, id, security) {
  1333. super();
  1334. this.address = address;
  1335. this.port = port;
  1336. this.id = id;
  1337. this.security = security;
  1338. }
  1339. static fromJson(json = {}) {
  1340. if (!ObjectUtil.isArrEmpty(json.vnext)) {
  1341. const v = json.vnext[0] || {};
  1342. const u = ObjectUtil.isArrEmpty(v.users) ? {} : v.users[0];
  1343. return new Outbound.VmessSettings(
  1344. v.address,
  1345. v.port,
  1346. u.id,
  1347. u.security,
  1348. );
  1349. }
  1350. }
  1351. toJson() {
  1352. return {
  1353. vnext: [{
  1354. address: this.address,
  1355. port: this.port,
  1356. users: [{
  1357. id: this.id,
  1358. security: this.security
  1359. }]
  1360. }]
  1361. };
  1362. }
  1363. };
  1364. Outbound.VLESSSettings = class extends CommonClass {
  1365. constructor(address, port, id, flow, encryption, testpre = 0, testseed = [900, 500, 900, 256]) {
  1366. super();
  1367. this.address = address;
  1368. this.port = port;
  1369. this.id = id;
  1370. this.flow = flow;
  1371. this.encryption = encryption;
  1372. this.testpre = testpre;
  1373. this.testseed = testseed;
  1374. }
  1375. static fromJson(json = {}) {
  1376. if (ObjectUtil.isEmpty(json.address) || ObjectUtil.isEmpty(json.port)) return new Outbound.VLESSSettings();
  1377. return new Outbound.VLESSSettings(
  1378. json.address,
  1379. json.port,
  1380. json.id,
  1381. json.flow,
  1382. json.encryption,
  1383. json.testpre || 0,
  1384. json.testseed && json.testseed.length >= 4 ? json.testseed : [900, 500, 900, 256]
  1385. );
  1386. }
  1387. toJson() {
  1388. const result = {
  1389. address: this.address,
  1390. port: this.port,
  1391. id: this.id,
  1392. flow: this.flow,
  1393. encryption: this.encryption,
  1394. };
  1395. // Only include Vision settings when flow is set
  1396. if (this.flow && this.flow !== '') {
  1397. if (this.testpre > 0) {
  1398. result.testpre = this.testpre;
  1399. }
  1400. if (this.testseed && this.testseed.length >= 4) {
  1401. result.testseed = this.testseed;
  1402. }
  1403. }
  1404. return result;
  1405. }
  1406. };
  1407. Outbound.TrojanSettings = class extends CommonClass {
  1408. constructor(address, port, password) {
  1409. super();
  1410. this.address = address;
  1411. this.port = port;
  1412. this.password = password;
  1413. }
  1414. static fromJson(json = {}) {
  1415. if (ObjectUtil.isArrEmpty(json.servers)) return new Outbound.TrojanSettings();
  1416. return new Outbound.TrojanSettings(
  1417. json.servers[0].address,
  1418. json.servers[0].port,
  1419. json.servers[0].password,
  1420. );
  1421. }
  1422. toJson() {
  1423. return {
  1424. servers: [{
  1425. address: this.address,
  1426. port: this.port,
  1427. password: this.password,
  1428. }],
  1429. };
  1430. }
  1431. };
  1432. Outbound.ShadowsocksSettings = class extends CommonClass {
  1433. constructor(address, port, password, method, uot, UoTVersion) {
  1434. super();
  1435. this.address = address;
  1436. this.port = port;
  1437. this.password = password;
  1438. this.method = method;
  1439. this.uot = uot;
  1440. this.UoTVersion = UoTVersion;
  1441. }
  1442. static fromJson(json = {}) {
  1443. let servers = json.servers;
  1444. if (ObjectUtil.isArrEmpty(servers)) servers = [{}];
  1445. return new Outbound.ShadowsocksSettings(
  1446. servers[0].address,
  1447. servers[0].port,
  1448. servers[0].password,
  1449. servers[0].method,
  1450. servers[0].uot,
  1451. servers[0].UoTVersion,
  1452. );
  1453. }
  1454. toJson() {
  1455. return {
  1456. servers: [{
  1457. address: this.address,
  1458. port: this.port,
  1459. password: this.password,
  1460. method: this.method,
  1461. uot: this.uot,
  1462. UoTVersion: this.UoTVersion,
  1463. }],
  1464. };
  1465. }
  1466. };
  1467. Outbound.SocksSettings = class extends CommonClass {
  1468. constructor(address, port, user, pass) {
  1469. super();
  1470. this.address = address;
  1471. this.port = port;
  1472. this.user = user;
  1473. this.pass = pass;
  1474. }
  1475. static fromJson(json = {}) {
  1476. let servers = json.servers;
  1477. if (ObjectUtil.isArrEmpty(servers)) servers = [{ users: [{}] }];
  1478. return new Outbound.SocksSettings(
  1479. servers[0].address,
  1480. servers[0].port,
  1481. ObjectUtil.isArrEmpty(servers[0].users) ? '' : servers[0].users[0].user,
  1482. ObjectUtil.isArrEmpty(servers[0].users) ? '' : servers[0].users[0].pass,
  1483. );
  1484. }
  1485. toJson() {
  1486. return {
  1487. servers: [{
  1488. address: this.address,
  1489. port: this.port,
  1490. users: ObjectUtil.isEmpty(this.user) ? [] : [{ user: this.user, pass: this.pass }],
  1491. }],
  1492. };
  1493. }
  1494. };
  1495. Outbound.HttpSettings = class extends CommonClass {
  1496. constructor(address, port, user, pass) {
  1497. super();
  1498. this.address = address;
  1499. this.port = port;
  1500. this.user = user;
  1501. this.pass = pass;
  1502. }
  1503. static fromJson(json = {}) {
  1504. let servers = json.servers;
  1505. if (ObjectUtil.isArrEmpty(servers)) servers = [{ users: [{}] }];
  1506. return new Outbound.HttpSettings(
  1507. servers[0].address,
  1508. servers[0].port,
  1509. ObjectUtil.isArrEmpty(servers[0].users) ? '' : servers[0].users[0].user,
  1510. ObjectUtil.isArrEmpty(servers[0].users) ? '' : servers[0].users[0].pass,
  1511. );
  1512. }
  1513. toJson() {
  1514. return {
  1515. servers: [{
  1516. address: this.address,
  1517. port: this.port,
  1518. users: ObjectUtil.isEmpty(this.user) ? [] : [{ user: this.user, pass: this.pass }],
  1519. }],
  1520. };
  1521. }
  1522. };
  1523. Outbound.WireguardSettings = class extends CommonClass {
  1524. constructor(
  1525. mtu = 1420,
  1526. secretKey = '',
  1527. address = [''],
  1528. workers = 2,
  1529. domainStrategy = '',
  1530. reserved = '',
  1531. peers = [new Outbound.WireguardSettings.Peer()],
  1532. noKernelTun = false,
  1533. ) {
  1534. super();
  1535. this.mtu = mtu;
  1536. this.secretKey = secretKey;
  1537. this.pubKey = secretKey.length > 0 ? Wireguard.generateKeypair(secretKey).publicKey : '';
  1538. this.address = Array.isArray(address) ? address.join(',') : address;
  1539. this.workers = workers;
  1540. this.domainStrategy = domainStrategy;
  1541. this.reserved = Array.isArray(reserved) ? reserved.join(',') : reserved;
  1542. this.peers = peers;
  1543. this.noKernelTun = noKernelTun;
  1544. }
  1545. addPeer() {
  1546. this.peers.push(new Outbound.WireguardSettings.Peer());
  1547. }
  1548. delPeer(index) {
  1549. this.peers.splice(index, 1);
  1550. }
  1551. static fromJson(json = {}) {
  1552. return new Outbound.WireguardSettings(
  1553. json.mtu,
  1554. json.secretKey,
  1555. json.address,
  1556. json.workers,
  1557. json.domainStrategy,
  1558. json.reserved,
  1559. json.peers.map(peer => Outbound.WireguardSettings.Peer.fromJson(peer)),
  1560. json.noKernelTun,
  1561. );
  1562. }
  1563. toJson() {
  1564. return {
  1565. mtu: this.mtu ?? undefined,
  1566. secretKey: this.secretKey,
  1567. address: this.address ? this.address.split(",") : [],
  1568. workers: this.workers ?? undefined,
  1569. domainStrategy: WireguardDomainStrategy.includes(this.domainStrategy) ? this.domainStrategy : undefined,
  1570. reserved: this.reserved ? this.reserved.split(",").map(Number) : undefined,
  1571. peers: Outbound.WireguardSettings.Peer.toJsonArray(this.peers),
  1572. noKernelTun: this.noKernelTun,
  1573. };
  1574. }
  1575. };
  1576. Outbound.WireguardSettings.Peer = class extends CommonClass {
  1577. constructor(
  1578. publicKey = '',
  1579. psk = '',
  1580. allowedIPs = ['0.0.0.0/0', '::/0'],
  1581. endpoint = '',
  1582. keepAlive = 0
  1583. ) {
  1584. super();
  1585. this.publicKey = publicKey;
  1586. this.psk = psk;
  1587. this.allowedIPs = allowedIPs;
  1588. this.endpoint = endpoint;
  1589. this.keepAlive = keepAlive;
  1590. }
  1591. static fromJson(json = {}) {
  1592. return new Outbound.WireguardSettings.Peer(
  1593. json.publicKey,
  1594. json.preSharedKey,
  1595. json.allowedIPs,
  1596. json.endpoint,
  1597. json.keepAlive
  1598. );
  1599. }
  1600. toJson() {
  1601. return {
  1602. publicKey: this.publicKey,
  1603. preSharedKey: this.psk.length > 0 ? this.psk : undefined,
  1604. allowedIPs: this.allowedIPs ? this.allowedIPs : undefined,
  1605. endpoint: this.endpoint,
  1606. keepAlive: this.keepAlive ?? undefined,
  1607. };
  1608. }
  1609. };
  1610. Outbound.HysteriaSettings = class extends CommonClass {
  1611. constructor(address = '', port = 443, version = 2) {
  1612. super();
  1613. this.address = address;
  1614. this.port = port;
  1615. this.version = version;
  1616. }
  1617. static fromJson(json = {}) {
  1618. if (Object.keys(json).length === 0) return new Outbound.HysteriaSettings();
  1619. return new Outbound.HysteriaSettings(
  1620. json.address,
  1621. json.port,
  1622. json.version
  1623. );
  1624. }
  1625. toJson() {
  1626. return {
  1627. address: this.address,
  1628. port: this.port,
  1629. version: this.version
  1630. };
  1631. }
  1632. };