ruleset.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import { merge } from 'fast-cidr-tools';
  2. import type { Span } from '../../trace';
  3. import createKeywordFilter from '../aho-corasick';
  4. import { appendArrayInPlace } from '../append-array-in-place';
  5. import { appendArrayFromSet } from '../misc';
  6. import type { SingboxSourceFormat } from '../singbox';
  7. import { sortDomains } from '../stable-sort-domain';
  8. import { RuleOutput } from './base';
  9. import picocolors from 'picocolors';
  10. import { normalizeDomain } from '../normalize-domain';
  11. import { isProbablyIpv4, isProbablyIpv6 } from '../is-fast-ip';
  12. type Preprocessed = [domain: string[], domainSuffix: string[], sortedDomainRules: string[]];
  13. export class RulesetOutput extends RuleOutput<Preprocessed> {
  14. constructor(span: Span, id: string, protected type: 'non_ip' | 'ip') {
  15. super(span, id);
  16. }
  17. protected preprocess() {
  18. const kwfilter = createKeywordFilter(this.domainKeywords);
  19. const domains: string[] = [];
  20. const domainSuffixes: string[] = [];
  21. const sortedDomainRules: string[] = [];
  22. for (const domain of sortDomains(this.domainTrie.dump(), this.apexDomainMap, this.subDomainMap)) {
  23. if (kwfilter(domain)) {
  24. continue;
  25. }
  26. if (domain[0] === '.') {
  27. domainSuffixes.push(domain.slice(1));
  28. sortedDomainRules.push(`DOMAIN-SUFFIX,${domain.slice(1)}`);
  29. } else {
  30. domains.push(domain);
  31. sortedDomainRules.push(`DOMAIN,${domain}`);
  32. }
  33. }
  34. return [domains, domainSuffixes, sortedDomainRules] satisfies Preprocessed;
  35. }
  36. surge(): string[] {
  37. const results: string[] = ['DOMAIN,this_ruleset_is_made_by_sukkaw.ruleset.skk.moe'];
  38. appendArrayInPlace(results, this.$preprocessed[2]);
  39. appendArrayFromSet(results, this.domainKeywords, i => `DOMAIN-KEYWORD,${i}`);
  40. appendArrayFromSet(results, this.domainWildcard, i => `DOMAIN-WILDCARD,${i}`);
  41. appendArrayFromSet(results, this.userAgent, i => `USER-AGENT,${i}`);
  42. appendArrayFromSet(results, this.processName, i => `PROCESS-NAME,${i}`);
  43. appendArrayFromSet(results, this.processPath, i => `PROCESS-NAME,${i}`);
  44. appendArrayFromSet(results, this.sourceIpOrCidr, i => `SRC-IP,${i}`);
  45. appendArrayFromSet(results, this.sourcePort, i => `SRC-PORT,${i}`);
  46. appendArrayFromSet(results, this.destPort, i => `DEST-PORT,${i}`);
  47. appendArrayInPlace(results, this.otherRules);
  48. appendArrayFromSet(results, this.urlRegex, i => `URL-REGEX,${i}`);
  49. appendArrayInPlace(
  50. results,
  51. merge(Array.from(this.ipcidrNoResolve)).map(i => `IP-CIDR,${i},no-resolve`, true)
  52. );
  53. appendArrayFromSet(results, this.ipcidr6NoResolve, i => `IP-CIDR6,${i},no-resolve`);
  54. appendArrayFromSet(results, this.ipasnNoResolve, i => `IP-ASN,${i},no-resolve`);
  55. appendArrayFromSet(results, this.groipNoResolve, i => `GEOIP,${i},no-resolve`);
  56. appendArrayInPlace(
  57. results,
  58. merge(Array.from(this.ipcidr)).map(i => `IP-CIDR,${i}`, true)
  59. );
  60. appendArrayFromSet(results, this.ipcidr6, i => `IP-CIDR6,${i}`);
  61. appendArrayFromSet(results, this.ipasn, i => `IP-ASN,${i}`);
  62. appendArrayFromSet(results, this.geoip, i => `GEOIP,${i}`);
  63. return results;
  64. }
  65. clash(): string[] {
  66. const results: string[] = ['DOMAIN,this_ruleset_is_made_by_sukkaw.ruleset.skk.moe'];
  67. appendArrayInPlace(results, this.$preprocessed[2]);
  68. appendArrayFromSet(results, this.domainKeywords, i => `DOMAIN-KEYWORD,${i}`);
  69. appendArrayFromSet(results, this.domainWildcard, i => `DOMAIN-REGEX,${RuleOutput.domainWildCardToRegex(i)}`);
  70. appendArrayFromSet(results, this.processName, i => `PROCESS-NAME,${i}`);
  71. appendArrayFromSet(results, this.processPath, i => `PROCESS-PATH,${i}`);
  72. appendArrayFromSet(results, this.sourceIpOrCidr, value => {
  73. if (value.includes('/')) {
  74. return `SRC-IP-CIDR,${value}`;
  75. }
  76. if (isProbablyIpv4(value)) {
  77. return `SRC-IP-CIDR,${value}/32`;
  78. }
  79. if (isProbablyIpv6(value)) {
  80. return `SRC-IP-CIDR6,${value}/128`;
  81. }
  82. return '';
  83. });
  84. appendArrayFromSet(results, this.sourcePort, i => `SRC-PORT,${i}`);
  85. appendArrayFromSet(results, this.destPort, i => `DST-PORT,${i}`);
  86. // appendArrayInPlace(results, this.otherRules);
  87. appendArrayInPlace(
  88. results,
  89. merge(Array.from(this.ipcidrNoResolve)).map(i => `IP-CIDR,${i},no-resolve`, true)
  90. );
  91. appendArrayFromSet(results, this.ipcidr6NoResolve, i => `IP-CIDR6,${i},no-resolve`);
  92. appendArrayFromSet(results, this.ipasnNoResolve, i => `IP-ASN,${i},no-resolve`);
  93. appendArrayFromSet(results, this.groipNoResolve, i => `GEOIP,${i},no-resolve`);
  94. appendArrayInPlace(
  95. results,
  96. merge(Array.from(this.ipcidr)).map(i => `IP-CIDR,${i}`, true)
  97. );
  98. appendArrayFromSet(results, this.ipcidr6, i => `IP-CIDR6,${i}`);
  99. appendArrayFromSet(results, this.ipasn, i => `IP-ASN,${i}`);
  100. appendArrayFromSet(results, this.geoip, i => `GEOIP,${i}`);
  101. return results;
  102. }
  103. singbox(): string[] {
  104. const ip_cidr: string[] = [];
  105. appendArrayInPlace(
  106. ip_cidr,
  107. merge(
  108. appendArrayInPlace(Array.from(this.ipcidrNoResolve), Array.from(this.ipcidr)),
  109. true
  110. )
  111. );
  112. appendArrayFromSet(ip_cidr, this.ipcidr6NoResolve);
  113. appendArrayFromSet(ip_cidr, this.ipcidr6);
  114. const singbox: SingboxSourceFormat = {
  115. version: 2,
  116. rules: [{
  117. domain: appendArrayInPlace(['this_ruleset_is_made_by_sukkaw.ruleset.skk.moe'], this.$preprocessed[0]),
  118. domain_suffix: this.$preprocessed[1],
  119. domain_keyword: Array.from(this.domainKeywords),
  120. domain_regex: Array.from(this.domainWildcard).map(RuleOutput.domainWildCardToRegex),
  121. ip_cidr,
  122. source_ip_cidr: [...this.sourceIpOrCidr].reduce<string[]>((acc, cur) => {
  123. if (cur.includes('/')) {
  124. acc.push(cur);
  125. } else if (isProbablyIpv4(cur)) {
  126. acc.push(cur + '/32');
  127. } else if (isProbablyIpv6(cur)) {
  128. acc.push(cur + '/128');
  129. }
  130. return acc;
  131. }, []),
  132. source_port: [...this.sourcePort].reduce<number[]>((acc, cur) => {
  133. const tmp = Number(cur);
  134. if (!Number.isNaN(tmp)) {
  135. acc.push(tmp);
  136. }
  137. return acc;
  138. }, []),
  139. port: [...this.destPort].reduce<number[]>((acc, cur) => {
  140. const tmp = Number(cur);
  141. if (!Number.isNaN(tmp)) {
  142. acc.push(tmp);
  143. }
  144. return acc;
  145. }, []),
  146. process_name: Array.from(this.processName),
  147. process_path: Array.from(this.processPath)
  148. }]
  149. };
  150. return RuleOutput.jsonToLines(singbox);
  151. }
  152. mitmSgmodule(): string[] | null {
  153. if (this.urlRegex.size === 0 || this.mitmSgmodulePath === null) {
  154. return null;
  155. }
  156. const urlRegexResults: Array<{ origin: string, processed: string[] }> = [];
  157. const parsedFailures: Array<[original: string, processed: string]> = [];
  158. const parsed: Array<[original: string, domain: string]> = [];
  159. for (let urlRegex of this.urlRegex) {
  160. if (
  161. urlRegex.startsWith('http://')
  162. || urlRegex.startsWith('^http://')
  163. ) {
  164. continue;
  165. }
  166. if (urlRegex.startsWith('^https?://')) {
  167. urlRegex = urlRegex.slice(10);
  168. }
  169. if (urlRegex.startsWith('^https://')) {
  170. urlRegex = urlRegex.slice(9);
  171. }
  172. const potentialHostname = urlRegex.split('/')[0]
  173. // pre process regex
  174. .replaceAll(String.raw`\.`, '.')
  175. .replaceAll('.+', '*')
  176. .replaceAll(/([a-z])\?/g, '($1|)')
  177. // convert regex to surge hostlist syntax
  178. .replaceAll('([a-z])', '?')
  179. .replaceAll(String.raw`\d`, '?')
  180. .replaceAll(/\*+/g, '*');
  181. let processed: string[] = [potentialHostname];
  182. const matches = [...potentialHostname.matchAll(/\((?:([^()|]+)\|)+([^()|]*)\)/g)];
  183. if (matches.length > 0) {
  184. const replaceVariant = (combinations: string[], fullMatch: string, options: string[]): string[] => {
  185. const newCombinations: string[] = [];
  186. combinations.forEach(combination => {
  187. options.forEach(option => {
  188. newCombinations.push(combination.replace(fullMatch, option));
  189. });
  190. });
  191. return newCombinations;
  192. };
  193. for (let i = 0; i < matches.length; i++) {
  194. const match = matches[i];
  195. const [_, ...options] = match;
  196. processed = replaceVariant(processed, _, options);
  197. }
  198. }
  199. urlRegexResults.push({
  200. origin: potentialHostname,
  201. processed
  202. });
  203. }
  204. for (const i of urlRegexResults) {
  205. for (const processed of i.processed) {
  206. if (normalizeDomain(
  207. processed
  208. .replaceAll('*', 'a')
  209. .replaceAll('?', 'b')
  210. )) {
  211. parsed.push([i.origin, processed]);
  212. } else if (!isProbablyIpv4(processed)) {
  213. parsedFailures.push([i.origin, processed]);
  214. }
  215. }
  216. }
  217. if (parsedFailures.length > 0) {
  218. console.error(picocolors.bold('Parsed Failed'));
  219. console.table(parsedFailures);
  220. }
  221. return [
  222. '#!name=[Sukka] Surge Reject MITM',
  223. '#!desc=为 URL Regex 规则组启用 MITM',
  224. '',
  225. '[MITM]',
  226. 'hostname = %APPEND% ' + Array.from(new Set(parsed.map(i => i[1]))).join(', ')
  227. ];
  228. }
  229. }