build-reject-domainset.ts 7.9 KB

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