build-reject-domainset.js 8.1 KB

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