build-reject-domainset.ts 7.3 KB

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