build-reject-domainset.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. // @ts-check
  2. const fs = require('fs');
  3. const fse = require('fs-extra');
  4. const { resolve: pathResolve } = require('path');
  5. const tldts = require('tldts');
  6. const { processHosts, processFilterRules } = require('./lib/parse-filter');
  7. const Trie = require('./lib/trie');
  8. const { HOSTS, ADGUARD_FILTERS, PREDEFINED_WHITELIST, PREDEFINED_ENFORCED_BACKLIST } = require('./lib/reject-data-source');
  9. const { createRuleset } = require('./lib/create-file');
  10. const { processLine } = require('./lib/process-line');
  11. const { domainDeduper } = require('./lib/domain-deduper');
  12. const createKeywordFilter = require('./lib/aho-corasick');
  13. const { readFileByLine } = require('./lib/fetch-remote-text-by-line');
  14. const domainSorter = require('./lib/stable-sort-domain');
  15. /** Whitelists */
  16. const filterRuleWhitelistDomainSets = new Set(PREDEFINED_WHITELIST);
  17. /** @type {Set<string>} Dedupe domains inclued by DOMAIN-KEYWORD */
  18. const domainKeywordsSet = new Set();
  19. /** @type {Set<string>} Dedupe domains included by DOMAIN-SUFFIX */
  20. const domainSuffixSet = new Set();
  21. (async () => {
  22. /** @type Set<string> */
  23. const domainSets = new Set();
  24. // Parse from AdGuard Filters
  25. console.time('* Download and process Hosts / AdBlock Filter Rules');
  26. let shouldStop = false;
  27. await Promise.all([
  28. // Parse from remote hosts & domain lists
  29. ...HOSTS.map(entry => processHosts(entry[0], entry[1]).then(hosts => {
  30. hosts.forEach(host => {
  31. if (host) {
  32. domainSets.add(host);
  33. }
  34. });
  35. })),
  36. ...ADGUARD_FILTERS.map(input => {
  37. const promise = typeof input === 'string'
  38. ? processFilterRules(input, undefined, false)
  39. : processFilterRules(input[0], input[1] || undefined, input[2] ?? false);
  40. return promise.then((i) => {
  41. if (i) {
  42. const { white, black, foundDebugDomain } = i;
  43. if (foundDebugDomain) {
  44. shouldStop = true;
  45. // we should not break here, as we want to see full matches from all data source
  46. }
  47. white.forEach(i => filterRuleWhitelistDomainSets.add(i));
  48. black.forEach(i => domainSets.add(i));
  49. } else {
  50. process.exitCode = 1;
  51. throw new Error('Failed to process AdGuard Filter Rules!');
  52. }
  53. });
  54. }),
  55. ...([
  56. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exceptions.txt',
  57. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exclusions.txt'
  58. ].map(input => processFilterRules(input).then((i) => {
  59. if (i) {
  60. const { white, black } = i;
  61. white.forEach(i => {
  62. filterRuleWhitelistDomainSets.add(i);
  63. });
  64. black.forEach(i => {
  65. filterRuleWhitelistDomainSets.add(i);
  66. });
  67. } else {
  68. process.exitCode = 1;
  69. throw new Error('Failed to process AdGuard Filter Rules!');
  70. }
  71. })))
  72. ]);
  73. // remove pre-defined enforced blacklist from whitelist
  74. const trie0 = Trie.from(filterRuleWhitelistDomainSets);
  75. PREDEFINED_ENFORCED_BACKLIST.forEach(enforcedBlack => {
  76. trie0.find(enforcedBlack).forEach(found => filterRuleWhitelistDomainSets.delete(found));
  77. });
  78. console.timeEnd('* Download and process Hosts / AdBlock Filter Rules');
  79. if (shouldStop) {
  80. // eslint-disable-next-line n/no-process-exit -- force stop
  81. process.exit(1);
  82. }
  83. let previousSize = domainSets.size;
  84. console.log(`Import ${previousSize} rules from Hosts / AdBlock Filter Rules!`);
  85. for await (const line of readFileByLine(pathResolve(__dirname, '../Source/domainset/reject_sukka.conf'))) {
  86. const l = processLine(line);
  87. if (l) {
  88. domainSets.add(l);
  89. }
  90. }
  91. previousSize = domainSets.size - previousSize;
  92. console.log(`Import ${previousSize} rules from reject_sukka.conf!`);
  93. for await (const line of readFileByLine(pathResolve(__dirname, '../Source/non_ip/reject.conf'))) {
  94. if (line.startsWith('DOMAIN-KEYWORD')) {
  95. const [, ...keywords] = line.split(',');
  96. domainKeywordsSet.add(keywords.join(',').trim());
  97. } else if (line.startsWith('DOMAIN-SUFFIX')) {
  98. const [, ...keywords] = line.split(',');
  99. domainSuffixSet.add(keywords.join(',').trim());
  100. }
  101. }
  102. for await (const line of readFileByLine(pathResolve(__dirname, '../List/domainset/reject_phishing.conf'))) {
  103. const l = processLine(line);
  104. if (l && l[0] === '.') {
  105. domainSuffixSet.add(l.slice(1));
  106. }
  107. }
  108. console.log(`Import ${domainKeywordsSet.size} black keywords and ${domainSuffixSet.size} black suffixes!`);
  109. previousSize = domainSets.size;
  110. // Dedupe domainSets
  111. console.log(`Start deduping from black keywords/suffixes! (${previousSize})`);
  112. console.time('* Dedupe from black keywords/suffixes');
  113. const kwfilter = createKeywordFilter(Array.from(domainKeywordsSet));
  114. const trie1 = Trie.from(domainSets);
  115. domainSuffixSet.forEach(suffix => {
  116. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  117. });
  118. filterRuleWhitelistDomainSets.forEach(suffix => {
  119. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  120. });
  121. // Build whitelist trie, to handle case like removing `g.msn.com` due to white `.g.msn.com` (`@@||g.msn.com`)
  122. const trieWhite = Trie.from(filterRuleWhitelistDomainSets);
  123. for (const domain of domainSets) {
  124. if (domain[0] === '.') {
  125. if (trieWhite.contains(domain)) {
  126. domainSets.delete(domain);
  127. continue;
  128. }
  129. } else if (trieWhite.has(`.${domain}`)) {
  130. domainSets.delete(domain);
  131. continue;
  132. }
  133. // Remove keyword
  134. if (kwfilter.search(domain)) {
  135. domainSets.delete(domain);
  136. }
  137. }
  138. console.timeEnd('* Dedupe from black keywords/suffixes');
  139. console.log(`Deduped ${previousSize} - ${domainSets.size} = ${previousSize - domainSets.size} from black keywords and suffixes!`);
  140. previousSize = domainSets.size;
  141. // Dedupe domainSets
  142. console.log(`Start deduping! (${previousSize})`);
  143. const START_TIME = Date.now();
  144. const dudupedDominArray = domainDeduper(Array.from(domainSets));
  145. console.log(`* Dedupe from covered subdomain - ${(Date.now() - START_TIME) / 1000}s`);
  146. console.log(`Deduped ${previousSize - dudupedDominArray.length} rules!`);
  147. /** @type {Record<string, number>} */
  148. const rejectDomainsStats = dudupedDominArray.reduce((acc, cur) => {
  149. const suffix = tldts.getDomain(cur, { allowPrivateDomains: false });
  150. if (suffix) {
  151. acc[suffix] = (acc[suffix] ?? 0) + 1;
  152. }
  153. return acc;
  154. }, {});
  155. const description = [
  156. 'License: AGPL 3.0',
  157. 'Homepage: https://ruleset.skk.moe',
  158. 'GitHub: https://github.com/SukkaW/Surge',
  159. '',
  160. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  161. '',
  162. 'Build from:',
  163. ...HOSTS.map(host => ` - ${host[0]}`),
  164. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`)
  165. ];
  166. const domainset = dudupedDominArray.sort(domainSorter);
  167. await Promise.all([
  168. ...createRuleset(
  169. 'Sukka\'s Ruleset - Reject Base',
  170. description,
  171. new Date(),
  172. domainset,
  173. 'domainset',
  174. pathResolve(__dirname, '../List/domainset/reject.conf'),
  175. pathResolve(__dirname, '../Clash/domainset/reject.txt')
  176. ),
  177. fs.promises.writeFile(
  178. pathResolve(__dirname, '../List/internal/reject-stats.txt'),
  179. Object.entries(rejectDomainsStats)
  180. .filter(a => a[1] > 1)
  181. .sort((a, b) => {
  182. const t = b[1] - a[1];
  183. if (t === 0) {
  184. return a[0].localeCompare(b[0]);
  185. }
  186. return t;
  187. })
  188. .map(([domain, count]) => `${domain}${' '.repeat(100 - domain.length)}${count}`)
  189. .join('\n')
  190. ),
  191. // Copy reject_sukka.conf for backward compatibility
  192. fse.copy(pathResolve(__dirname, '../Source/domainset/reject_sukka.conf'), pathResolve(__dirname, '../List/domainset/reject_sukka.conf'))
  193. ]);
  194. })();