build-reject-domainset.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. // @ts-check
  2. import fsp from 'fs/promises'
  3. import path from 'path';
  4. import { processHosts, processFilterRules } from './lib/parse-filter';
  5. import createTrie from './lib/trie';
  6. import { HOSTS, ADGUARD_FILTERS, PREDEFINED_WHITELIST, PREDEFINED_ENFORCED_BACKLIST } from './lib/reject-data-source';
  7. import { createRuleset, compareAndWriteFile } from './lib/create-file';
  8. import { processLine } from './lib/process-line';
  9. import { domainDeduper } from './lib/domain-deduper';
  10. import createKeywordFilter from './lib/aho-corasick';
  11. import { readFileByLine } from './lib/fetch-remote-text-by-line';
  12. import { createDomainSorter } from './lib/stable-sort-domain';
  13. import { traceSync, task } from './lib/trace-runner';
  14. import { getGorhillPublicSuffixPromise } from './lib/get-gorhill-publicsuffix';
  15. import * as tldts from 'tldts';
  16. import { SHARED_DESCRIPTION } from './lib/constants';
  17. /** Whitelists */
  18. const filterRuleWhitelistDomainSets = new Set(PREDEFINED_WHITELIST);
  19. /** @type {Set<string>} Dedupe domains inclued by DOMAIN-KEYWORD */
  20. const domainKeywordsSet: Set<string> = new Set();
  21. /** @type {Set<string>} Dedupe domains included by DOMAIN-SUFFIX */
  22. const domainSuffixSet: Set<string> = new Set();
  23. export const buildRejectDomainSet = task(import.meta.path, async () => {
  24. /** @type Set<string> */
  25. const domainSets: Set<string> = new Set();
  26. // Parse from AdGuard Filters
  27. console.time('* Download and process Hosts / AdBlock Filter Rules');
  28. let shouldStop = false;
  29. const [gorhill] = await Promise.all([
  30. getGorhillPublicSuffixPromise(),
  31. // Parse from remote hosts & domain lists
  32. ...HOSTS.map(entry => processHosts(entry[0], entry[1]).then(hosts => {
  33. hosts.forEach(host => {
  34. if (host) {
  35. domainSets.add(host);
  36. }
  37. });
  38. })),
  39. ...ADGUARD_FILTERS.map(input => {
  40. const promise = typeof input === 'string'
  41. ? processFilterRules(input)
  42. : processFilterRules(input[0], input[1] || undefined);
  43. return promise.then((i) => {
  44. if (i) {
  45. const { white, black, foundDebugDomain } = i;
  46. if (foundDebugDomain) {
  47. shouldStop = true;
  48. // we should not break here, as we want to see full matches from all data source
  49. }
  50. white.forEach(i => filterRuleWhitelistDomainSets.add(i));
  51. black.forEach(i => domainSets.add(i));
  52. } else {
  53. process.exitCode = 1;
  54. throw new Error('Failed to process AdGuard Filter Rules!');
  55. }
  56. });
  57. }),
  58. ...([
  59. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exceptions.txt',
  60. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exclusions.txt'
  61. ].map(input => processFilterRules(input).then((i) => {
  62. if (i) {
  63. const { white, black } = i;
  64. white.forEach(i => {
  65. filterRuleWhitelistDomainSets.add(i);
  66. });
  67. black.forEach(i => {
  68. filterRuleWhitelistDomainSets.add(i);
  69. });
  70. } else {
  71. process.exitCode = 1;
  72. throw new Error('Failed to process AdGuard Filter Rules!');
  73. }
  74. })))
  75. ]);
  76. // remove pre-defined enforced blacklist from whitelist
  77. const trie0 = createTrie(filterRuleWhitelistDomainSets);
  78. PREDEFINED_ENFORCED_BACKLIST.forEach(enforcedBlack => {
  79. trie0.find(enforcedBlack).forEach(found => filterRuleWhitelistDomainSets.delete(found));
  80. });
  81. console.timeEnd('* Download and process Hosts / AdBlock Filter Rules');
  82. if (shouldStop) {
  83. // eslint-disable-next-line n/no-process-exit -- force stop
  84. process.exit(1);
  85. }
  86. let previousSize = domainSets.size;
  87. console.log(`Import ${previousSize} rules from Hosts / AdBlock Filter Rules!`);
  88. for await (const line of readFileByLine(path.resolve(import.meta.dir, '../Source/domainset/reject_sukka.conf'))) {
  89. const l = processLine(line);
  90. if (l) {
  91. domainSets.add(l);
  92. }
  93. }
  94. previousSize = domainSets.size - previousSize;
  95. console.log(`Import ${previousSize} rules from reject_sukka.conf!`);
  96. for await (const line of readFileByLine(path.resolve(import.meta.dir, '../Source/non_ip/reject.conf'))) {
  97. if (line.startsWith('DOMAIN-KEYWORD')) {
  98. const [, ...keywords] = line.split(',');
  99. domainKeywordsSet.add(keywords.join(',').trim());
  100. } else if (line.startsWith('DOMAIN-SUFFIX')) {
  101. const [, ...keywords] = line.split(',');
  102. domainSuffixSet.add(keywords.join(',').trim());
  103. }
  104. }
  105. for await (const line of readFileByLine(path.resolve(import.meta.dir, '../List/domainset/reject_phishing.conf'))) {
  106. const l = processLine(line);
  107. if (l && l[0] === '.') {
  108. domainSuffixSet.add(l.slice(1));
  109. }
  110. }
  111. console.log(`Import ${domainKeywordsSet.size} black keywords and ${domainSuffixSet.size} black suffixes!`);
  112. previousSize = domainSets.size;
  113. // Dedupe domainSets
  114. console.log(`Start deduping from black keywords/suffixes! (${previousSize})`);
  115. console.time('* Dedupe from black keywords/suffixes');
  116. const trie1 = createTrie(domainSets);
  117. domainSuffixSet.forEach(suffix => {
  118. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  119. });
  120. filterRuleWhitelistDomainSets.forEach(suffix => {
  121. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  122. });
  123. // remove pre-defined enforced blacklist from whitelist
  124. const kwfilter = createKeywordFilter(domainKeywordsSet);
  125. // Build whitelist trie, to handle case like removing `g.msn.com` due to white `.g.msn.com` (`@@||g.msn.com`)
  126. const trieWhite = createTrie(filterRuleWhitelistDomainSets);
  127. for (const domain of domainSets) {
  128. if (domain[0] === '.') {
  129. if (trieWhite.contains(domain)) {
  130. domainSets.delete(domain);
  131. continue;
  132. }
  133. } else if (trieWhite.has(`.${domain}`)) {
  134. domainSets.delete(domain);
  135. continue;
  136. }
  137. // Remove keyword
  138. if (kwfilter.search(domain)) {
  139. domainSets.delete(domain);
  140. }
  141. }
  142. console.timeEnd('* Dedupe from black keywords/suffixes');
  143. console.log(`Deduped ${previousSize} - ${domainSets.size} = ${previousSize - domainSets.size} from black keywords and suffixes!`);
  144. previousSize = domainSets.size;
  145. // Dedupe domainSets
  146. console.log(`Start deduping! (${previousSize})`);
  147. const dudupedDominArray = traceSync('* Dedupe from covered subdomain', () => domainDeduper(Array.from(domainSets)));
  148. console.log(`Deduped ${previousSize - dudupedDominArray.length} rules!`);
  149. // Create reject stats
  150. const rejectDomainsStats: [string, number][] = traceSync(
  151. '* Collect reject domain stats',
  152. () => Object.entries(
  153. dudupedDominArray.reduce<Record<string, number>>((acc, cur) => {
  154. const suffix = tldts.getDomain(cur, { allowPrivateDomains: false, detectIp: false });
  155. if (suffix) {
  156. acc[suffix] = (acc[suffix] ?? 0) + 1;
  157. }
  158. return acc;
  159. }, {})
  160. ).filter(a => a[1] > 10).sort((a, b) => {
  161. const t = b[1] - a[1];
  162. if (t !== 0) {
  163. return t;
  164. }
  165. return a[0].localeCompare(b[0]);
  166. })
  167. );
  168. const domainSorter = createDomainSorter(gorhill);
  169. const domainset = traceSync('* Sort reject domainset', () => dudupedDominArray.sort(domainSorter));
  170. const description = [
  171. ...SHARED_DESCRIPTION,
  172. '',
  173. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  174. '',
  175. 'Build from:',
  176. ...HOSTS.map(host => ` - ${host[0]}`),
  177. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`)
  178. ];
  179. return Promise.all([
  180. ...createRuleset(
  181. 'Sukka\'s Ruleset - Reject Base',
  182. description,
  183. new Date(),
  184. domainset,
  185. 'domainset',
  186. path.resolve(import.meta.dir, '../List/domainset/reject.conf'),
  187. path.resolve(import.meta.dir, '../Clash/domainset/reject.txt')
  188. ),
  189. compareAndWriteFile(
  190. rejectDomainsStats.map(([domain, count]) => `${domain}${' '.repeat(100 - domain.length)}${count}`),
  191. path.resolve(import.meta.dir, '../List/internal/reject-stats.txt')
  192. ),
  193. // Copy reject_sukka.conf for backward compatibility
  194. fsp.cp(
  195. path.resolve(import.meta.dir, '../Source/domainset/reject_sukka.conf'),
  196. path.resolve(import.meta.dir, '../List/domainset/reject_sukka.conf'),
  197. { force: true, recursive: true }
  198. )
  199. ]);
  200. });
  201. if (import.meta.main) {
  202. buildRejectDomainSet();
  203. }