build-reject-domainset.js 8.1 KB

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