surge.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import { appendSetElementsToArray } from 'foxts/append-set-elements-to-array';
  2. import { BaseWriteStrategy } from './base';
  3. import { appendArrayInPlace } from 'foxts/append-array-in-place';
  4. import { noop } from 'foxts/noop';
  5. import { isProbablyIpv4 } from 'foxts/is-probably-ip';
  6. import picocolors from 'picocolors';
  7. import { normalizeDomain } from '../normalize-domain';
  8. import { OUTPUT_MODULES_DIR, OUTPUT_SURGE_DIR } from '../../constants/dir';
  9. import { withBannerArray, withIdentityContent } from '../misc';
  10. import { MARKER_DOMAIN } from '../../constants/description';
  11. export class SurgeDomainSet extends BaseWriteStrategy {
  12. public readonly name = 'surge domainset';
  13. // readonly type = 'domainset';
  14. readonly fileExtension = 'conf';
  15. type = 'domainset';
  16. protected result: string[] = [MARKER_DOMAIN];
  17. constructor(outputDir = OUTPUT_SURGE_DIR) {
  18. super(outputDir);
  19. }
  20. withPadding = withBannerArray;
  21. writeDomain(domain: string): void {
  22. this.result.push(domain);
  23. }
  24. writeDomainSuffix(domain: string): void {
  25. this.result.push('.' + domain);
  26. }
  27. writeDomainKeywords = noop;
  28. writeDomainWildcard = noop;
  29. writeUserAgents = noop;
  30. writeProcessNames = noop;
  31. writeProcessPaths = noop;
  32. writeUrlRegexes = noop;
  33. writeIpCidrs = noop;
  34. writeIpCidr6s = noop;
  35. writeGeoip = noop;
  36. writeIpAsns = noop;
  37. writeSourceIpCidrs = noop;
  38. writeSourcePorts = noop;
  39. writeDestinationPorts = noop;
  40. writeProtocols = noop;
  41. writeOtherRules = noop;
  42. }
  43. export class SurgeRuleSet extends BaseWriteStrategy {
  44. public readonly name: string = 'surge ruleset';
  45. readonly fileExtension = 'conf';
  46. protected result: string[] = [`DOMAIN,${MARKER_DOMAIN}`];
  47. constructor(
  48. /** Surge RULE-SET can be both ip or non_ip, so this needs to be specified */
  49. public readonly type: 'ip' | 'non_ip' | (string & {}),
  50. public readonly outputDir = OUTPUT_SURGE_DIR
  51. ) {
  52. super(outputDir);
  53. }
  54. withPadding = withBannerArray;
  55. writeDomain(domain: string): void {
  56. this.result.push('DOMAIN,' + domain);
  57. }
  58. writeDomainSuffix(domain: string): void {
  59. this.result.push('DOMAIN-SUFFIX,' + domain);
  60. }
  61. writeDomainKeywords(keyword: Set<string>): void {
  62. appendSetElementsToArray(this.result, keyword, i => `DOMAIN-KEYWORD,${i}`);
  63. }
  64. writeDomainWildcard(wildcard: string): void {
  65. this.result.push(`DOMAIN-WILDCARD,${wildcard}`);
  66. }
  67. writeUserAgents(userAgent: Set<string>): void {
  68. appendSetElementsToArray(this.result, userAgent, i => `USER-AGENT,${i}`);
  69. }
  70. writeProcessNames(processName: Set<string>): void {
  71. appendSetElementsToArray(this.result, processName, i => `PROCESS-NAME,${i}`);
  72. }
  73. writeProcessPaths(processPath: Set<string>): void {
  74. appendSetElementsToArray(this.result, processPath, i => `PROCESS-NAME,${i}`);
  75. }
  76. writeUrlRegexes(urlRegex: Set<string>): void {
  77. appendSetElementsToArray(this.result, urlRegex, i => `URL-REGEX,${i}`);
  78. }
  79. writeIpCidrs(ipCidr: string[], noResolve: boolean): void {
  80. for (let i = 0, len = ipCidr.length; i < len; i++) {
  81. this.result.push(`IP-CIDR,${ipCidr[i]}${noResolve ? ',no-resolve' : ''}`);
  82. }
  83. }
  84. writeIpCidr6s(ipCidr6: string[], noResolve: boolean): void {
  85. for (let i = 0, len = ipCidr6.length; i < len; i++) {
  86. this.result.push(`IP-CIDR6,${ipCidr6[i]}${noResolve ? ',no-resolve' : ''}`);
  87. }
  88. }
  89. writeGeoip(geoip: Set<string>, noResolve: boolean): void {
  90. appendSetElementsToArray(this.result, geoip, i => `GEOIP,${i}${noResolve ? ',no-resolve' : ''}`);
  91. }
  92. writeIpAsns(asns: Set<string>, noResolve: boolean): void {
  93. appendSetElementsToArray(this.result, asns, i => `IP-ASN,${i}${noResolve ? ',no-resolve' : ''}`);
  94. }
  95. writeSourceIpCidrs(sourceIpCidr: string[]): void {
  96. for (let i = 0, len = sourceIpCidr.length; i < len; i++) {
  97. this.result.push(`SRC-IP,${sourceIpCidr[i]}`);
  98. }
  99. }
  100. writeSourcePorts(port: Set<string>): void {
  101. appendSetElementsToArray(this.result, port, i => `SRC-PORT,${i}`);
  102. }
  103. writeDestinationPorts(port: Set<string>): void {
  104. appendSetElementsToArray(this.result, port, i => `DEST-PORT,${i}`);
  105. }
  106. writeProtocols(protocol: Set<string>): void {
  107. appendSetElementsToArray(this.result, protocol, i => `PROTOCOL,${i}`);
  108. }
  109. writeOtherRules(rule: string[]): void {
  110. appendArrayInPlace(this.result, rule);
  111. }
  112. }
  113. export class SurgeMitmSgmodule extends BaseWriteStrategy {
  114. public readonly name = 'surge sgmodule';
  115. // readonly type = 'domainset';
  116. readonly fileExtension = 'sgmodule';
  117. readonly type = '';
  118. private readonly rules = new Set<string>();
  119. protected get result() {
  120. if (this.rules.size === 0) {
  121. return null;
  122. }
  123. return [
  124. '#!name=[Sukka] Surge Reject MITM',
  125. `#!desc=为 URL Regex 规则组启用 MITM (size: ${this.rules.size})`,
  126. '',
  127. '[MITM]',
  128. 'hostname = %APPEND% ' + Array.from(this.rules).join(', ')
  129. ];
  130. }
  131. withPadding = withIdentityContent;
  132. constructor(moduleName: string, outputDir = OUTPUT_MODULES_DIR) {
  133. super(outputDir);
  134. this.withFilename(moduleName);
  135. }
  136. writeDomain = noop;
  137. writeDomainSuffix = noop;
  138. writeDomainKeywords = noop;
  139. writeDomainWildcard = noop;
  140. writeUserAgents = noop;
  141. writeProcessNames = noop;
  142. writeProcessPaths = noop;
  143. writeUrlRegexes(urlRegexes: Set<string>): void {
  144. const urlRegexResults: Array<{ origin: string, processed: string[] }> = [];
  145. const parsedFailures: Array<[original: string, processed: string]> = [];
  146. const parsed: Array<[original: string, domain: string]> = [];
  147. for (let urlRegex of urlRegexes) {
  148. if (
  149. urlRegex.startsWith('http://')
  150. || urlRegex.startsWith('^http://')
  151. ) {
  152. continue;
  153. }
  154. if (urlRegex.startsWith('^https?://')) {
  155. urlRegex = urlRegex.slice(10);
  156. }
  157. if (urlRegex.startsWith('^https://')) {
  158. urlRegex = urlRegex.slice(9);
  159. }
  160. const potentialHostname = urlRegex.slice(0, urlRegex.indexOf('/'))
  161. // pre process regex
  162. .replaceAll(String.raw`\.`, '.')
  163. .replaceAll('.+', '*')
  164. .replaceAll(/([a-z])\?/g, '($1|)')
  165. // convert regex to surge hostlist syntax
  166. .replaceAll('([a-z])', '?')
  167. .replaceAll(String.raw`\d`, '?')
  168. .replaceAll(/\*+/g, '*');
  169. let processed: string[] = [potentialHostname];
  170. const matches = [...potentialHostname.matchAll(/\((?:([^()|]+)\|)+([^()|]*)\)/g)];
  171. if (matches.length > 0) {
  172. const replaceVariant = (combinations: string[], fullMatch: string, options: string[]): string[] => {
  173. const newCombinations: string[] = [];
  174. combinations.forEach(combination => {
  175. options.forEach(option => {
  176. newCombinations.push(combination.replace(fullMatch, option));
  177. });
  178. });
  179. return newCombinations;
  180. };
  181. for (let i = 0; i < matches.length; i++) {
  182. const match = matches[i];
  183. const [_, ...options] = match;
  184. processed = replaceVariant(processed, _, options);
  185. }
  186. }
  187. urlRegexResults.push({
  188. origin: potentialHostname,
  189. processed
  190. });
  191. }
  192. for (const i of urlRegexResults) {
  193. for (const processed of i.processed) {
  194. if (
  195. normalizeDomain(
  196. processed
  197. .replaceAll('*', 'a')
  198. .replaceAll('?', 'b')
  199. )
  200. ) {
  201. parsed.push([i.origin, processed]);
  202. } else if (!isProbablyIpv4(processed)) {
  203. parsedFailures.push([i.origin, processed]);
  204. }
  205. }
  206. }
  207. if (parsedFailures.length > 0) {
  208. console.error(picocolors.bold('Parsed Failed'));
  209. console.table(parsedFailures);
  210. }
  211. for (let i = 0, len = parsed.length; i < len; i++) {
  212. this.rules.add(parsed[i][1]);
  213. }
  214. }
  215. writeIpCidrs = noop;
  216. writeIpCidr6s = noop;
  217. writeGeoip = noop;
  218. writeIpAsns = noop;
  219. writeSourceIpCidrs = noop;
  220. writeSourcePorts = noop;
  221. writeDestinationPorts = noop;
  222. writeProtocols = noop;
  223. writeOtherRules = noop;
  224. }