build-reject-domainset.ts 7.4 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 { getGorhillPublicSuffixPromise } from './lib/get-gorhill-publicsuffix';
  13. import * as tldts from 'tldts';
  14. import { SHARED_DESCRIPTION } from './lib/constants';
  15. import { getPhishingDomains } from './lib/get-phishing-domains';
  16. import * as SetHelpers from 'mnemonist/set';
  17. import { setAddFromArray } from './lib/set-add-from-array';
  18. export const buildRejectDomainSet = task(import.meta.path, async (span) => {
  19. const gorhill = await getGorhillPublicSuffixPromise();
  20. /** Whitelists */
  21. const filterRuleWhitelistDomainSets = new Set(PREDEFINED_WHITELIST);
  22. const domainSets = new Set<string>();
  23. let shouldStop = false;
  24. // Parse from AdGuard Filters
  25. await span
  26. .traceChild('download and process hosts / adblock filter rules')
  27. .traceAsyncFn(async (childSpan) => {
  28. await Promise.all([
  29. // Parse from remote hosts & domain lists
  30. ...HOSTS.map(entry => processHosts(childSpan, entry[0], entry[1], entry[2]).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. shouldStop = true;
  39. // we should not break here, as we want to see full matches from all data source
  40. }
  41. setAddFromArray(filterRuleWhitelistDomainSets, white);
  42. setAddFromArray(domainSets, black);
  43. })),
  44. ...([
  45. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exceptions.txt',
  46. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exclusions.txt'
  47. ].map(input => processFilterRules(childSpan, input).then(({ white, black }) => {
  48. setAddFromArray(filterRuleWhitelistDomainSets, white);
  49. setAddFromArray(filterRuleWhitelistDomainSets, black);
  50. }))),
  51. getPhishingDomains(childSpan).then(([purePhishingDomains, fullPhishingDomainSet]) => {
  52. SetHelpers.add(domainSets, fullPhishingDomainSet);
  53. setAddFromArray(domainSets, purePhishingDomains);
  54. }),
  55. childSpan.traceChild('process reject_sukka.conf').traceAsyncFn(async () => {
  56. setAddFromArray(domainSets, await readFileIntoProcessedArray(path.resolve(import.meta.dir, '../Source/domainset/reject_sukka.conf')));
  57. })
  58. ]);
  59. return shouldStop;
  60. });
  61. if (shouldStop) {
  62. process.exit(1);
  63. }
  64. let previousSize = domainSets.size;
  65. console.log(`Import ${previousSize} rules from Hosts / AdBlock Filter Rules & reject_sukka.conf!`);
  66. // Dedupe domainSets
  67. await span.traceChild('dedupe from black keywords/suffixes').traceAsyncFn(async () => {
  68. /** Collect DOMAIN-SUFFIX from non_ip/reject.conf for deduplication */
  69. const domainSuffixSet = new Set<string>();
  70. /** Collect DOMAIN-KEYWORD from non_ip/reject.conf for deduplication */
  71. const domainKeywordsSet = new Set<string>();
  72. for await (const line of readFileByLine(path.resolve(import.meta.dir, '../Source/non_ip/reject.conf'))) {
  73. const [type, keyword] = line.split(',');
  74. if (type === 'DOMAIN-KEYWORD') {
  75. domainKeywordsSet.add(keyword.trim());
  76. } else if (type === 'DOMAIN-SUFFIX') {
  77. domainSuffixSet.add(keyword.trim());
  78. }
  79. }
  80. const trie1 = createTrie(domainSets);
  81. domainSuffixSet.forEach(suffix => {
  82. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  83. });
  84. filterRuleWhitelistDomainSets.forEach(suffix => {
  85. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  86. if (suffix[0] === '.') {
  87. // handle case like removing `g.msn.com` due to white `.g.msn.com` (`@@||g.msn.com`)
  88. domainSets.delete(suffix.slice(1));
  89. } else {
  90. // If `g.msn.com` is whitelisted, then `.g.msn.com` should be removed from domain set
  91. domainSets.delete(`.${suffix}`);
  92. }
  93. });
  94. // remove pre-defined enforced blacklist from whitelist
  95. const kwfilter = createKeywordFilter(domainKeywordsSet);
  96. for (const domain of domainSets) {
  97. // Remove keyword
  98. if (kwfilter(domain)) {
  99. domainSets.delete(domain);
  100. }
  101. }
  102. console.log(`Deduped ${previousSize} - ${domainSets.size} = ${previousSize - domainSets.size} from black keywords and suffixes!`);
  103. });
  104. previousSize = domainSets.size;
  105. // Dedupe domainSets
  106. const dudupedDominArray = span.traceChild('dedupe from covered subdomain').traceSyncFn(() => domainDeduper(Array.from(domainSets)));
  107. console.log(`Deduped ${previousSize - dudupedDominArray.length} rules from covered subdomain!`);
  108. console.log(`Final size ${dudupedDominArray.length}`);
  109. // Create reject stats
  110. const rejectDomainsStats: Array<[string, number]> = span
  111. .traceChild('create reject stats')
  112. .traceSyncFn(() => Object.entries(
  113. dudupedDominArray.reduce<Record<string, number>>((acc, cur) => {
  114. const suffix = tldts.getDomain(cur, { allowPrivateDomains: false, detectIp: false, validateHostname: false });
  115. if (suffix) {
  116. acc[suffix] = (acc[suffix] || 0) + 1;
  117. }
  118. return acc;
  119. }, {})
  120. ).filter(a => a[1] > 5).sort((a, b) => (b[1] - a[1]) || a[0].localeCompare(b[0])));
  121. const description = [
  122. ...SHARED_DESCRIPTION,
  123. '',
  124. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  125. '',
  126. 'Build from:',
  127. ...HOSTS.map(host => ` - ${host[0]}`),
  128. ...DOMAIN_LISTS.map(domainList => ` - ${domainList[0]}`),
  129. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`),
  130. ' - https://curbengh.github.io/phishing-filter/phishing-filter-hosts.txt',
  131. ' - https://phishing.army/download/phishing_army_blocklist.txt'
  132. ];
  133. return Promise.all([
  134. createRuleset(
  135. span,
  136. 'Sukka\'s Ruleset - Reject Base',
  137. description,
  138. new Date(),
  139. span.traceChild('sort reject domainset').traceSyncFn(() => sortDomains(dudupedDominArray, gorhill)),
  140. 'domainset',
  141. path.resolve(import.meta.dir, '../List/domainset/reject.conf'),
  142. path.resolve(import.meta.dir, '../Clash/domainset/reject.txt')
  143. ),
  144. compareAndWriteFile(
  145. span,
  146. rejectDomainsStats.map(([domain, count]) => `${domain}${' '.repeat(100 - domain.length)}${count}`),
  147. path.resolve(import.meta.dir, '../List/internal/reject-stats.txt')
  148. ),
  149. Bun.write(
  150. path.resolve(import.meta.dir, '../List/domainset/reject_sukka.conf'),
  151. '# The file has been deprecated, its content has been merged into the main `reject` domainset.\n'
  152. )
  153. ]);
  154. });
  155. if (import.meta.main) {
  156. buildRejectDomainSet();
  157. }