build-reject-domainset.ts 8.1 KB

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