build-reject-domainset.ts 8.0 KB

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