build-reject-domainset.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. // @ts-check
  2. import fsp from 'fs/promises';
  3. import path from 'path';
  4. import { processHosts, processFilterRules } from './lib/parse-filter';
  5. import { createTrie } from './lib/trie';
  6. import { HOSTS, ADGUARD_FILTERS, PREDEFINED_WHITELIST, PREDEFINED_ENFORCED_BACKLIST } from './lib/reject-data-source';
  7. import { createRuleset, compareAndWriteFile } from './lib/create-file';
  8. import { processLine } from './lib/process-line';
  9. import { domainDeduper } from './lib/domain-deduper';
  10. import createKeywordFilter from './lib/aho-corasick';
  11. import { readFileByLine } from './lib/fetch-text-by-line';
  12. import { createDomainSorter } from './lib/stable-sort-domain';
  13. import { traceSync, task, traceAsync } from './lib/trace-runner';
  14. import { getGorhillPublicSuffixPromise } from './lib/get-gorhill-publicsuffix';
  15. import * as tldts from 'tldts';
  16. import { SHARED_DESCRIPTION } from './lib/constants';
  17. import { getPhishingDomains } from './lib/get-phishing-domains';
  18. export const buildRejectDomainSet = task(import.meta.path, async () => {
  19. /** Whitelists */
  20. const filterRuleWhitelistDomainSets = new Set(PREDEFINED_WHITELIST);
  21. const domainKeywordsSet = new Set<string>();
  22. const domainSuffixSet = new Set<string>();
  23. const domainSets = new Set<string>();
  24. // Parse from AdGuard Filters
  25. const [gorhill, shouldStop] = await traceAsync('* Download and process Hosts / AdBlock Filter Rules', async () => {
  26. let shouldStop = false;
  27. const [gorhill] = await Promise.all([
  28. getGorhillPublicSuffixPromise(),
  29. // Parse from remote hosts & domain lists
  30. ...HOSTS.map(entry => processHosts(entry[0], entry[1]).then(hosts => {
  31. hosts.forEach(host => {
  32. domainSets.add(host);
  33. });
  34. })),
  35. ...ADGUARD_FILTERS.map(input => {
  36. const promise = typeof input === 'string'
  37. ? processFilterRules(input)
  38. : processFilterRules(input[0], input[1]);
  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. white.forEach(i => filterRuleWhitelistDomainSets.add(i));
  45. black.forEach(i => domainSets.add(i));
  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(input).then(({ white, black }) => {
  52. white.forEach(i => filterRuleWhitelistDomainSets.add(i));
  53. black.forEach(i => filterRuleWhitelistDomainSets.add(i));
  54. }))),
  55. getPhishingDomains().then(([purePhishingDomains, fullDomainSet]) => {
  56. fullDomainSet.forEach(host => {
  57. if (host) {
  58. domainSets.add(host);
  59. }
  60. });
  61. purePhishingDomains.forEach(suffix => domainSets.add(`.${suffix}`));
  62. }),
  63. (async () => {
  64. for await (const line of readFileByLine(path.resolve(import.meta.dir, '../Source/domainset/reject_sukka.conf'))) {
  65. const l = processLine(line);
  66. if (l) {
  67. domainSets.add(l);
  68. }
  69. }
  70. })()
  71. ]);
  72. // remove pre-defined enforced blacklist from whitelist
  73. const trie0 = createTrie(filterRuleWhitelistDomainSets);
  74. PREDEFINED_ENFORCED_BACKLIST.forEach(enforcedBlack => {
  75. trie0.find(enforcedBlack).forEach(found => filterRuleWhitelistDomainSets.delete(found));
  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. for await (const line of readFileByLine(path.resolve(import.meta.dir, '../Source/non_ip/reject.conf'))) {
  85. const [type, keyword] = line.split(',');
  86. if (type === 'DOMAIN-KEYWORD') {
  87. domainKeywordsSet.add(keyword.trim());
  88. } else if (type === 'DOMAIN-SUFFIX') {
  89. domainSuffixSet.add(keyword.trim());
  90. }
  91. }
  92. console.log(`Import ${domainKeywordsSet.size} black keywords and ${domainSuffixSet.size} black suffixes!`);
  93. previousSize = domainSets.size;
  94. // Dedupe domainSets
  95. traceSync('* Dedupe from black keywords/suffixes', () => {
  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!`);
  128. // Create reject stats
  129. const rejectDomainsStats: Array<[string, number]> = traceSync(
  130. '* Collect reject domain stats',
  131. () => Object.entries(
  132. dudupedDominArray.reduce<Record<string, number>>((acc, cur) => {
  133. const suffix = tldts.getDomain(cur, { allowPrivateDomains: false, detectIp: false });
  134. if (suffix) {
  135. acc[suffix] = (acc[suffix] ?? 0) + 1;
  136. }
  137. return acc;
  138. }, {})
  139. ).filter(a => a[1] > 10).sort((a, b) => {
  140. const t = b[1] - a[1];
  141. if (t !== 0) {
  142. return t;
  143. }
  144. return a[0].localeCompare(b[0]);
  145. })
  146. );
  147. const description = [
  148. ...SHARED_DESCRIPTION,
  149. '',
  150. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  151. '',
  152. 'Build from:',
  153. ...HOSTS.map(host => ` - ${host[0]}`),
  154. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`)
  155. ];
  156. return Promise.all([
  157. ...createRuleset(
  158. 'Sukka\'s Ruleset - Reject Base',
  159. description,
  160. new Date(),
  161. traceSync('* Sort reject domainset', () => dudupedDominArray.sort(createDomainSorter(gorhill))),
  162. 'domainset',
  163. path.resolve(import.meta.dir, '../List/domainset/reject.conf'),
  164. path.resolve(import.meta.dir, '../Clash/domainset/reject.txt')
  165. ),
  166. compareAndWriteFile(
  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. }