build-reject-domainset.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. import * as tldts from 'tldts';
  13. import { SHARED_DESCRIPTION } from './lib/constants';
  14. import { getPhishingDomains } from './lib/get-phishing-domains';
  15. import { add as SetAdd, subtract as SetSubstract } from 'mnemonist/set';
  16. import { setAddFromArray } from './lib/set-add-from-array';
  17. import { sort } from './lib/timsort';
  18. export const buildRejectDomainSet = task(import.meta.path, async (span) => {
  19. /** Whitelists */
  20. const filterRuleWhitelistDomainSets = new Set(PREDEFINED_WHITELIST);
  21. const domainSets = new Set<string>();
  22. // Parse from AdGuard Filters
  23. const shouldStop = await span
  24. .traceChild('download and process hosts / adblock filter rules')
  25. .traceAsyncFn(async (childSpan) => {
  26. // eslint-disable-next-line sukka/no-single-return -- not single return
  27. let shouldStop = false;
  28. await Promise.all([
  29. // Parse from remote hosts & domain lists
  30. ...HOSTS.map(entry => processHosts(childSpan, entry[0], entry[1], entry[2], entry[3]).then(hosts => SetAdd(domainSets, hosts))),
  31. ...DOMAIN_LISTS.map(entry => processDomainLists(childSpan, entry[0], entry[1], entry[2]).then(hosts => SetAdd(domainSets, hosts))),
  32. ...ADGUARD_FILTERS.map(input => (
  33. typeof input === 'string'
  34. ? processFilterRules(childSpan, input)
  35. : processFilterRules(childSpan, input[0], input[1], input[2])
  36. ).then(({ white, black, foundDebugDomain }) => {
  37. if (foundDebugDomain) {
  38. // eslint-disable-next-line sukka/no-single-return -- not single return
  39. shouldStop = true;
  40. // we should not break here, as we want to see full matches from all data source
  41. }
  42. setAddFromArray(filterRuleWhitelistDomainSets, white);
  43. setAddFromArray(domainSets, black);
  44. })),
  45. ...([
  46. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exceptions.txt',
  47. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exclusions.txt'
  48. ].map(input => processFilterRules(childSpan, input).then(({ white, black }) => {
  49. setAddFromArray(filterRuleWhitelistDomainSets, white);
  50. setAddFromArray(filterRuleWhitelistDomainSets, black);
  51. }))),
  52. getPhishingDomains(childSpan).then(([purePhishingDomains, fullPhishingDomainSet]) => {
  53. SetAdd(domainSets, fullPhishingDomainSet);
  54. setAddFromArray(domainSets, purePhishingDomains);
  55. }),
  56. childSpan.traceChildAsync('process reject_sukka.conf', async () => {
  57. setAddFromArray(domainSets, await readFileIntoProcessedArray(path.resolve(import.meta.dir, '../Source/domainset/reject_sukka.conf')));
  58. })
  59. ]);
  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. // Remove as many domains as possible from domainSets before creating trie
  82. SetSubstract(domainSets, filterRuleWhitelistDomainSets);
  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 = createTrie(domainSets, true, true);
  95. span.traceChildSync('dedupe from white suffixes', () => {
  96. filterRuleWhitelistDomainSets.forEach(suffix => {
  97. trie.whitelist(suffix);
  98. });
  99. });
  100. // Dedupe domainSets
  101. const dudupedDominArray = span.traceChildSync('dedupe from covered subdomain', () => domainDeduper(trie));
  102. console.log(`Final size ${dudupedDominArray.length}`);
  103. // Create reject stats
  104. const rejectDomainsStats: Array<[string, number]> = span
  105. .traceChild('create reject stats')
  106. .traceSyncFn(() => {
  107. const tldtsOpt = { allowPrivateDomains: false, detectIp: false, validateHostname: false };
  108. const statMap = dudupedDominArray.reduce<Map<string, number>>((acc, cur) => {
  109. const suffix = tldts.getDomain(cur, tldtsOpt);
  110. if (!suffix) return acc;
  111. if (acc.has(suffix)) {
  112. acc.set(suffix, acc.get(suffix)! + 1);
  113. } else {
  114. acc.set(suffix, 1);
  115. }
  116. return acc;
  117. }, new Map());
  118. return sort(Array.from(statMap.entries()).filter(a => a[1] > 9), (a, b) => (b[1] - a[1]) || a[0].localeCompare(b[0]));
  119. });
  120. const description = [
  121. ...SHARED_DESCRIPTION,
  122. '',
  123. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  124. '',
  125. 'Build from:',
  126. ...HOSTS.map(host => ` - ${host[0]}`),
  127. ...DOMAIN_LISTS.map(domainList => ` - ${domainList[0]}`),
  128. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`),
  129. ' - https://curbengh.github.io/phishing-filter/phishing-filter-hosts.txt',
  130. ' - https://phishing.army/download/phishing_army_blocklist.txt'
  131. ];
  132. return Promise.all([
  133. createRuleset(
  134. span,
  135. 'Sukka\'s Ruleset - Reject Base',
  136. description,
  137. new Date(),
  138. span.traceChildSync('sort reject domainset', () => sortDomains(dudupedDominArray)),
  139. 'domainset',
  140. path.resolve(import.meta.dir, '../List/domainset/reject.conf'),
  141. path.resolve(import.meta.dir, '../Clash/domainset/reject.txt')
  142. ),
  143. compareAndWriteFile(
  144. span,
  145. rejectDomainsStats.map(([domain, count]) => `${domain}${' '.repeat(100 - domain.length)}${count}`),
  146. path.resolve(import.meta.dir, '../Internal/reject-stats.txt')
  147. )
  148. ]);
  149. });
  150. if (import.meta.main) {
  151. buildRejectDomainSet();
  152. }