build-reject-domainset.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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, PREDEFINED_ENFORCED_BACKLIST, DOMAIN_LISTS } from './lib/reject-data-source';
  6. import { createRuleset, compareAndWriteFile } from './lib/create-file';
  7. import { processLine } from './lib/process-line';
  8. import { domainDeduper } from './lib/domain-deduper';
  9. import createKeywordFilter from './lib/aho-corasick';
  10. import { readFileByLine } from './lib/fetch-text-by-line';
  11. import { sortDomains } from './lib/stable-sort-domain';
  12. import { traceSync, task, traceAsync } from './lib/trace-runner';
  13. import { getGorhillPublicSuffixPromise } from './lib/get-gorhill-publicsuffix';
  14. import * as tldts from 'tldts';
  15. import { SHARED_DESCRIPTION } from './lib/constants';
  16. import { getPhishingDomains } from './lib/get-phishing-domains';
  17. import * as SetHelpers from 'mnemonist/set';
  18. import { setAddFromArray } from './lib/set-add-from-array';
  19. export const buildRejectDomainSet = task(import.meta.path, async () => {
  20. /** Whitelists */
  21. const filterRuleWhitelistDomainSets = new Set(PREDEFINED_WHITELIST);
  22. const domainSets = new Set<string>();
  23. // Parse from AdGuard Filters
  24. const [gorhill, shouldStop] = await traceAsync('* Download and process Hosts / AdBlock Filter Rules', async () => {
  25. let shouldStop = false;
  26. const [gorhill] = await Promise.all([
  27. getGorhillPublicSuffixPromise(),
  28. // Parse from remote hosts & domain lists
  29. ...HOSTS.map(entry => processHosts(entry[0], entry[1], entry[2]).then(hosts => {
  30. SetHelpers.add(domainSets, hosts);
  31. })),
  32. ...DOMAIN_LISTS.map(entry => processDomainLists(entry[0], entry[1], entry[2])),
  33. ...ADGUARD_FILTERS.map(input => {
  34. const promise = typeof input === 'string'
  35. ? processFilterRules(input)
  36. : processFilterRules(input[0], input[1], input[2]);
  37. return promise.then(({ white, black, foundDebugDomain }) => {
  38. if (foundDebugDomain) {
  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. ...([
  47. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exceptions.txt',
  48. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exclusions.txt'
  49. ].map(input => processFilterRules(input).then(({ white, black }) => {
  50. setAddFromArray(filterRuleWhitelistDomainSets, white);
  51. setAddFromArray(filterRuleWhitelistDomainSets, black);
  52. }))),
  53. getPhishingDomains().then(([purePhishingDomains, fullPhishingDomainSet]) => {
  54. SetHelpers.add(domainSets, fullPhishingDomainSet);
  55. setAddFromArray(domainSets, purePhishingDomains);
  56. }),
  57. (async () => {
  58. for await (const l of readFileByLine(path.resolve(import.meta.dir, '../Source/domainset/reject_sukka.conf'))) {
  59. const line = processLine(l);
  60. if (line) {
  61. domainSets.add(line);
  62. }
  63. }
  64. })()
  65. ]);
  66. // remove pre-defined enforced blacklist from whitelist
  67. const trie0 = createTrie(filterRuleWhitelistDomainSets);
  68. for (let i = 0, len1 = PREDEFINED_ENFORCED_BACKLIST.length; i < len1; i++) {
  69. const enforcedBlack = PREDEFINED_ENFORCED_BACKLIST[i];
  70. const found = trie0.find(enforcedBlack);
  71. for (let j = 0, len2 = found.length; j < len2; j++) {
  72. filterRuleWhitelistDomainSets.delete(found[j]);
  73. }
  74. }
  75. return [gorhill, shouldStop] as const;
  76. });
  77. if (shouldStop) {
  78. process.exit(1);
  79. }
  80. let previousSize = domainSets.size;
  81. console.log(`Import ${previousSize} rules from Hosts / AdBlock Filter Rules & reject_sukka.conf!`);
  82. // Dedupe domainSets
  83. await traceAsync('* Dedupe from black keywords/suffixes', async () => {
  84. /** Collect DOMAIN-SUFFIX from non_ip/reject.conf for deduplication */
  85. const domainSuffixSet = new Set<string>();
  86. /** Collect DOMAIN-KEYWORD from non_ip/reject.conf for deduplication */
  87. const domainKeywordsSet = new Set<string>();
  88. for await (const line of readFileByLine(path.resolve(import.meta.dir, '../Source/non_ip/reject.conf'))) {
  89. const [type, keyword] = line.split(',');
  90. if (type === 'DOMAIN-KEYWORD') {
  91. domainKeywordsSet.add(keyword.trim());
  92. } else if (type === 'DOMAIN-SUFFIX') {
  93. domainSuffixSet.add(keyword.trim());
  94. }
  95. }
  96. const trie1 = createTrie(domainSets);
  97. domainSuffixSet.forEach(suffix => {
  98. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  99. });
  100. filterRuleWhitelistDomainSets.forEach(suffix => {
  101. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  102. });
  103. // remove pre-defined enforced blacklist from whitelist
  104. const kwfilter = createKeywordFilter(domainKeywordsSet);
  105. // Build whitelist trie, to handle case like removing `g.msn.com` due to white `.g.msn.com` (`@@||g.msn.com`)
  106. const trieWhite = createTrie(filterRuleWhitelistDomainSets);
  107. for (const domain of domainSets) {
  108. if (domain[0] === '.') {
  109. if (trieWhite.contains(domain)) {
  110. domainSets.delete(domain);
  111. continue;
  112. }
  113. } else if (trieWhite.has(`.${domain}`)) {
  114. domainSets.delete(domain);
  115. continue;
  116. }
  117. // Remove keyword
  118. if (kwfilter.search(domain)) {
  119. domainSets.delete(domain);
  120. }
  121. }
  122. console.log(`Deduped ${previousSize} - ${domainSets.size} = ${previousSize - domainSets.size} from black keywords and suffixes!`);
  123. });
  124. previousSize = domainSets.size;
  125. // Dedupe domainSets
  126. const dudupedDominArray = traceSync('* Dedupe from covered subdomain', () => domainDeduper(Array.from(domainSets)));
  127. console.log(`Deduped ${previousSize - dudupedDominArray.length} rules from covered subdomain!`);
  128. console.log(`Final size ${dudupedDominArray.length}`);
  129. // Create reject stats
  130. const rejectDomainsStats: Array<[string, number]> = traceSync(
  131. '* Collect reject domain stats',
  132. () => Object.entries(
  133. dudupedDominArray.reduce<Record<string, number>>((acc, cur) => {
  134. const suffix = tldts.getDomain(cur, { allowPrivateDomains: false, detectIp: false, validateHostname: false });
  135. if (suffix) {
  136. acc[suffix] = (acc[suffix] || 0) + 1;
  137. }
  138. return acc;
  139. }, {})
  140. ).filter(a => a[1] > 10).sort((a, b) => {
  141. const t = b[1] - a[1];
  142. if (t !== 0) {
  143. return t;
  144. }
  145. return a[0].localeCompare(b[0]);
  146. })
  147. );
  148. const description = [
  149. ...SHARED_DESCRIPTION,
  150. '',
  151. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  152. '',
  153. 'Build from:',
  154. ...HOSTS.map(host => ` - ${host[0]}`),
  155. ...DOMAIN_LISTS.map(domainList => ` - ${domainList[0]}`),
  156. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`),
  157. ' - https://curbengh.github.io/phishing-filter/phishing-filter-hosts.txt',
  158. ' - https://phishing.army/download/phishing_army_blocklist.txt'
  159. ];
  160. return Promise.all([
  161. ...createRuleset(
  162. 'Sukka\'s Ruleset - Reject Base',
  163. description,
  164. new Date(),
  165. traceSync('* Sort reject domainset', () => sortDomains(dudupedDominArray, gorhill)),
  166. 'domainset',
  167. path.resolve(import.meta.dir, '../List/domainset/reject.conf'),
  168. path.resolve(import.meta.dir, '../Clash/domainset/reject.txt')
  169. ),
  170. compareAndWriteFile(
  171. rejectDomainsStats.map(([domain, count]) => `${domain}${' '.repeat(100 - domain.length)}${count}`),
  172. path.resolve(import.meta.dir, '../List/internal/reject-stats.txt')
  173. ),
  174. Bun.write(
  175. path.resolve(import.meta.dir, '../List/domainset/reject_sukka.conf'),
  176. '# The file has been deprecated, its content has been merged into the main `reject` domainset.\n'
  177. )
  178. ]);
  179. });
  180. if (import.meta.main) {
  181. buildRejectDomainSet();
  182. }