build-reject-domainset.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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. // tldts-experimental is way faster than tldts, but very little bit inaccurate
  13. // (since it is hashes based). But the result is still deterministic, which is
  14. // enough when creating a simple stat of reject hosts.
  15. import * as tldts from 'tldts-experimental';
  16. import { SHARED_DESCRIPTION } from './lib/constants';
  17. import { getPhishingDomains } from './lib/get-phishing-domains';
  18. import { subtract as SetSubstract } from 'mnemonist/set';
  19. import { setAddFromArray, setAddFromArrayCurried } from './lib/set-add-from-array';
  20. import { sort } from './lib/timsort';
  21. export const buildRejectDomainSet = task(import.meta.path, async (span) => {
  22. /** Whitelists */
  23. const filterRuleWhitelistDomainSets = new Set(PREDEFINED_WHITELIST);
  24. const domainSets = new Set<string>();
  25. const appendArrayToDomainSets = setAddFromArrayCurried(domainSets);
  26. // Parse from AdGuard Filters
  27. const shouldStop = await span
  28. .traceChild('download and process hosts / adblock filter rules')
  29. .traceAsyncFn(async (childSpan) => {
  30. // eslint-disable-next-line sukka/no-single-return -- not single return
  31. let shouldStop = false;
  32. await Promise.all([
  33. // Parse from remote hosts & domain lists
  34. ...HOSTS.map(entry => processHosts(childSpan, ...entry).then(appendArrayToDomainSets)),
  35. ...DOMAIN_LISTS.map(entry => processDomainLists(childSpan, ...entry).then(appendArrayToDomainSets)),
  36. ...ADGUARD_FILTERS.map(
  37. input => processFilterRules(childSpan, ...input)
  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. ...([
  49. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exceptions.txt',
  50. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exclusions.txt'
  51. ].map(
  52. input => processFilterRules(childSpan, input)
  53. .then(({ white, black }) => {
  54. setAddFromArray(filterRuleWhitelistDomainSets, white);
  55. setAddFromArray(filterRuleWhitelistDomainSets, black);
  56. })
  57. )),
  58. getPhishingDomains(childSpan).then(appendArrayToDomainSets),
  59. childSpan.traceChildAsync('process reject_sukka.conf', () => readFileIntoProcessedArray(path.resolve(import.meta.dir, '../Source/domainset/reject_sukka.conf'))
  60. .then(appendArrayToDomainSets))
  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. console.log(`Import ${domainSets.size} 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-KEYWORD from non_ip/reject.conf for deduplication */
  72. const domainKeywordsSet = new Set<string>();
  73. await childSpan.traceChildAsync('collect keywords/suffixes', async () => {
  74. for await (const line of readFileByLine(path.resolve(import.meta.dir, '../Source/non_ip/reject.conf'))) {
  75. const [type, value] = line.split(',');
  76. if (type === 'DOMAIN-KEYWORD') {
  77. domainKeywordsSet.add(value.trim());
  78. } else if (type === 'DOMAIN-SUFFIX') {
  79. domainSets.add(`.${value.trim()}`); // Add to domainSets for later deduplication
  80. }
  81. }
  82. });
  83. // Perform kwfilter to remove as many domains as possible from domainSets before creating trie
  84. childSpan.traceChildSync('dedupe from black keywords', () => {
  85. const kwfilter = createKeywordFilter(domainKeywordsSet);
  86. for (const domain of domainSets) {
  87. // Remove keyword
  88. if (kwfilter(domain)) {
  89. domainSets.delete(domain);
  90. }
  91. }
  92. });
  93. });
  94. const trie = span.traceChildSync('dedupe from white suffixes', () => {
  95. const trie = createTrie(domainSets, true, true);
  96. filterRuleWhitelistDomainSets.forEach(suffix => {
  97. trie.whitelist(suffix);
  98. });
  99. return trie;
  100. });
  101. // Dedupe domainSets
  102. const dudupedDominArray = span.traceChildSync('dedupe from covered subdomain', () => domainDeduper(trie));
  103. console.log(`Final size ${dudupedDominArray.length}`);
  104. // Create reject stats
  105. const rejectDomainsStats: Array<[string, number]> = span
  106. .traceChild('create reject stats')
  107. .traceSyncFn(() => {
  108. const tldtsOpt = { allowPrivateDomains: false, detectIp: false, validateHostname: false };
  109. const statMap = dudupedDominArray.reduce<Map<string, number>>((acc, cur) => {
  110. const suffix = tldts.getDomain(cur, tldtsOpt);
  111. if (!suffix) return acc;
  112. if (acc.has(suffix)) {
  113. acc.set(suffix, acc.get(suffix)! + 1);
  114. } else {
  115. acc.set(suffix, 1);
  116. }
  117. return acc;
  118. }, new Map());
  119. return sort(Array.from(statMap.entries()).filter(a => a[1] > 9), (a, b) => (b[1] - a[1]) || a[0].localeCompare(b[0]));
  120. });
  121. const description = [
  122. ...SHARED_DESCRIPTION,
  123. '',
  124. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  125. '',
  126. 'Build from:',
  127. ...HOSTS.map(host => ` - ${host[0]}`),
  128. ...DOMAIN_LISTS.map(domainList => ` - ${domainList[0]}`),
  129. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`),
  130. ' - https://curbengh.github.io/phishing-filter/phishing-filter-hosts.txt',
  131. ' - https://phishing.army/download/phishing_army_blocklist.txt'
  132. ];
  133. return Promise.all([
  134. createRuleset(
  135. span,
  136. 'Sukka\'s Ruleset - Reject Base',
  137. description,
  138. new Date(),
  139. span.traceChildSync('sort reject domainset', () => sortDomains(dudupedDominArray)),
  140. 'domainset',
  141. path.resolve(import.meta.dir, '../List/domainset/reject.conf'),
  142. path.resolve(import.meta.dir, '../Clash/domainset/reject.txt')
  143. ),
  144. compareAndWriteFile(
  145. span,
  146. rejectDomainsStats.map(([domain, count]) => `${domain}${' '.repeat(100 - domain.length)}${count}`),
  147. path.resolve(import.meta.dir, '../Internal/reject-stats.txt')
  148. )
  149. ]);
  150. });
  151. if (import.meta.main) {
  152. buildRejectDomainSet();
  153. }