outbound.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  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. trustedXForwardedFor = [],
  398. ) {
  399. super();
  400. this.dialerProxy = dialerProxy;
  401. this.tcpFastOpen = tcpFastOpen;
  402. this.tcpKeepAliveInterval = tcpKeepAliveInterval;
  403. this.tcpMptcp = tcpMptcp;
  404. this.penetrate = penetrate;
  405. this.addressPortStrategy = addressPortStrategy;
  406. this.trustedXForwardedFor = trustedXForwardedFor;
  407. }
  408. static fromJson(json = {}) {
  409. if (Object.keys(json).length === 0) return undefined;
  410. return new SockoptStreamSettings(
  411. json.dialerProxy,
  412. json.tcpFastOpen,
  413. json.tcpKeepAliveInterval,
  414. json.tcpMptcp,
  415. json.penetrate,
  416. json.addressPortStrategy,
  417. json.trustedXForwardedFor || []
  418. );
  419. }
  420. toJson() {
  421. const result = {
  422. dialerProxy: this.dialerProxy,
  423. tcpFastOpen: this.tcpFastOpen,
  424. tcpKeepAliveInterval: this.tcpKeepAliveInterval,
  425. tcpMptcp: this.tcpMptcp,
  426. penetrate: this.penetrate,
  427. addressPortStrategy: this.addressPortStrategy
  428. };
  429. if (this.trustedXForwardedFor && this.trustedXForwardedFor.length > 0) {
  430. result.trustedXForwardedFor = this.trustedXForwardedFor;
  431. }
  432. return result;
  433. }
  434. }
  435. class StreamSettings extends CommonClass {
  436. constructor(
  437. network = 'tcp',
  438. security = 'none',
  439. tlsSettings = new TlsStreamSettings(),
  440. realitySettings = new RealityStreamSettings(),
  441. tcpSettings = new TcpStreamSettings(),
  442. kcpSettings = new KcpStreamSettings(),
  443. wsSettings = new WsStreamSettings(),
  444. grpcSettings = new GrpcStreamSettings(),
  445. httpupgradeSettings = new HttpUpgradeStreamSettings(),
  446. xhttpSettings = new xHTTPStreamSettings(),
  447. sockopt = undefined,
  448. ) {
  449. super();
  450. this.network = network;
  451. this.security = security;
  452. this.tls = tlsSettings;
  453. this.reality = realitySettings;
  454. this.tcp = tcpSettings;
  455. this.kcp = kcpSettings;
  456. this.ws = wsSettings;
  457. this.grpc = grpcSettings;
  458. this.httpupgrade = httpupgradeSettings;
  459. this.xhttp = xhttpSettings;
  460. this.sockopt = sockopt;
  461. }
  462. get isTls() {
  463. return this.security === 'tls';
  464. }
  465. get isReality() {
  466. return this.security === "reality";
  467. }
  468. get sockoptSwitch() {
  469. return this.sockopt != undefined;
  470. }
  471. set sockoptSwitch(value) {
  472. this.sockopt = value ? new SockoptStreamSettings() : undefined;
  473. }
  474. static fromJson(json = {}) {
  475. return new StreamSettings(
  476. json.network,
  477. json.security,
  478. TlsStreamSettings.fromJson(json.tlsSettings),
  479. RealityStreamSettings.fromJson(json.realitySettings),
  480. TcpStreamSettings.fromJson(json.tcpSettings),
  481. KcpStreamSettings.fromJson(json.kcpSettings),
  482. WsStreamSettings.fromJson(json.wsSettings),
  483. GrpcStreamSettings.fromJson(json.grpcSettings),
  484. HttpUpgradeStreamSettings.fromJson(json.httpupgradeSettings),
  485. xHTTPStreamSettings.fromJson(json.xhttpSettings),
  486. SockoptStreamSettings.fromJson(json.sockopt),
  487. );
  488. }
  489. toJson() {
  490. const network = this.network;
  491. return {
  492. network: network,
  493. security: this.security,
  494. tlsSettings: this.security == 'tls' ? this.tls.toJson() : undefined,
  495. realitySettings: this.security == 'reality' ? this.reality.toJson() : undefined,
  496. tcpSettings: network === 'tcp' ? this.tcp.toJson() : undefined,
  497. kcpSettings: network === 'kcp' ? this.kcp.toJson() : undefined,
  498. wsSettings: network === 'ws' ? this.ws.toJson() : undefined,
  499. grpcSettings: network === 'grpc' ? this.grpc.toJson() : undefined,
  500. httpupgradeSettings: network === 'httpupgrade' ? this.httpupgrade.toJson() : undefined,
  501. xhttpSettings: network === 'xhttp' ? this.xhttp.toJson() : undefined,
  502. sockopt: this.sockopt != undefined ? this.sockopt.toJson() : undefined,
  503. };
  504. }
  505. }
  506. class Mux extends CommonClass {
  507. constructor(enabled = false, concurrency = 8, xudpConcurrency = 16, xudpProxyUDP443 = "reject") {
  508. super();
  509. this.enabled = enabled;
  510. this.concurrency = concurrency;
  511. this.xudpConcurrency = xudpConcurrency;
  512. this.xudpProxyUDP443 = xudpProxyUDP443;
  513. }
  514. static fromJson(json = {}) {
  515. if (Object.keys(json).length === 0) return undefined;
  516. return new Mux(
  517. json.enabled,
  518. json.concurrency,
  519. json.xudpConcurrency,
  520. json.xudpProxyUDP443,
  521. );
  522. }
  523. toJson() {
  524. return {
  525. enabled: this.enabled,
  526. concurrency: this.concurrency,
  527. xudpConcurrency: this.xudpConcurrency,
  528. xudpProxyUDP443: this.xudpProxyUDP443,
  529. };
  530. }
  531. }
  532. class Outbound extends CommonClass {
  533. constructor(
  534. tag = '',
  535. protocol = Protocols.VLESS,
  536. settings = null,
  537. streamSettings = new StreamSettings(),
  538. sendThrough,
  539. mux = new Mux(),
  540. ) {
  541. super();
  542. this.tag = tag;
  543. this._protocol = protocol;
  544. this.settings = settings == null ? Outbound.Settings.getSettings(protocol) : settings;
  545. this.stream = streamSettings;
  546. this.sendThrough = sendThrough;
  547. this.mux = mux;
  548. }
  549. get protocol() {
  550. return this._protocol;
  551. }
  552. set protocol(protocol) {
  553. this._protocol = protocol;
  554. this.settings = Outbound.Settings.getSettings(protocol);
  555. this.stream = new StreamSettings();
  556. }
  557. canEnableTls() {
  558. if (![Protocols.VMess, Protocols.VLESS, Protocols.Trojan, Protocols.Shadowsocks].includes(this.protocol)) return false;
  559. return ["tcp", "ws", "http", "grpc", "httpupgrade", "xhttp"].includes(this.stream.network);
  560. }
  561. //this is used for xtls-rprx-vision
  562. canEnableTlsFlow() {
  563. if ((this.stream.security != 'none') && (this.stream.network === "tcp")) {
  564. return this.protocol === Protocols.VLESS;
  565. }
  566. return false;
  567. }
  568. canEnableReality() {
  569. if (![Protocols.VLESS, Protocols.Trojan].includes(this.protocol)) return false;
  570. return ["tcp", "http", "grpc", "xhttp"].includes(this.stream.network);
  571. }
  572. canEnableStream() {
  573. return [Protocols.VMess, Protocols.VLESS, Protocols.Trojan, Protocols.Shadowsocks].includes(this.protocol);
  574. }
  575. canEnableMux() {
  576. // Disable Mux if flow is set
  577. if (this.settings.flow && this.settings.flow !== '') {
  578. this.mux.enabled = false;
  579. return false;
  580. }
  581. // Disable Mux if network is xhttp
  582. if (this.stream.network === 'xhttp') {
  583. this.mux.enabled = false;
  584. return false;
  585. }
  586. // Allow Mux only for these protocols
  587. return [
  588. Protocols.VMess,
  589. Protocols.VLESS,
  590. Protocols.Trojan,
  591. Protocols.Shadowsocks,
  592. Protocols.HTTP,
  593. Protocols.Socks
  594. ].includes(this.protocol);
  595. }
  596. hasServers() {
  597. return [Protocols.Trojan, Protocols.Shadowsocks, Protocols.Socks, Protocols.HTTP].includes(this.protocol);
  598. }
  599. hasAddressPort() {
  600. return [
  601. Protocols.DNS,
  602. Protocols.VMess,
  603. Protocols.VLESS,
  604. Protocols.Trojan,
  605. Protocols.Shadowsocks,
  606. Protocols.Socks,
  607. Protocols.HTTP
  608. ].includes(this.protocol);
  609. }
  610. hasUsername() {
  611. return [Protocols.Socks, Protocols.HTTP].includes(this.protocol);
  612. }
  613. static fromJson(json = {}) {
  614. return new Outbound(
  615. json.tag,
  616. json.protocol,
  617. Outbound.Settings.fromJson(json.protocol, json.settings),
  618. StreamSettings.fromJson(json.streamSettings),
  619. json.sendThrough,
  620. Mux.fromJson(json.mux),
  621. )
  622. }
  623. toJson() {
  624. var stream;
  625. if (this.canEnableStream()) {
  626. stream = this.stream.toJson();
  627. } else {
  628. if (this.stream?.sockopt)
  629. stream = { sockopt: this.stream.sockopt.toJson() };
  630. }
  631. let settingsOut = this.settings instanceof CommonClass ? this.settings.toJson() : this.settings;
  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.isArrEmpty(json.vnext)) {
  939. const v = json.vnext[0] || {};
  940. const u = ObjectUtil.isArrEmpty(v.users) ? {} : v.users[0];
  941. return new Outbound.VmessSettings(
  942. v.address,
  943. v.port,
  944. u.id,
  945. u.security,
  946. );
  947. }
  948. }
  949. toJson() {
  950. return {
  951. vnext: [{
  952. address: this.address,
  953. port: this.port,
  954. users: [{
  955. id: this.id,
  956. security: this.security
  957. }]
  958. }]
  959. };
  960. }
  961. };
  962. Outbound.VLESSSettings = class extends CommonClass {
  963. constructor(address, port, id, flow, encryption, testpre = 0, testseed = [900, 500, 900, 256]) {
  964. super();
  965. this.address = address;
  966. this.port = port;
  967. this.id = id;
  968. this.flow = flow;
  969. this.encryption = encryption;
  970. this.testpre = testpre;
  971. this.testseed = testseed;
  972. }
  973. static fromJson(json = {}) {
  974. if (ObjectUtil.isEmpty(json.address) || ObjectUtil.isEmpty(json.port)) return new Outbound.VLESSSettings();
  975. return new Outbound.VLESSSettings(
  976. json.address,
  977. json.port,
  978. json.id,
  979. json.flow,
  980. json.encryption,
  981. json.testpre || 0,
  982. json.testseed && json.testseed.length >= 4 ? json.testseed : [900, 500, 900, 256]
  983. );
  984. }
  985. toJson() {
  986. const result = {
  987. address: this.address,
  988. port: this.port,
  989. id: this.id,
  990. flow: this.flow,
  991. encryption: this.encryption,
  992. };
  993. if (this.testpre > 0) {
  994. result.testpre = this.testpre;
  995. }
  996. if (this.testseed && this.testseed.length >= 4) {
  997. result.testseed = this.testseed;
  998. }
  999. return result;
  1000. }
  1001. };
  1002. Outbound.TrojanSettings = class extends CommonClass {
  1003. constructor(address, port, password) {
  1004. super();
  1005. this.address = address;
  1006. this.port = port;
  1007. this.password = password;
  1008. }
  1009. static fromJson(json = {}) {
  1010. if (ObjectUtil.isArrEmpty(json.servers)) return new Outbound.TrojanSettings();
  1011. return new Outbound.TrojanSettings(
  1012. json.servers[0].address,
  1013. json.servers[0].port,
  1014. json.servers[0].password,
  1015. );
  1016. }
  1017. toJson() {
  1018. return {
  1019. servers: [{
  1020. address: this.address,
  1021. port: this.port,
  1022. password: this.password,
  1023. }],
  1024. };
  1025. }
  1026. };
  1027. Outbound.ShadowsocksSettings = class extends CommonClass {
  1028. constructor(address, port, password, method, uot, UoTVersion) {
  1029. super();
  1030. this.address = address;
  1031. this.port = port;
  1032. this.password = password;
  1033. this.method = method;
  1034. this.uot = uot;
  1035. this.UoTVersion = UoTVersion;
  1036. }
  1037. static fromJson(json = {}) {
  1038. let servers = json.servers;
  1039. if (ObjectUtil.isArrEmpty(servers)) servers = [{}];
  1040. return new Outbound.ShadowsocksSettings(
  1041. servers[0].address,
  1042. servers[0].port,
  1043. servers[0].password,
  1044. servers[0].method,
  1045. servers[0].uot,
  1046. servers[0].UoTVersion,
  1047. );
  1048. }
  1049. toJson() {
  1050. return {
  1051. servers: [{
  1052. address: this.address,
  1053. port: this.port,
  1054. password: this.password,
  1055. method: this.method,
  1056. uot: this.uot,
  1057. UoTVersion: this.UoTVersion,
  1058. }],
  1059. };
  1060. }
  1061. };
  1062. Outbound.SocksSettings = class extends CommonClass {
  1063. constructor(address, port, user, pass) {
  1064. super();
  1065. this.address = address;
  1066. this.port = port;
  1067. this.user = user;
  1068. this.pass = pass;
  1069. }
  1070. static fromJson(json = {}) {
  1071. let servers = json.servers;
  1072. if (ObjectUtil.isArrEmpty(servers)) servers = [{ users: [{}] }];
  1073. return new Outbound.SocksSettings(
  1074. servers[0].address,
  1075. servers[0].port,
  1076. ObjectUtil.isArrEmpty(servers[0].users) ? '' : servers[0].users[0].user,
  1077. ObjectUtil.isArrEmpty(servers[0].users) ? '' : servers[0].users[0].pass,
  1078. );
  1079. }
  1080. toJson() {
  1081. return {
  1082. servers: [{
  1083. address: this.address,
  1084. port: this.port,
  1085. users: ObjectUtil.isEmpty(this.user) ? [] : [{ user: this.user, pass: this.pass }],
  1086. }],
  1087. };
  1088. }
  1089. };
  1090. Outbound.HttpSettings = class extends CommonClass {
  1091. constructor(address, port, user, pass) {
  1092. super();
  1093. this.address = address;
  1094. this.port = port;
  1095. this.user = user;
  1096. this.pass = pass;
  1097. }
  1098. static fromJson(json = {}) {
  1099. let servers = json.servers;
  1100. if (ObjectUtil.isArrEmpty(servers)) servers = [{ users: [{}] }];
  1101. return new Outbound.HttpSettings(
  1102. servers[0].address,
  1103. servers[0].port,
  1104. ObjectUtil.isArrEmpty(servers[0].users) ? '' : servers[0].users[0].user,
  1105. ObjectUtil.isArrEmpty(servers[0].users) ? '' : servers[0].users[0].pass,
  1106. );
  1107. }
  1108. toJson() {
  1109. return {
  1110. servers: [{
  1111. address: this.address,
  1112. port: this.port,
  1113. users: ObjectUtil.isEmpty(this.user) ? [] : [{ user: this.user, pass: this.pass }],
  1114. }],
  1115. };
  1116. }
  1117. };
  1118. Outbound.WireguardSettings = class extends CommonClass {
  1119. constructor(
  1120. mtu = 1420,
  1121. secretKey = '',
  1122. address = [''],
  1123. workers = 2,
  1124. domainStrategy = '',
  1125. reserved = '',
  1126. peers = [new Outbound.WireguardSettings.Peer()],
  1127. noKernelTun = false,
  1128. ) {
  1129. super();
  1130. this.mtu = mtu;
  1131. this.secretKey = secretKey;
  1132. this.pubKey = secretKey.length > 0 ? Wireguard.generateKeypair(secretKey).publicKey : '';
  1133. this.address = Array.isArray(address) ? address.join(',') : address;
  1134. this.workers = workers;
  1135. this.domainStrategy = domainStrategy;
  1136. this.reserved = Array.isArray(reserved) ? reserved.join(',') : reserved;
  1137. this.peers = peers;
  1138. this.noKernelTun = noKernelTun;
  1139. }
  1140. addPeer() {
  1141. this.peers.push(new Outbound.WireguardSettings.Peer());
  1142. }
  1143. delPeer(index) {
  1144. this.peers.splice(index, 1);
  1145. }
  1146. static fromJson(json = {}) {
  1147. return new Outbound.WireguardSettings(
  1148. json.mtu,
  1149. json.secretKey,
  1150. json.address,
  1151. json.workers,
  1152. json.domainStrategy,
  1153. json.reserved,
  1154. json.peers.map(peer => Outbound.WireguardSettings.Peer.fromJson(peer)),
  1155. json.noKernelTun,
  1156. );
  1157. }
  1158. toJson() {
  1159. return {
  1160. mtu: this.mtu ?? undefined,
  1161. secretKey: this.secretKey,
  1162. address: this.address ? this.address.split(",") : [],
  1163. workers: this.workers ?? undefined,
  1164. domainStrategy: WireguardDomainStrategy.includes(this.domainStrategy) ? this.domainStrategy : undefined,
  1165. reserved: this.reserved ? this.reserved.split(",").map(Number) : undefined,
  1166. peers: Outbound.WireguardSettings.Peer.toJsonArray(this.peers),
  1167. noKernelTun: this.noKernelTun,
  1168. };
  1169. }
  1170. };
  1171. Outbound.WireguardSettings.Peer = class extends CommonClass {
  1172. constructor(
  1173. publicKey = '',
  1174. psk = '',
  1175. allowedIPs = ['0.0.0.0/0', '::/0'],
  1176. endpoint = '',
  1177. keepAlive = 0
  1178. ) {
  1179. super();
  1180. this.publicKey = publicKey;
  1181. this.psk = psk;
  1182. this.allowedIPs = allowedIPs;
  1183. this.endpoint = endpoint;
  1184. this.keepAlive = keepAlive;
  1185. }
  1186. static fromJson(json = {}) {
  1187. return new Outbound.WireguardSettings.Peer(
  1188. json.publicKey,
  1189. json.preSharedKey,
  1190. json.allowedIPs,
  1191. json.endpoint,
  1192. json.keepAlive
  1193. );
  1194. }
  1195. toJson() {
  1196. return {
  1197. publicKey: this.publicKey,
  1198. preSharedKey: this.psk.length > 0 ? this.psk : undefined,
  1199. allowedIPs: this.allowedIPs ? this.allowedIPs : undefined,
  1200. endpoint: this.endpoint,
  1201. keepAlive: this.keepAlive ?? undefined,
  1202. };
  1203. }
  1204. };