build-reject-domainset.ts 6.9 KB

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