build-reject-domainset.ts 7.1 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. // Remove as many domains as possible from domainSets before creating trie
  84. SetSubstract(domainSets, filterRuleWhitelistDomainSets);
  85. // Perform kwfilter to remove as many domains as possible from domainSets before creating trie
  86. childSpan.traceChildSync('dedupe from black keywords', () => {
  87. const kwfilter = createKeywordFilter(domainKeywordsSet);
  88. for (const domain of domainSets) {
  89. // Remove keyword
  90. if (kwfilter(domain)) {
  91. domainSets.delete(domain);
  92. }
  93. }
  94. });
  95. });
  96. const trie = createTrie(domainSets, true, true);
  97. span.traceChildSync('dedupe from white suffixes', () => {
  98. filterRuleWhitelistDomainSets.forEach(suffix => {
  99. trie.whitelist(suffix);
  100. });
  101. });
  102. // Dedupe domainSets
  103. const dudupedDominArray = span.traceChildSync('dedupe from covered subdomain', () => domainDeduper(trie));
  104. console.log(`Final size ${dudupedDominArray.length}`);
  105. // Create reject stats
  106. const rejectDomainsStats: Array<[string, number]> = span
  107. .traceChild('create reject stats')
  108. .traceSyncFn(() => {
  109. const tldtsOpt = { allowPrivateDomains: false, detectIp: false, validateHostname: false };
  110. const statMap = dudupedDominArray.reduce<Map<string, number>>((acc, cur) => {
  111. const suffix = tldts.getDomain(cur, tldtsOpt);
  112. if (!suffix) return acc;
  113. if (acc.has(suffix)) {
  114. acc.set(suffix, acc.get(suffix)! + 1);
  115. } else {
  116. acc.set(suffix, 1);
  117. }
  118. return acc;
  119. }, new Map());
  120. return sort(Array.from(statMap.entries()).filter(a => a[1] > 9), (a, b) => (b[1] - a[1]) || a[0].localeCompare(b[0]));
  121. });
  122. const description = [
  123. ...SHARED_DESCRIPTION,
  124. '',
  125. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  126. '',
  127. 'Build from:',
  128. ...HOSTS.map(host => ` - ${host[0]}`),
  129. ...DOMAIN_LISTS.map(domainList => ` - ${domainList[0]}`),
  130. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`),
  131. ' - https://curbengh.github.io/phishing-filter/phishing-filter-hosts.txt',
  132. ' - https://phishing.army/download/phishing_army_blocklist.txt'
  133. ];
  134. return Promise.all([
  135. createRuleset(
  136. span,
  137. 'Sukka\'s Ruleset - Reject Base',
  138. description,
  139. new Date(),
  140. span.traceChildSync('sort reject domainset', () => sortDomains(dudupedDominArray)),
  141. 'domainset',
  142. path.resolve(import.meta.dir, '../List/domainset/reject.conf'),
  143. path.resolve(import.meta.dir, '../Clash/domainset/reject.txt')
  144. ),
  145. compareAndWriteFile(
  146. span,
  147. rejectDomainsStats.map(([domain, count]) => `${domain}${' '.repeat(100 - domain.length)}${count}`),
  148. path.resolve(import.meta.dir, '../Internal/reject-stats.txt')
  149. )
  150. ]);
  151. });
  152. if (import.meta.main) {
  153. buildRejectDomainSet();
  154. }