outbound.js 73 KB

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