outbound.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  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. };
  13. const SSMethods = {
  14. AES_256_GCM: 'aes-256-gcm',
  15. AES_128_GCM: 'aes-128-gcm',
  16. CHACHA20_POLY1305: 'chacha20-poly1305',
  17. CHACHA20_IETF_POLY1305: 'chacha20-ietf-poly1305',
  18. XCHACHA20_POLY1305: 'xchacha20-poly1305',
  19. XCHACHA20_IETF_POLY1305: 'xchacha20-ietf-poly1305',
  20. BLAKE3_AES_128_GCM: '2022-blake3-aes-128-gcm',
  21. BLAKE3_AES_256_GCM: '2022-blake3-aes-256-gcm',
  22. BLAKE3_CHACHA20_POLY1305: '2022-blake3-chacha20-poly1305',
  23. };
  24. const TLS_FLOW_CONTROL = {
  25. VISION: "xtls-rprx-vision",
  26. VISION_UDP443: "xtls-rprx-vision-udp443",
  27. };
  28. const UTLS_FINGERPRINT = {
  29. UTLS_CHROME: "chrome",
  30. UTLS_FIREFOX: "firefox",
  31. UTLS_SAFARI: "safari",
  32. UTLS_IOS: "ios",
  33. UTLS_android: "android",
  34. UTLS_EDGE: "edge",
  35. UTLS_360: "360",
  36. UTLS_QQ: "qq",
  37. UTLS_RANDOM: "random",
  38. UTLS_RANDOMIZED: "randomized",
  39. UTLS_RONDOMIZEDNOALPN: "randomizednoalpn",
  40. UTLS_UNSAFE: "unsafe",
  41. };
  42. const ALPN_OPTION = {
  43. H3: "h3",
  44. H2: "h2",
  45. HTTP1: "http/1.1",
  46. };
  47. const OutboundDomainStrategies = [
  48. "AsIs",
  49. "UseIP",
  50. "UseIPv4",
  51. "UseIPv6",
  52. "UseIPv6v4",
  53. "UseIPv4v6",
  54. "ForceIP",
  55. "ForceIPv6v4",
  56. "ForceIPv6",
  57. "ForceIPv4v6",
  58. "ForceIPv4"
  59. ];
  60. const WireguardDomainStrategy = [
  61. "ForceIP",
  62. "ForceIPv4",
  63. "ForceIPv4v6",
  64. "ForceIPv6",
  65. "ForceIPv6v4"
  66. ];
  67. const USERS_SECURITY = {
  68. AES_128_GCM: "aes-128-gcm",
  69. CHACHA20_POLY1305: "chacha20-poly1305",
  70. AUTO: "auto",
  71. NONE: "none",
  72. ZERO: "zero",
  73. };
  74. const MODE_OPTION = {
  75. AUTO: "auto",
  76. PACKET_UP: "packet-up",
  77. STREAM_UP: "stream-up",
  78. STREAM_ONE: "stream-one",
  79. };
  80. const Address_Port_Strategy = {
  81. NONE: "none",
  82. SrvPortOnly: "srvportonly",
  83. SrvAddressOnly: "srvaddressonly",
  84. SrvPortAndAddress: "srvportandaddress",
  85. TxtPortOnly: "txtportonly",
  86. TxtAddressOnly: "txtaddressonly",
  87. TxtPortAndAddress: "txtportandaddress"
  88. };
  89. Object.freeze(Protocols);
  90. Object.freeze(SSMethods);
  91. Object.freeze(TLS_FLOW_CONTROL);
  92. Object.freeze(UTLS_FINGERPRINT);
  93. Object.freeze(ALPN_OPTION);
  94. Object.freeze(OutboundDomainStrategies);
  95. Object.freeze(WireguardDomainStrategy);
  96. Object.freeze(USERS_SECURITY);
  97. Object.freeze(MODE_OPTION);
  98. Object.freeze(Address_Port_Strategy);
  99. class CommonClass {
  100. static toJsonArray(arr) {
  101. return arr.map(obj => obj.toJson());
  102. }
  103. static fromJson() {
  104. return new CommonClass();
  105. }
  106. toJson() {
  107. return this;
  108. }
  109. toString(format = true) {
  110. return format ? JSON.stringify(this.toJson(), null, 2) : JSON.stringify(this.toJson());
  111. }
  112. }
  113. class TcpStreamSettings extends CommonClass {
  114. constructor(type = 'none', host, path) {
  115. super();
  116. this.type = type;
  117. this.host = host;
  118. this.path = path;
  119. }
  120. static fromJson(json = {}) {
  121. let header = json.header;
  122. if (!header) return new TcpStreamSettings();
  123. if (header.type == 'http' && header.request) {
  124. return new TcpStreamSettings(
  125. header.type,
  126. header.request.headers.Host.join(','),
  127. header.request.path.join(','),
  128. );
  129. }
  130. return new TcpStreamSettings(header.type, '', '');
  131. }
  132. toJson() {
  133. return {
  134. header: {
  135. type: this.type,
  136. request: this.type === 'http' ? {
  137. headers: {
  138. Host: ObjectUtil.isEmpty(this.host) ? [] : this.host.split(',')
  139. },
  140. path: ObjectUtil.isEmpty(this.path) ? ["/"] : this.path.split(',')
  141. } : undefined,
  142. }
  143. };
  144. }
  145. }
  146. class KcpStreamSettings extends CommonClass {
  147. constructor(
  148. mtu = 1350,
  149. tti = 50,
  150. uplinkCapacity = 5,
  151. downlinkCapacity = 20,
  152. congestion = false,
  153. readBufferSize = 2,
  154. writeBufferSize = 2,
  155. type = 'none',
  156. seed = '',
  157. ) {
  158. super();
  159. this.mtu = mtu;
  160. this.tti = tti;
  161. this.upCap = uplinkCapacity;
  162. this.downCap = downlinkCapacity;
  163. this.congestion = congestion;
  164. this.readBuffer = readBufferSize;
  165. this.writeBuffer = writeBufferSize;
  166. this.type = type;
  167. this.seed = seed;
  168. }
  169. static fromJson(json = {}) {
  170. return new KcpStreamSettings(
  171. json.mtu,
  172. json.tti,
  173. json.uplinkCapacity,
  174. json.downlinkCapacity,
  175. json.congestion,
  176. json.readBufferSize,
  177. json.writeBufferSize,
  178. ObjectUtil.isEmpty(json.header) ? 'none' : json.header.type,
  179. json.seed,
  180. );
  181. }
  182. toJson() {
  183. return {
  184. mtu: this.mtu,
  185. tti: this.tti,
  186. uplinkCapacity: this.upCap,
  187. downlinkCapacity: this.downCap,
  188. congestion: this.congestion,
  189. readBufferSize: this.readBuffer,
  190. writeBufferSize: this.writeBuffer,
  191. header: {
  192. type: this.type,
  193. },
  194. seed: this.seed,
  195. };
  196. }
  197. }
  198. class WsStreamSettings extends CommonClass {
  199. constructor(
  200. path = '/',
  201. host = '',
  202. heartbeatPeriod = 0,
  203. ) {
  204. super();
  205. this.path = path;
  206. this.host = host;
  207. this.heartbeatPeriod = heartbeatPeriod;
  208. }
  209. static fromJson(json = {}) {
  210. return new WsStreamSettings(
  211. json.path,
  212. json.host,
  213. json.heartbeatPeriod,
  214. );
  215. }
  216. toJson() {
  217. return {
  218. path: this.path,
  219. host: this.host,
  220. heartbeatPeriod: this.heartbeatPeriod
  221. };
  222. }
  223. }
  224. class GrpcStreamSettings extends CommonClass {
  225. constructor(
  226. serviceName = "",
  227. authority = "",
  228. multiMode = false
  229. ) {
  230. super();
  231. this.serviceName = serviceName;
  232. this.authority = authority;
  233. this.multiMode = multiMode;
  234. }
  235. static fromJson(json = {}) {
  236. return new GrpcStreamSettings(json.serviceName, json.authority, json.multiMode);
  237. }
  238. toJson() {
  239. return {
  240. serviceName: this.serviceName,
  241. authority: this.authority,
  242. multiMode: this.multiMode
  243. }
  244. }
  245. }
  246. class HttpUpgradeStreamSettings extends CommonClass {
  247. constructor(path = '/', host = '') {
  248. super();
  249. this.path = path;
  250. this.host = host;
  251. }
  252. static fromJson(json = {}) {
  253. return new HttpUpgradeStreamSettings(
  254. json.path,
  255. json.host,
  256. );
  257. }
  258. toJson() {
  259. return {
  260. path: this.path,
  261. host: this.host,
  262. };
  263. }
  264. }
  265. class xHTTPStreamSettings extends CommonClass {
  266. constructor(
  267. path = '/',
  268. host = '',
  269. mode = '',
  270. noGRPCHeader = false,
  271. scMinPostsIntervalMs = "30",
  272. xmux = {
  273. maxConcurrency: "16-32",
  274. maxConnections: 0,
  275. cMaxReuseTimes: 0,
  276. hMaxRequestTimes: "600-900",
  277. hMaxReusableSecs: "1800-3000",
  278. hKeepAlivePeriod: 0,
  279. },
  280. ) {
  281. super();
  282. this.path = path;
  283. this.host = host;
  284. this.mode = mode;
  285. this.noGRPCHeader = noGRPCHeader;
  286. this.scMinPostsIntervalMs = scMinPostsIntervalMs;
  287. this.xmux = xmux;
  288. }
  289. static fromJson(json = {}) {
  290. return new xHTTPStreamSettings(
  291. json.path,
  292. json.host,
  293. json.mode,
  294. json.noGRPCHeader,
  295. json.scMinPostsIntervalMs,
  296. json.xmux
  297. );
  298. }
  299. toJson() {
  300. return {
  301. path: this.path,
  302. host: this.host,
  303. mode: this.mode,
  304. noGRPCHeader: this.noGRPCHeader,
  305. scMinPostsIntervalMs: this.scMinPostsIntervalMs,
  306. xmux: {
  307. maxConcurrency: this.xmux.maxConcurrency,
  308. maxConnections: this.xmux.maxConnections,
  309. cMaxReuseTimes: this.xmux.cMaxReuseTimes,
  310. hMaxRequestTimes: this.xmux.hMaxRequestTimes,
  311. hMaxReusableSecs: this.xmux.hMaxReusableSecs,
  312. hKeepAlivePeriod: this.xmux.hKeepAlivePeriod,
  313. },
  314. };
  315. }
  316. }
  317. class TlsStreamSettings extends CommonClass {
  318. constructor(
  319. serverName = '',
  320. alpn = [],
  321. fingerprint = '',
  322. allowInsecure = false,
  323. echConfigList = '',
  324. ) {
  325. super();
  326. this.serverName = serverName;
  327. this.alpn = alpn;
  328. this.fingerprint = fingerprint;
  329. this.allowInsecure = allowInsecure;
  330. this.echConfigList = echConfigList;
  331. }
  332. static fromJson(json = {}) {
  333. return new TlsStreamSettings(
  334. json.serverName,
  335. json.alpn,
  336. json.fingerprint,
  337. json.allowInsecure,
  338. json.echConfigList,
  339. );
  340. }
  341. toJson() {
  342. return {
  343. serverName: this.serverName,
  344. alpn: this.alpn,
  345. fingerprint: this.fingerprint,
  346. allowInsecure: this.allowInsecure,
  347. echConfigList: this.echConfigList
  348. };
  349. }
  350. }
  351. class RealityStreamSettings extends CommonClass {
  352. constructor(
  353. publicKey = '',
  354. fingerprint = '',
  355. serverName = '',
  356. shortId = '',
  357. spiderX = '',
  358. mldsa65Verify = ''
  359. ) {
  360. super();
  361. this.publicKey = publicKey;
  362. this.fingerprint = fingerprint;
  363. this.serverName = serverName;
  364. this.shortId = shortId
  365. this.spiderX = spiderX;
  366. this.mldsa65Verify = mldsa65Verify;
  367. }
  368. static fromJson(json = {}) {
  369. return new RealityStreamSettings(
  370. json.publicKey,
  371. json.fingerprint,
  372. json.serverName,
  373. json.shortId,
  374. json.spiderX,
  375. json.mldsa65Verify
  376. );
  377. }
  378. toJson() {
  379. return {
  380. publicKey: this.publicKey,
  381. fingerprint: this.fingerprint,
  382. serverName: this.serverName,
  383. shortId: this.shortId,
  384. spiderX: this.spiderX,
  385. mldsa65Verify: this.mldsa65Verify
  386. };
  387. }
  388. };
  389. class SockoptStreamSettings extends CommonClass {
  390. constructor(
  391. dialerProxy = "",
  392. tcpFastOpen = false,
  393. tcpKeepAliveInterval = 0,
  394. tcpMptcp = false,
  395. penetrate = false,
  396. addressPortStrategy = Address_Port_Strategy.NONE,
  397. ) {
  398. super();
  399. this.dialerProxy = dialerProxy;
  400. this.tcpFastOpen = tcpFastOpen;
  401. this.tcpKeepAliveInterval = tcpKeepAliveInterval;
  402. this.tcpMptcp = tcpMptcp;
  403. this.penetrate = penetrate;
  404. this.addressPortStrategy = addressPortStrategy;
  405. }
  406. static fromJson(json = {}) {
  407. if (Object.keys(json).length === 0) return undefined;
  408. return new SockoptStreamSettings(
  409. json.dialerProxy,
  410. json.tcpFastOpen,
  411. json.tcpKeepAliveInterval,
  412. json.tcpMptcp,
  413. json.penetrate,
  414. json.addressPortStrategy
  415. );
  416. }
  417. toJson() {
  418. return {
  419. dialerProxy: this.dialerProxy,
  420. tcpFastOpen: this.tcpFastOpen,
  421. tcpKeepAliveInterval: this.tcpKeepAliveInterval,
  422. tcpMptcp: this.tcpMptcp,
  423. penetrate: this.penetrate,
  424. addressPortStrategy: this.addressPortStrategy
  425. };
  426. }
  427. }
  428. class StreamSettings extends CommonClass {
  429. constructor(
  430. network = 'tcp',
  431. security = 'none',
  432. tlsSettings = new TlsStreamSettings(),
  433. realitySettings = new RealityStreamSettings(),
  434. tcpSettings = new TcpStreamSettings(),
  435. kcpSettings = new KcpStreamSettings(),
  436. wsSettings = new WsStreamSettings(),
  437. grpcSettings = new GrpcStreamSettings(),
  438. httpupgradeSettings = new HttpUpgradeStreamSettings(),
  439. xhttpSettings = new xHTTPStreamSettings(),
  440. sockopt = undefined,
  441. ) {
  442. super();
  443. this.network = network;
  444. this.security = security;
  445. this.tls = tlsSettings;
  446. this.reality = realitySettings;
  447. this.tcp = tcpSettings;
  448. this.kcp = kcpSettings;
  449. this.ws = wsSettings;
  450. this.grpc = grpcSettings;
  451. this.httpupgrade = httpupgradeSettings;
  452. this.xhttp = xhttpSettings;
  453. this.sockopt = sockopt;
  454. }
  455. get isTls() {
  456. return this.security === 'tls';
  457. }
  458. get isReality() {
  459. return this.security === "reality";
  460. }
  461. get sockoptSwitch() {
  462. return this.sockopt != undefined;
  463. }
  464. set sockoptSwitch(value) {
  465. this.sockopt = value ? new SockoptStreamSettings() : undefined;
  466. }
  467. static fromJson(json = {}) {
  468. return new StreamSettings(
  469. json.network,
  470. json.security,
  471. TlsStreamSettings.fromJson(json.tlsSettings),
  472. RealityStreamSettings.fromJson(json.realitySettings),
  473. TcpStreamSettings.fromJson(json.tcpSettings),
  474. KcpStreamSettings.fromJson(json.kcpSettings),
  475. WsStreamSettings.fromJson(json.wsSettings),
  476. GrpcStreamSettings.fromJson(json.grpcSettings),
  477. HttpUpgradeStreamSettings.fromJson(json.httpupgradeSettings),
  478. xHTTPStreamSettings.fromJson(json.xhttpSettings),
  479. SockoptStreamSettings.fromJson(json.sockopt),
  480. );
  481. }
  482. toJson() {
  483. const network = this.network;
  484. return {
  485. network: network,
  486. security: this.security,
  487. tlsSettings: this.security == 'tls' ? this.tls.toJson() : undefined,
  488. realitySettings: this.security == 'reality' ? this.reality.toJson() : undefined,
  489. tcpSettings: network === 'tcp' ? this.tcp.toJson() : undefined,
  490. kcpSettings: network === 'kcp' ? this.kcp.toJson() : undefined,
  491. wsSettings: network === 'ws' ? this.ws.toJson() : undefined,
  492. grpcSettings: network === 'grpc' ? this.grpc.toJson() : undefined,
  493. httpupgradeSettings: network === 'httpupgrade' ? this.httpupgrade.toJson() : undefined,
  494. xhttpSettings: network === 'xhttp' ? this.xhttp.toJson() : undefined,
  495. sockopt: this.sockopt != undefined ? this.sockopt.toJson() : undefined,
  496. };
  497. }
  498. }
  499. class Mux extends CommonClass {
  500. constructor(enabled = false, concurrency = 8, xudpConcurrency = 16, xudpProxyUDP443 = "reject") {
  501. super();
  502. this.enabled = enabled;
  503. this.concurrency = concurrency;
  504. this.xudpConcurrency = xudpConcurrency;
  505. this.xudpProxyUDP443 = xudpProxyUDP443;
  506. }
  507. static fromJson(json = {}) {
  508. if (Object.keys(json).length === 0) return undefined;
  509. return new Mux(
  510. json.enabled,
  511. json.concurrency,
  512. json.xudpConcurrency,
  513. json.xudpProxyUDP443,
  514. );
  515. }
  516. toJson() {
  517. return {
  518. enabled: this.enabled,
  519. concurrency: this.concurrency,
  520. xudpConcurrency: this.xudpConcurrency,
  521. xudpProxyUDP443: this.xudpProxyUDP443,
  522. };
  523. }
  524. }
  525. class Outbound extends CommonClass {
  526. constructor(
  527. tag = '',
  528. protocol = Protocols.VLESS,
  529. settings = null,
  530. streamSettings = new StreamSettings(),
  531. sendThrough,
  532. mux = new Mux(),
  533. ) {
  534. super();
  535. this.tag = tag;
  536. this._protocol = protocol;
  537. this.settings = settings == null ? Outbound.Settings.getSettings(protocol) : settings;
  538. this.stream = streamSettings;
  539. this.sendThrough = sendThrough;
  540. this.mux = mux;
  541. }
  542. get protocol() {
  543. return this._protocol;
  544. }
  545. set protocol(protocol) {
  546. this._protocol = protocol;
  547. this.settings = Outbound.Settings.getSettings(protocol);
  548. this.stream = new StreamSettings();
  549. }
  550. canEnableTls() {
  551. if (![Protocols.VMess, Protocols.VLESS, Protocols.Trojan, Protocols.Shadowsocks].includes(this.protocol)) return false;
  552. return ["tcp", "ws", "http", "grpc", "httpupgrade", "xhttp"].includes(this.stream.network);
  553. }
  554. //this is used for xtls-rprx-vision
  555. canEnableTlsFlow() {
  556. if ((this.stream.security != 'none') && (this.stream.network === "tcp")) {
  557. return this.protocol === Protocols.VLESS;
  558. }
  559. return false;
  560. }
  561. canEnableReality() {
  562. if (![Protocols.VLESS, Protocols.Trojan].includes(this.protocol)) return false;
  563. return ["tcp", "http", "grpc", "xhttp"].includes(this.stream.network);
  564. }
  565. canEnableStream() {
  566. return [Protocols.VMess, Protocols.VLESS, Protocols.Trojan, Protocols.Shadowsocks].includes(this.protocol);
  567. }
  568. canEnableMux() {
  569. // Disable Mux if flow is set
  570. if (this.settings.flow && this.settings.flow !== '') {
  571. this.mux.enabled = false;
  572. return false;
  573. }
  574. // Disable Mux if network is xhttp
  575. if (this.stream.network === 'xhttp') {
  576. this.mux.enabled = false;
  577. return false;
  578. }
  579. // Allow Mux only for these protocols
  580. return [
  581. Protocols.VMess,
  582. Protocols.VLESS,
  583. Protocols.Trojan,
  584. Protocols.Shadowsocks,
  585. Protocols.HTTP,
  586. Protocols.Socks
  587. ].includes(this.protocol);
  588. }
  589. hasServers() {
  590. return [Protocols.Trojan, Protocols.Shadowsocks, Protocols.Socks, Protocols.HTTP].includes(this.protocol);
  591. }
  592. hasAddressPort() {
  593. return [
  594. Protocols.DNS,
  595. Protocols.VMess,
  596. Protocols.VLESS,
  597. Protocols.Trojan,
  598. Protocols.Shadowsocks,
  599. Protocols.Socks,
  600. Protocols.HTTP
  601. ].includes(this.protocol);
  602. }
  603. hasUsername() {
  604. return [Protocols.Socks, Protocols.HTTP].includes(this.protocol);
  605. }
  606. static fromJson(json = {}) {
  607. return new Outbound(
  608. json.tag,
  609. json.protocol,
  610. Outbound.Settings.fromJson(json.protocol, json.settings),
  611. StreamSettings.fromJson(json.streamSettings),
  612. json.sendThrough,
  613. Mux.fromJson(json.mux),
  614. )
  615. }
  616. toJson() {
  617. var stream;
  618. if (this.canEnableStream()) {
  619. stream = this.stream.toJson();
  620. } else {
  621. if (this.stream?.sockopt)
  622. stream = { sockopt: this.stream.sockopt.toJson() };
  623. }
  624. // For VMess/VLESS, emit settings as a flat object
  625. let settingsOut = this.settings instanceof CommonClass ? this.settings.toJson() : this.settings;
  626. // Remove undefined/null keys
  627. if (settingsOut && typeof settingsOut === 'object') {
  628. Object.keys(settingsOut).forEach(k => {
  629. if (settingsOut[k] === undefined || settingsOut[k] === null) delete settingsOut[k];
  630. });
  631. }
  632. return {
  633. protocol: this.protocol,
  634. settings: settingsOut,
  635. // Only include tag, streamSettings, sendThrough, mux if present and not empty
  636. ...(this.tag ? { tag: this.tag } : {}),
  637. ...(stream ? { streamSettings: stream } : {}),
  638. ...(this.sendThrough ? { sendThrough: this.sendThrough } : {}),
  639. ...(this.mux?.enabled ? { mux: this.mux } : {}),
  640. };
  641. }
  642. static fromLink(link) {
  643. data = link.split('://');
  644. if (data.length != 2) return null;
  645. switch (data[0].toLowerCase()) {
  646. case Protocols.VMess:
  647. return this.fromVmessLink(JSON.parse(Base64.decode(data[1])));
  648. case Protocols.VLESS:
  649. case Protocols.Trojan:
  650. case 'ss':
  651. return this.fromParamLink(link);
  652. default:
  653. return null;
  654. }
  655. }
  656. static fromVmessLink(json = {}) {
  657. let stream = new StreamSettings(json.net, json.tls);
  658. let network = json.net;
  659. if (network === 'tcp') {
  660. stream.tcp = new TcpStreamSettings(
  661. json.type,
  662. json.host ?? '',
  663. json.path ?? '');
  664. } else if (network === 'kcp') {
  665. stream.kcp = new KcpStreamSettings();
  666. stream.type = json.type;
  667. stream.seed = json.path;
  668. } else if (network === 'ws') {
  669. stream.ws = new WsStreamSettings(json.path, json.host);
  670. } else if (network === 'grpc') {
  671. stream.grpc = new GrpcStreamSettings(json.path, json.authority, json.type == 'multi');
  672. } else if (network === 'httpupgrade') {
  673. stream.httpupgrade = new HttpUpgradeStreamSettings(json.path, json.host);
  674. } else if (network === 'xhttp') {
  675. stream.xhttp = new xHTTPStreamSettings(json.path, json.host, json.mode);
  676. }
  677. if (json.tls && json.tls == 'tls') {
  678. stream.tls = new TlsStreamSettings(
  679. json.sni,
  680. json.alpn ? json.alpn.split(',') : [],
  681. json.fp,
  682. json.allowInsecure);
  683. }
  684. const port = json.port * 1;
  685. return new Outbound(json.ps, Protocols.VMess, new Outbound.VmessSettings(json.add, port, json.id, json.scy), stream);
  686. }
  687. static fromParamLink(link) {
  688. const url = new URL(link);
  689. let type = url.searchParams.get('type') ?? 'tcp';
  690. let security = url.searchParams.get('security') ?? 'none';
  691. let stream = new StreamSettings(type, security);
  692. let headerType = url.searchParams.get('headerType') ?? undefined;
  693. let host = url.searchParams.get('host') ?? undefined;
  694. let path = url.searchParams.get('path') ?? undefined;
  695. let mode = url.searchParams.get('mode') ?? undefined;
  696. if (type === 'tcp' || type === 'none') {
  697. stream.tcp = new TcpStreamSettings(headerType ?? 'none', host, path);
  698. } else if (type === 'kcp') {
  699. stream.kcp = new KcpStreamSettings();
  700. stream.kcp.type = headerType ?? 'none';
  701. stream.kcp.seed = path;
  702. } else if (type === 'ws') {
  703. stream.ws = new WsStreamSettings(path, host);
  704. } else if (type === 'grpc') {
  705. stream.grpc = new GrpcStreamSettings(
  706. url.searchParams.get('serviceName') ?? '',
  707. url.searchParams.get('authority') ?? '',
  708. url.searchParams.get('mode') == 'multi');
  709. } else if (type === 'httpupgrade') {
  710. stream.httpupgrade = new HttpUpgradeStreamSettings(path, host);
  711. } else if (type === 'xhttp') {
  712. stream.xhttp = new xHTTPStreamSettings(path, host, mode);
  713. }
  714. if (security == 'tls') {
  715. let fp = url.searchParams.get('fp') ?? 'none';
  716. let alpn = url.searchParams.get('alpn');
  717. let allowInsecure = url.searchParams.get('allowInsecure');
  718. let sni = url.searchParams.get('sni') ?? '';
  719. let ech = url.searchParams.get('ech') ?? '';
  720. stream.tls = new TlsStreamSettings(sni, alpn ? alpn.split(',') : [], fp, allowInsecure == 1, ech);
  721. }
  722. if (security == 'reality') {
  723. let pbk = url.searchParams.get('pbk');
  724. let fp = url.searchParams.get('fp');
  725. let sni = url.searchParams.get('sni') ?? '';
  726. let sid = url.searchParams.get('sid') ?? '';
  727. let spx = url.searchParams.get('spx') ?? '';
  728. let pqv = url.searchParams.get('pqv') ?? '';
  729. stream.reality = new RealityStreamSettings(pbk, fp, sni, sid, spx, pqv);
  730. }
  731. const regex = /([^@]+):\/\/([^@]+)@(.+):(\d+)(.*)$/;
  732. const match = link.match(regex);
  733. if (!match) return null;
  734. let [, protocol, userData, address, port,] = match;
  735. port *= 1;
  736. if (protocol == 'ss') {
  737. protocol = 'shadowsocks';
  738. userData = atob(userData).split(':');
  739. }
  740. var settings;
  741. switch (protocol) {
  742. case Protocols.VLESS:
  743. settings = new Outbound.VLESSSettings(address, port, userData, url.searchParams.get('flow') ?? '', url.searchParams.get('encryption') ?? 'none');
  744. break;
  745. case Protocols.Trojan:
  746. settings = new Outbound.TrojanSettings(address, port, userData);
  747. break;
  748. case Protocols.Shadowsocks:
  749. let method = userData.splice(0, 1)[0];
  750. settings = new Outbound.ShadowsocksSettings(address, port, userData.join(":"), method, true);
  751. break;
  752. default:
  753. return null;
  754. }
  755. let remark = decodeURIComponent(url.hash);
  756. // Remove '#' from url.hash
  757. remark = remark.length > 0 ? remark.substring(1) : 'out-' + protocol + '-' + port;
  758. return new Outbound(remark, protocol, settings, stream);
  759. }
  760. }
  761. Outbound.Settings = class extends CommonClass {
  762. constructor(protocol) {
  763. super();
  764. this.protocol = protocol;
  765. }
  766. static getSettings(protocol) {
  767. switch (protocol) {
  768. case Protocols.Freedom: return new Outbound.FreedomSettings();
  769. case Protocols.Blackhole: return new Outbound.BlackholeSettings();
  770. case Protocols.DNS: return new Outbound.DNSSettings();
  771. case Protocols.VMess: return new Outbound.VmessSettings();
  772. case Protocols.VLESS: return new Outbound.VLESSSettings();
  773. case Protocols.Trojan: return new Outbound.TrojanSettings();
  774. case Protocols.Shadowsocks: return new Outbound.ShadowsocksSettings();
  775. case Protocols.Socks: return new Outbound.SocksSettings();
  776. case Protocols.HTTP: return new Outbound.HttpSettings();
  777. case Protocols.Wireguard: return new Outbound.WireguardSettings();
  778. default: return null;
  779. }
  780. }
  781. static fromJson(protocol, json) {
  782. switch (protocol) {
  783. case Protocols.Freedom: return Outbound.FreedomSettings.fromJson(json);
  784. case Protocols.Blackhole: return Outbound.BlackholeSettings.fromJson(json);
  785. case Protocols.DNS: return Outbound.DNSSettings.fromJson(json);
  786. case Protocols.VMess: return Outbound.VmessSettings.fromJson(json);
  787. case Protocols.VLESS: return Outbound.VLESSSettings.fromJson(json);
  788. case Protocols.Trojan: return Outbound.TrojanSettings.fromJson(json);
  789. case Protocols.Shadowsocks: return Outbound.ShadowsocksSettings.fromJson(json);
  790. case Protocols.Socks: return Outbound.SocksSettings.fromJson(json);
  791. case Protocols.HTTP: return Outbound.HttpSettings.fromJson(json);
  792. case Protocols.Wireguard: return Outbound.WireguardSettings.fromJson(json);
  793. default: return null;
  794. }
  795. }
  796. toJson() {
  797. return {};
  798. }
  799. };
  800. Outbound.FreedomSettings = class extends CommonClass {
  801. constructor(
  802. domainStrategy = '',
  803. redirect = '',
  804. fragment = {},
  805. noises = []
  806. ) {
  807. super();
  808. this.domainStrategy = domainStrategy;
  809. this.redirect = redirect;
  810. this.fragment = fragment;
  811. this.noises = noises;
  812. }
  813. addNoise() {
  814. this.noises.push(new Outbound.FreedomSettings.Noise());
  815. }
  816. delNoise(index) {
  817. this.noises.splice(index, 1);
  818. }
  819. static fromJson(json = {}) {
  820. return new Outbound.FreedomSettings(
  821. json.domainStrategy,
  822. json.redirect,
  823. json.fragment ? Outbound.FreedomSettings.Fragment.fromJson(json.fragment) : undefined,
  824. json.noises ? json.noises.map(noise => Outbound.FreedomSettings.Noise.fromJson(noise)) : undefined,
  825. );
  826. }
  827. toJson() {
  828. return {
  829. domainStrategy: ObjectUtil.isEmpty(this.domainStrategy) ? undefined : this.domainStrategy,
  830. redirect: ObjectUtil.isEmpty(this.redirect) ? undefined : this.redirect,
  831. fragment: Object.keys(this.fragment).length === 0 ? undefined : this.fragment,
  832. noises: this.noises.length === 0 ? undefined : Outbound.FreedomSettings.Noise.toJsonArray(this.noises),
  833. };
  834. }
  835. };
  836. Outbound.FreedomSettings.Fragment = class extends CommonClass {
  837. constructor(
  838. packets = '1-3',
  839. length = '',
  840. interval = '',
  841. maxSplit = ''
  842. ) {
  843. super();
  844. this.packets = packets;
  845. this.length = length;
  846. this.interval = interval;
  847. this.maxSplit = maxSplit;
  848. }
  849. static fromJson(json = {}) {
  850. return new Outbound.FreedomSettings.Fragment(
  851. json.packets,
  852. json.length,
  853. json.interval,
  854. json.maxSplit
  855. );
  856. }
  857. };
  858. Outbound.FreedomSettings.Noise = class extends CommonClass {
  859. constructor(
  860. type = 'rand',
  861. packet = '10-20',
  862. delay = '10-16',
  863. applyTo = 'ip'
  864. ) {
  865. super();
  866. this.type = type;
  867. this.packet = packet;
  868. this.delay = delay;
  869. this.applyTo = applyTo;
  870. }
  871. static fromJson(json = {}) {
  872. return new Outbound.FreedomSettings.Noise(
  873. json.type,
  874. json.packet,
  875. json.delay,
  876. json.applyTo
  877. );
  878. }
  879. toJson() {
  880. return {
  881. type: this.type,
  882. packet: this.packet,
  883. delay: this.delay,
  884. applyTo: this.applyTo
  885. };
  886. }
  887. };
  888. Outbound.BlackholeSettings = class extends CommonClass {
  889. constructor(type) {
  890. super();
  891. this.type = type;
  892. }
  893. static fromJson(json = {}) {
  894. return new Outbound.BlackholeSettings(
  895. json.response ? json.response.type : undefined,
  896. );
  897. }
  898. toJson() {
  899. return {
  900. response: ObjectUtil.isEmpty(this.type) ? undefined : { type: this.type },
  901. };
  902. }
  903. };
  904. Outbound.DNSSettings = class extends CommonClass {
  905. constructor(
  906. network = 'udp',
  907. address = '',
  908. port = 53,
  909. nonIPQuery = 'reject',
  910. blockTypes = []
  911. ) {
  912. super();
  913. this.network = network;
  914. this.address = address;
  915. this.port = port;
  916. this.nonIPQuery = nonIPQuery;
  917. this.blockTypes = blockTypes;
  918. }
  919. static fromJson(json = {}) {
  920. return new Outbound.DNSSettings(
  921. json.network,
  922. json.address,
  923. json.port,
  924. json.nonIPQuery,
  925. json.blockTypes,
  926. );
  927. }
  928. };
  929. Outbound.VmessSettings = class extends CommonClass {
  930. constructor(address, port, id, security) {
  931. super();
  932. this.address = address;
  933. this.port = port;
  934. this.id = id;
  935. this.security = security;
  936. }
  937. static fromJson(json = {}) {
  938. if (ObjectUtil.isEmpty(json.address) || ObjectUtil.isEmpty(json.port)) return new Outbound.VmessSettings();
  939. return new Outbound.VmessSettings(
  940. json.address,
  941. json.port,
  942. json.id,
  943. json.security,
  944. );
  945. }
  946. toJson() {
  947. return {
  948. address: this.address,
  949. port: this.port,
  950. id: this.id,
  951. security: this.security,
  952. };
  953. }
  954. };
  955. Outbound.VLESSSettings = class extends CommonClass {
  956. constructor(address, port, id, flow, encryption) {
  957. super();
  958. this.address = address;
  959. this.port = port;
  960. this.id = id;
  961. this.flow = flow;
  962. this.encryption = encryption;
  963. }
  964. static fromJson(json = {}) {
  965. if (ObjectUtil.isEmpty(json.address) || ObjectUtil.isEmpty(json.port)) return new Outbound.VLESSSettings();
  966. return new Outbound.VLESSSettings(
  967. json.address,
  968. json.port,
  969. json.id,
  970. json.flow,
  971. json.encryption
  972. );
  973. }
  974. toJson() {
  975. return {
  976. address: this.address,
  977. port: this.port,
  978. id: this.id,
  979. flow: this.flow,
  980. encryption: this.encryption,
  981. };
  982. }
  983. };
  984. Outbound.TrojanSettings = class extends CommonClass {
  985. constructor(address, port, password) {
  986. super();
  987. this.address = address;
  988. this.port = port;
  989. this.password = password;
  990. }
  991. static fromJson(json = {}) {
  992. if (ObjectUtil.isArrEmpty(json.servers)) return new Outbound.TrojanSettings();
  993. return new Outbound.TrojanSettings(
  994. json.servers[0].address,
  995. json.servers[0].port,
  996. json.servers[0].password,
  997. );
  998. }
  999. toJson() {
  1000. return {
  1001. servers: [{
  1002. address: this.address,
  1003. port: this.port,
  1004. password: this.password,
  1005. }],
  1006. };
  1007. }
  1008. };
  1009. Outbound.ShadowsocksSettings = class extends CommonClass {
  1010. constructor(address, port, password, method, uot, UoTVersion) {
  1011. super();
  1012. this.address = address;
  1013. this.port = port;
  1014. this.password = password;
  1015. this.method = method;
  1016. this.uot = uot;
  1017. this.UoTVersion = UoTVersion;
  1018. }
  1019. static fromJson(json = {}) {
  1020. let servers = json.servers;
  1021. if (ObjectUtil.isArrEmpty(servers)) servers = [{}];
  1022. return new Outbound.ShadowsocksSettings(
  1023. servers[0].address,
  1024. servers[0].port,
  1025. servers[0].password,
  1026. servers[0].method,
  1027. servers[0].uot,
  1028. servers[0].UoTVersion,
  1029. );
  1030. }
  1031. toJson() {
  1032. return {
  1033. servers: [{
  1034. address: this.address,
  1035. port: this.port,
  1036. password: this.password,
  1037. method: this.method,
  1038. uot: this.uot,
  1039. UoTVersion: this.UoTVersion,
  1040. }],
  1041. };
  1042. }
  1043. };
  1044. Outbound.SocksSettings = class extends CommonClass {
  1045. constructor(address, port, user, pass) {
  1046. super();
  1047. this.address = address;
  1048. this.port = port;
  1049. this.user = user;
  1050. this.pass = pass;
  1051. }
  1052. static fromJson(json = {}) {
  1053. let servers = json.servers;
  1054. if (ObjectUtil.isArrEmpty(servers)) servers = [{ users: [{}] }];
  1055. return new Outbound.SocksSettings(
  1056. servers[0].address,
  1057. servers[0].port,
  1058. ObjectUtil.isArrEmpty(servers[0].users) ? '' : servers[0].users[0].user,
  1059. ObjectUtil.isArrEmpty(servers[0].users) ? '' : servers[0].users[0].pass,
  1060. );
  1061. }
  1062. toJson() {
  1063. return {
  1064. servers: [{
  1065. address: this.address,
  1066. port: this.port,
  1067. users: ObjectUtil.isEmpty(this.user) ? [] : [{ user: this.user, pass: this.pass }],
  1068. }],
  1069. };
  1070. }
  1071. };
  1072. Outbound.HttpSettings = class extends CommonClass {
  1073. constructor(address, port, user, pass) {
  1074. super();
  1075. this.address = address;
  1076. this.port = port;
  1077. this.user = user;
  1078. this.pass = pass;
  1079. }
  1080. static fromJson(json = {}) {
  1081. let servers = json.servers;
  1082. if (ObjectUtil.isArrEmpty(servers)) servers = [{ users: [{}] }];
  1083. return new Outbound.HttpSettings(
  1084. servers[0].address,
  1085. servers[0].port,
  1086. ObjectUtil.isArrEmpty(servers[0].users) ? '' : servers[0].users[0].user,
  1087. ObjectUtil.isArrEmpty(servers[0].users) ? '' : servers[0].users[0].pass,
  1088. );
  1089. }
  1090. toJson() {
  1091. return {
  1092. servers: [{
  1093. address: this.address,
  1094. port: this.port,
  1095. users: ObjectUtil.isEmpty(this.user) ? [] : [{ user: this.user, pass: this.pass }],
  1096. }],
  1097. };
  1098. }
  1099. };
  1100. Outbound.WireguardSettings = class extends CommonClass {
  1101. constructor(
  1102. mtu = 1420,
  1103. secretKey = '',
  1104. address = [''],
  1105. workers = 2,
  1106. domainStrategy = '',
  1107. reserved = '',
  1108. peers = [new Outbound.WireguardSettings.Peer()],
  1109. noKernelTun = false,
  1110. ) {
  1111. super();
  1112. this.mtu = mtu;
  1113. this.secretKey = secretKey;
  1114. this.pubKey = secretKey.length > 0 ? Wireguard.generateKeypair(secretKey).publicKey : '';
  1115. this.address = Array.isArray(address) ? address.join(',') : address;
  1116. this.workers = workers;
  1117. this.domainStrategy = domainStrategy;
  1118. this.reserved = Array.isArray(reserved) ? reserved.join(',') : reserved;
  1119. this.peers = peers;
  1120. this.noKernelTun = noKernelTun;
  1121. }
  1122. addPeer() {
  1123. this.peers.push(new Outbound.WireguardSettings.Peer());
  1124. }
  1125. delPeer(index) {
  1126. this.peers.splice(index, 1);
  1127. }
  1128. static fromJson(json = {}) {
  1129. return new Outbound.WireguardSettings(
  1130. json.mtu,
  1131. json.secretKey,
  1132. json.address,
  1133. json.workers,
  1134. json.domainStrategy,
  1135. json.reserved,
  1136. json.peers.map(peer => Outbound.WireguardSettings.Peer.fromJson(peer)),
  1137. json.noKernelTun,
  1138. );
  1139. }
  1140. toJson() {
  1141. return {
  1142. mtu: this.mtu ?? undefined,
  1143. secretKey: this.secretKey,
  1144. address: this.address ? this.address.split(",") : [],
  1145. workers: this.workers ?? undefined,
  1146. domainStrategy: WireguardDomainStrategy.includes(this.domainStrategy) ? this.domainStrategy : undefined,
  1147. reserved: this.reserved ? this.reserved.split(",").map(Number) : undefined,
  1148. peers: Outbound.WireguardSettings.Peer.toJsonArray(this.peers),
  1149. noKernelTun: this.noKernelTun,
  1150. };
  1151. }
  1152. };
  1153. Outbound.WireguardSettings.Peer = class extends CommonClass {
  1154. constructor(
  1155. publicKey = '',
  1156. psk = '',
  1157. allowedIPs = ['0.0.0.0/0', '::/0'],
  1158. endpoint = '',
  1159. keepAlive = 0
  1160. ) {
  1161. super();
  1162. this.publicKey = publicKey;
  1163. this.psk = psk;
  1164. this.allowedIPs = allowedIPs;
  1165. this.endpoint = endpoint;
  1166. this.keepAlive = keepAlive;
  1167. }
  1168. static fromJson(json = {}) {
  1169. return new Outbound.WireguardSettings.Peer(
  1170. json.publicKey,
  1171. json.preSharedKey,
  1172. json.allowedIPs,
  1173. json.endpoint,
  1174. json.keepAlive
  1175. );
  1176. }
  1177. toJson() {
  1178. return {
  1179. publicKey: this.publicKey,
  1180. preSharedKey: this.psk.length > 0 ? this.psk : undefined,
  1181. allowedIPs: this.allowedIPs ? this.allowedIPs : undefined,
  1182. endpoint: this.endpoint,
  1183. keepAlive: this.keepAlive ?? undefined,
  1184. };
  1185. }
  1186. };