build-reject-domainset.ts 7.3 KB

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