build-reject-domainset.ts 8.4 KB

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