build-reject-domainset.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. // @ts-check
  2. const fs = require('fs');
  3. const fse = require('fs-extra');
  4. const { resolve: pathResolve } = require('path');
  5. const { processHosts, processFilterRules } = require('./lib/parse-filter');
  6. const { getDomain } = require('tldts');
  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. /** 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. const rl1 = readFileByLine(pathResolve(__dirname, '../Source/domainset/reject_sukka.conf'));
  96. for await (const line of rl1) {
  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. const rl2 = readFileByLine(pathResolve(__dirname, '../List/non_ip/reject.conf'));
  105. for await (const line of rl2) {
  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. const rl3 = readFileByLine(pathResolve(__dirname, '../List/domainset/reject_phishing.conf'));
  115. for await (const line of rl3) {
  116. const l = processLine(line);
  117. if (l && l[0] === '.') {
  118. domainSuffixSet.add(l.slice(1));
  119. }
  120. }
  121. console.log(`Import ${domainKeywordsSet.size} black keywords and ${domainSuffixSet.size} black suffixes!`);
  122. previousSize = domainSets.size;
  123. // Dedupe domainSets
  124. console.log(`Start deduping from black keywords/suffixes! (${previousSize})`);
  125. console.time('* Dedupe from black keywords/suffixes');
  126. const kwfilter = createKeywordFilter(Array.from(domainKeywordsSet));
  127. const trie1 = Trie.from(Array.from(domainSets));
  128. domainSuffixSet.forEach(suffix => {
  129. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  130. });
  131. filterRuleWhitelistDomainSets.forEach(suffix => {
  132. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  133. });
  134. // Build whitelist trie, to handle case like removing `g.msn.com` due to white `.g.msn.com` (`@@||g.msn.com`)
  135. const trieWhite = Trie.from(Array.from(filterRuleWhitelistDomainSets));
  136. for (const domain of domainSets) {
  137. if (domain[0] === '.') {
  138. if (trieWhite.contains(domain)) {
  139. domainSets.delete(domain);
  140. continue;
  141. }
  142. } else if (trieWhite.has(`.${domain}`)) {
  143. domainSets.delete(domain);
  144. continue;
  145. }
  146. // Remove keyword
  147. if (kwfilter.search(domain)) {
  148. domainSets.delete(domain);
  149. }
  150. }
  151. console.timeEnd('* Dedupe from black keywords/suffixes');
  152. console.log(`Deduped ${previousSize} - ${domainSets.size} = ${previousSize - domainSets.size} from black keywords and suffixes!`);
  153. previousSize = domainSets.size;
  154. // Dedupe domainSets
  155. console.log(`Start deduping! (${previousSize})`);
  156. const START_TIME = Date.now();
  157. const dudupedDominArray = domainDeduper(Array.from(domainSets));
  158. console.log(`* Dedupe from covered subdomain - ${(Date.now() - START_TIME) / 1000}s`);
  159. console.log(`Deduped ${previousSize - dudupedDominArray.length} rules!`);
  160. console.time('* Write reject.conf');
  161. /** @type {Record<string, number>} */
  162. const rejectDomainsStats = {};
  163. const sorter = (a, b) => {
  164. if (a.domain > b.domain) {
  165. return 1;
  166. }
  167. if (a.domain < b.domain) {
  168. return -1;
  169. }
  170. if (a.v > b.v) {
  171. return 1;
  172. }
  173. if (a.v < b.v) {
  174. return -1;
  175. }
  176. return 0;
  177. };
  178. const sortedDomainSets = dudupedDominArray
  179. .map((v) => {
  180. const domain = getDomain(v.charCodeAt(0) === 46 ? v.slice(1) : v) || v;
  181. rejectDomainsStats[domain] = (rejectDomainsStats[domain] || 0) + 1;
  182. return { v, domain };
  183. })
  184. .sort(sorter)
  185. .map((i) => i.v);
  186. await compareAndWriteFile(
  187. withBannerArray(
  188. 'Sukka\'s Surge Rules - Reject Base',
  189. [
  190. 'License: AGPL 3.0',
  191. 'Homepage: https://ruleset.skk.moe',
  192. 'GitHub: https://github.com/SukkaW/Surge',
  193. '',
  194. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  195. '',
  196. 'Build from:',
  197. ...HOSTS.map(host => ` - ${host[0]}`),
  198. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`)
  199. ],
  200. new Date(),
  201. sortedDomainSets
  202. ),
  203. pathResolve(__dirname, '../List/domainset/reject.conf')
  204. );
  205. await fs.promises.writeFile(
  206. pathResolve(__dirname, '../List/internal/reject-stats.txt'),
  207. Object.entries(rejectDomainsStats)
  208. .sort((a, b) => {
  209. const t = b[1] - a[1];
  210. if (t === 0) {
  211. return a[0].localeCompare(b[0]);
  212. }
  213. return t;
  214. })
  215. .map(([domain, count]) => `${domain}${' '.repeat(100 - domain.length)}${count}`)
  216. .join('\n')
  217. );
  218. // Copy reject_sukka.conf for backward compatibility
  219. await fse.copy(pathResolve(__dirname, '../Source/domainset/reject_sukka.conf'), pathResolve(__dirname, '../List/domainset/reject_sukka.conf'));
  220. console.timeEnd('* Write reject.conf');
  221. console.timeEnd('Total Time - build-reject-domain-set');
  222. })();