build-reject-domainset.ts 7.8 KB

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