build-reject-domainset.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. // @ts-check
  2. import path from 'path';
  3. import { processHosts, processFilterRules, processDomainLists } from './lib/parse-filter';
  4. import { createTrie } from './lib/trie';
  5. import { HOSTS, ADGUARD_FILTERS, PREDEFINED_WHITELIST, PREDEFINED_ENFORCED_BACKLIST, DOMAIN_LISTS } from './lib/reject-data-source';
  6. import { createRuleset, compareAndWriteFile } from './lib/create-file';
  7. import { processLine } from './lib/process-line';
  8. import { domainDeduper } from './lib/domain-deduper';
  9. import createKeywordFilter from './lib/aho-corasick';
  10. import { readFileByLine } from './lib/fetch-text-by-line';
  11. import { sortDomains } from './lib/stable-sort-domain';
  12. import { task } from './trace';
  13. import { getGorhillPublicSuffixPromise } from './lib/get-gorhill-publicsuffix';
  14. import * as tldts from 'tldts';
  15. import { SHARED_DESCRIPTION } from './lib/constants';
  16. import { getPhishingDomains } from './lib/get-phishing-domains';
  17. import * as SetHelpers from 'mnemonist/set';
  18. import { setAddFromArray } from './lib/set-add-from-array';
  19. export const buildRejectDomainSet = task(import.meta.path, async (span) => {
  20. const gorhill = await getGorhillPublicSuffixPromise();
  21. /** Whitelists */
  22. const filterRuleWhitelistDomainSets = new Set(PREDEFINED_WHITELIST);
  23. const domainSets = new Set<string>();
  24. let shouldStop = false;
  25. // Parse from AdGuard Filters
  26. await span
  27. .traceChild('download and process hosts / adblock filter rules')
  28. .traceAsyncFn(async (childSpan) => {
  29. await Promise.all([
  30. // Parse from remote hosts & domain lists
  31. ...HOSTS.map(entry => processHosts(childSpan, entry[0], entry[1], entry[2]).then(hosts => SetHelpers.add(domainSets, hosts))),
  32. ...DOMAIN_LISTS.map(entry => processDomainLists(childSpan, entry[0], entry[1], entry[2]).then(hosts => SetHelpers.add(domainSets, hosts))),
  33. ...ADGUARD_FILTERS.map(input => (
  34. typeof input === 'string'
  35. ? processFilterRules(childSpan, input)
  36. : processFilterRules(childSpan, input[0], input[1], input[2])
  37. ).then(({ white, black, foundDebugDomain }) => {
  38. if (foundDebugDomain) {
  39. shouldStop = true;
  40. // we should not break here, as we want to see full matches from all data source
  41. }
  42. setAddFromArray(filterRuleWhitelistDomainSets, white);
  43. setAddFromArray(domainSets, black);
  44. })),
  45. ...([
  46. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exceptions.txt',
  47. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exclusions.txt'
  48. ].map(input => processFilterRules(childSpan, input).then(({ white, black }) => {
  49. setAddFromArray(filterRuleWhitelistDomainSets, white);
  50. setAddFromArray(filterRuleWhitelistDomainSets, black);
  51. }))),
  52. getPhishingDomains(childSpan).then(([purePhishingDomains, fullPhishingDomainSet]) => {
  53. SetHelpers.add(domainSets, fullPhishingDomainSet);
  54. setAddFromArray(domainSets, purePhishingDomains);
  55. }),
  56. childSpan.traceChild('process reject_sukka.conf').traceAsyncFn(async () => {
  57. for await (const l of readFileByLine(path.resolve(import.meta.dir, '../Source/domainset/reject_sukka.conf'))) {
  58. const line = processLine(l);
  59. if (!line) continue;
  60. domainSets.add(line);
  61. }
  62. })
  63. ]);
  64. // remove pre-defined enforced blacklist from whitelist
  65. const trie0 = createTrie(filterRuleWhitelistDomainSets);
  66. for (let i = 0, len1 = PREDEFINED_ENFORCED_BACKLIST.length; i < len1; i++) {
  67. const enforcedBlack = PREDEFINED_ENFORCED_BACKLIST[i];
  68. const found = trie0.find(enforcedBlack);
  69. for (let j = 0, len2 = found.length; j < len2; j++) {
  70. filterRuleWhitelistDomainSets.delete(found[j]);
  71. }
  72. }
  73. return shouldStop;
  74. });
  75. if (shouldStop) {
  76. process.exit(1);
  77. }
  78. let previousSize = domainSets.size;
  79. console.log(`Import ${previousSize} rules from Hosts / AdBlock Filter Rules & reject_sukka.conf!`);
  80. // Dedupe domainSets
  81. await span.traceChild('dedupe from black keywords/suffixes').traceAsyncFn(async () => {
  82. /** Collect DOMAIN-SUFFIX from non_ip/reject.conf for deduplication */
  83. const domainSuffixSet = new Set<string>();
  84. /** Collect DOMAIN-KEYWORD from non_ip/reject.conf for deduplication */
  85. const domainKeywordsSet = new Set<string>();
  86. for await (const line of readFileByLine(path.resolve(import.meta.dir, '../Source/non_ip/reject.conf'))) {
  87. const [type, keyword] = line.split(',');
  88. if (type === 'DOMAIN-KEYWORD') {
  89. domainKeywordsSet.add(keyword.trim());
  90. } else if (type === 'DOMAIN-SUFFIX') {
  91. domainSuffixSet.add(keyword.trim());
  92. }
  93. }
  94. const trie1 = createTrie(domainSets);
  95. domainSuffixSet.forEach(suffix => {
  96. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  97. });
  98. filterRuleWhitelistDomainSets.forEach(suffix => {
  99. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  100. });
  101. // remove pre-defined enforced blacklist from whitelist
  102. const kwfilter = createKeywordFilter(domainKeywordsSet);
  103. // handle case like removing `g.msn.com` due to white `.g.msn.com` (`@@||g.msn.com`)
  104. for (const domain of domainSets) {
  105. if (domain[0] === '.') {
  106. if (filterRuleWhitelistDomainSets.has(domain)) {
  107. domainSets.delete(domain);
  108. continue;
  109. }
  110. } else if (filterRuleWhitelistDomainSets.has(`.${domain}`)) {
  111. domainSets.delete(domain);
  112. continue;
  113. }
  114. // Remove keyword
  115. if (kwfilter.search(domain)) {
  116. domainSets.delete(domain);
  117. }
  118. }
  119. console.log(`Deduped ${previousSize} - ${domainSets.size} = ${previousSize - domainSets.size} from black keywords and suffixes!`);
  120. });
  121. previousSize = domainSets.size;
  122. // Dedupe domainSets
  123. const dudupedDominArray = span.traceChild('dedupe from covered subdomain').traceSyncFn(() => domainDeduper(Array.from(domainSets)));
  124. console.log(`Deduped ${previousSize - dudupedDominArray.length} rules from covered subdomain!`);
  125. console.log(`Final size ${dudupedDominArray.length}`);
  126. // Create reject stats
  127. const rejectDomainsStats: Array<[string, number]> = span
  128. .traceChild('create reject stats')
  129. .traceSyncFn(() => Object.entries(
  130. dudupedDominArray.reduce<Record<string, number>>((acc, cur) => {
  131. const suffix = tldts.getDomain(cur, { allowPrivateDomains: false, detectIp: false, validateHostname: false });
  132. if (suffix) {
  133. acc[suffix] = (acc[suffix] || 0) + 1;
  134. }
  135. return acc;
  136. }, {})
  137. ).filter(a => a[1] > 5).sort((a, b) => (b[1] - a[1]) || a[0].localeCompare(b[0])));
  138. const description = [
  139. ...SHARED_DESCRIPTION,
  140. '',
  141. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  142. '',
  143. 'Build from:',
  144. ...HOSTS.map(host => ` - ${host[0]}`),
  145. ...DOMAIN_LISTS.map(domainList => ` - ${domainList[0]}`),
  146. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`),
  147. ' - https://curbengh.github.io/phishing-filter/phishing-filter-hosts.txt',
  148. ' - https://phishing.army/download/phishing_army_blocklist.txt'
  149. ];
  150. return Promise.all([
  151. createRuleset(
  152. span,
  153. 'Sukka\'s Ruleset - Reject Base',
  154. description,
  155. new Date(),
  156. span.traceChild('sort reject domainset').traceSyncFn(() => sortDomains(dudupedDominArray, gorhill)),
  157. 'domainset',
  158. path.resolve(import.meta.dir, '../List/domainset/reject.conf'),
  159. path.resolve(import.meta.dir, '../Clash/domainset/reject.txt')
  160. ),
  161. compareAndWriteFile(
  162. span,
  163. rejectDomainsStats.map(([domain, count]) => `${domain}${' '.repeat(100 - domain.length)}${count}`),
  164. path.resolve(import.meta.dir, '../List/internal/reject-stats.txt')
  165. ),
  166. Bun.write(
  167. path.resolve(import.meta.dir, '../List/domainset/reject_sukka.conf'),
  168. '# The file has been deprecated, its content has been merged into the main `reject` domainset.\n'
  169. )
  170. ]);
  171. });
  172. if (import.meta.main) {
  173. buildRejectDomainSet();
  174. }