build-reject-domainset.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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 { add as SetAdd, 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. // 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(setAddFromArrayCurried(domainSets))),
  34. ...DOMAIN_LISTS.map(entry => processDomainLists(childSpan, ...entry).then(setAddFromArrayCurried(domainSets))),
  35. ...ADGUARD_FILTERS.map(input => (
  36. typeof input === 'string'
  37. ? processFilterRules(childSpan, input)
  38. : processFilterRules(childSpan, ...input)
  39. ).then(({ white, black, foundDebugDomain }) => {
  40. if (foundDebugDomain) {
  41. // eslint-disable-next-line sukka/no-single-return -- not single return
  42. shouldStop = true;
  43. // we should not break here, as we want to see full matches from all data source
  44. }
  45. setAddFromArray(filterRuleWhitelistDomainSets, white);
  46. setAddFromArray(domainSets, black);
  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(input => processFilterRules(childSpan, input).then(({ white, black }) => {
  52. setAddFromArray(filterRuleWhitelistDomainSets, white);
  53. setAddFromArray(filterRuleWhitelistDomainSets, black);
  54. }))),
  55. getPhishingDomains(childSpan).then(setAddFromArrayCurried(domainSets)),
  56. childSpan.traceChildAsync('process reject_sukka.conf', () => readFileIntoProcessedArray(path.resolve(import.meta.dir, '../Source/domainset/reject_sukka.conf'))
  57. .then(setAddFromArrayCurried(domainSets)))
  58. ]);
  59. // eslint-disable-next-line sukka/no-single-return -- not single return
  60. return shouldStop;
  61. });
  62. if (shouldStop) {
  63. process.exit(1);
  64. }
  65. console.log(`Import ${domainSets.size} rules from Hosts / AdBlock Filter Rules & reject_sukka.conf!`);
  66. // Dedupe domainSets
  67. await span.traceChildAsync('dedupe from black keywords/suffixes', async (childSpan) => {
  68. /** Collect DOMAIN-KEYWORD from non_ip/reject.conf for deduplication */
  69. const domainKeywordsSet = new Set<string>();
  70. await childSpan.traceChildAsync('collect keywords/suffixes', async () => {
  71. for await (const line of readFileByLine(path.resolve(import.meta.dir, '../Source/non_ip/reject.conf'))) {
  72. const [type, value] = line.split(',');
  73. if (type === 'DOMAIN-KEYWORD') {
  74. domainKeywordsSet.add(value.trim());
  75. } else if (type === 'DOMAIN-SUFFIX') {
  76. domainSets.add(`.${value.trim()}`); // Add to domainSets for later deduplication
  77. }
  78. }
  79. });
  80. // Remove as many domains as possible from domainSets before creating trie
  81. SetSubstract(domainSets, filterRuleWhitelistDomainSets);
  82. // Perform kwfilter to remove as many domains as possible from domainSets before creating trie
  83. childSpan.traceChildSync('dedupe from black keywords', () => {
  84. const kwfilter = createKeywordFilter(domainKeywordsSet);
  85. for (const domain of domainSets) {
  86. // Remove keyword
  87. if (kwfilter(domain)) {
  88. domainSets.delete(domain);
  89. }
  90. }
  91. });
  92. });
  93. const trie = createTrie(domainSets, true, true);
  94. span.traceChildSync('dedupe from white suffixes', () => {
  95. filterRuleWhitelistDomainSets.forEach(suffix => {
  96. trie.whitelist(suffix);
  97. });
  98. });
  99. // Dedupe domainSets
  100. const dudupedDominArray = span.traceChildSync('dedupe from covered subdomain', () => domainDeduper(trie));
  101. console.log(`Final size ${dudupedDominArray.length}`);
  102. // Create reject stats
  103. const rejectDomainsStats: Array<[string, number]> = span
  104. .traceChild('create reject stats')
  105. .traceSyncFn(() => {
  106. const tldtsOpt = { allowPrivateDomains: false, detectIp: false, validateHostname: false };
  107. const statMap = dudupedDominArray.reduce<Map<string, number>>((acc, cur) => {
  108. const suffix = tldts.getDomain(cur, tldtsOpt);
  109. if (!suffix) return acc;
  110. if (acc.has(suffix)) {
  111. acc.set(suffix, acc.get(suffix)! + 1);
  112. } else {
  113. acc.set(suffix, 1);
  114. }
  115. return acc;
  116. }, new Map());
  117. return sort(Array.from(statMap.entries()).filter(a => a[1] > 9), (a, b) => (b[1] - a[1]) || a[0].localeCompare(b[0]));
  118. });
  119. const description = [
  120. ...SHARED_DESCRIPTION,
  121. '',
  122. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  123. '',
  124. 'Build from:',
  125. ...HOSTS.map(host => ` - ${host[0]}`),
  126. ...DOMAIN_LISTS.map(domainList => ` - ${domainList[0]}`),
  127. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`),
  128. ' - https://curbengh.github.io/phishing-filter/phishing-filter-hosts.txt',
  129. ' - https://phishing.army/download/phishing_army_blocklist.txt'
  130. ];
  131. return Promise.all([
  132. createRuleset(
  133. span,
  134. 'Sukka\'s Ruleset - Reject Base',
  135. description,
  136. new Date(),
  137. span.traceChildSync('sort reject domainset', () => sortDomains(dudupedDominArray)),
  138. 'domainset',
  139. path.resolve(import.meta.dir, '../List/domainset/reject.conf'),
  140. path.resolve(import.meta.dir, '../Clash/domainset/reject.txt')
  141. ),
  142. compareAndWriteFile(
  143. span,
  144. rejectDomainsStats.map(([domain, count]) => `${domain}${' '.repeat(100 - domain.length)}${count}`),
  145. path.resolve(import.meta.dir, '../Internal/reject-stats.txt')
  146. )
  147. ]);
  148. });
  149. if (import.meta.main) {
  150. buildRejectDomainSet();
  151. }