build-reject-domainset.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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 * as SetHelpers 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 => SetHelpers.add(domainSets, hosts))),
  31. ...DOMAIN_LISTS.map(entry => processDomainLists(childSpan, entry[0], entry[1], entry[2]).then(hosts => SetHelpers.add(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. SetHelpers.add(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. SetHelpers.subtract(domainSets, filterRuleWhitelistDomainSets);
  84. childSpan.traceChildSync('dedupe from white suffixes', () => {
  85. const trie = createTrie(domainSets);
  86. filterRuleWhitelistDomainSets.forEach(suffix => {
  87. trie.substractSetInPlaceFromFound(suffix, domainSets);
  88. if (suffix[0] === '.') {
  89. domainSets.delete(suffix.slice(1));
  90. domainSets.delete(suffix);
  91. } else {
  92. domainSets.delete(`.${suffix}`);
  93. domainSets.delete(suffix);
  94. }
  95. });
  96. });
  97. childSpan.traceChildSync('dedupe from black keywords', () => {
  98. const kwfilter = createKeywordFilter(domainKeywordsSet);
  99. for (const domain of domainSets) {
  100. // Remove keyword
  101. if (kwfilter(domain)) {
  102. domainSets.delete(domain);
  103. }
  104. }
  105. });
  106. console.log(`Deduped ${previousSize} - ${domainSets.size} = ${previousSize - domainSets.size} from black keywords and suffixes!`);
  107. });
  108. previousSize = domainSets.size;
  109. // Dedupe domainSets
  110. const dudupedDominArray = span.traceChildSync('dedupe from covered subdomain', () => domainDeduper(Array.from(domainSets)));
  111. console.log(`Deduped ${previousSize - dudupedDominArray.length} rules from covered subdomain!`);
  112. console.log(`Final size ${dudupedDominArray.length}`);
  113. // Create reject stats
  114. const rejectDomainsStats: Array<[string, number]> = span
  115. .traceChild('create reject stats')
  116. .traceSyncFn(() => {
  117. const tldtsOpt = { allowPrivateDomains: false, detectIp: false, validateHostname: false };
  118. const statMap = dudupedDominArray.reduce<Map<string, number>>((acc, cur) => {
  119. const suffix = tldts.getDomain(cur, tldtsOpt);
  120. if (!suffix) return acc;
  121. if (acc.has(suffix)) {
  122. acc.set(suffix, acc.get(suffix)! + 1);
  123. } else {
  124. acc.set(suffix, 1);
  125. }
  126. return acc;
  127. }, new Map());
  128. return sort(Array.from(statMap.entries()).filter(a => a[1] > 9), (a, b) => (b[1] - a[1]) || a[0].localeCompare(b[0]));
  129. });
  130. const description = [
  131. ...SHARED_DESCRIPTION,
  132. '',
  133. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  134. '',
  135. 'Build from:',
  136. ...HOSTS.map(host => ` - ${host[0]}`),
  137. ...DOMAIN_LISTS.map(domainList => ` - ${domainList[0]}`),
  138. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`),
  139. ' - https://curbengh.github.io/phishing-filter/phishing-filter-hosts.txt',
  140. ' - https://phishing.army/download/phishing_army_blocklist.txt'
  141. ];
  142. return Promise.all([
  143. createRuleset(
  144. span,
  145. 'Sukka\'s Ruleset - Reject Base',
  146. description,
  147. new Date(),
  148. span.traceChildSync('sort reject domainset', () => sortDomains(dudupedDominArray)),
  149. 'domainset',
  150. path.resolve(import.meta.dir, '../List/domainset/reject.conf'),
  151. path.resolve(import.meta.dir, '../Clash/domainset/reject.txt')
  152. ),
  153. compareAndWriteFile(
  154. span,
  155. rejectDomainsStats.map(([domain, count]) => `${domain}${' '.repeat(100 - domain.length)}${count}`),
  156. path.resolve(import.meta.dir, '../Internal/reject-stats.txt')
  157. )
  158. ]);
  159. });
  160. if (import.meta.main) {
  161. buildRejectDomainSet();
  162. }