build-reject-domainset.js 8.4 KB

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