build-reject-domainset.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. // @ts-check
  2. const fs = require('fs');
  3. const fse = require('fs-extra');
  4. const readline = require('readline');
  5. const { resolve: pathResolve } = require('path');
  6. const { processHosts, processFilterRules } = require('./lib/parse-filter');
  7. const { getDomain } = require('tldts');
  8. const Trie = require('./lib/trie');
  9. const { HOSTS, ADGUARD_FILTERS, PREDEFINED_WHITELIST, PREDEFINED_ENFORCED_BACKLIST } = require('./lib/reject-data-source');
  10. const { withBannerArray } = require('./lib/with-banner');
  11. const { compareAndWriteFile } = require('./lib/string-array-compare');
  12. const { processLine } = require('./lib/process-line');
  13. const { domainDeduper } = require('./lib/domain-deduper');
  14. const createKeywordFilter = require('./lib/aho-corasick');
  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 = readline.createInterface({
  96. input: fs.createReadStream(pathResolve(__dirname, '../Source/domainset/reject_sukka.conf'), { encoding: 'utf-8' }),
  97. crlfDelay: Infinity
  98. });
  99. for await (const line of rl1) {
  100. const l = processLine(line);
  101. if (l) {
  102. domainSets.add(l);
  103. }
  104. }
  105. previousSize = domainSets.size - previousSize;
  106. console.log(`Import ${previousSize} rules from reject_sukka.conf!`);
  107. const rl2 = readline.createInterface({
  108. input: fs.createReadStream(pathResolve(__dirname, '../List/non_ip/reject.conf'), { encoding: 'utf-8' }),
  109. crlfDelay: Infinity
  110. });
  111. for await (const line of rl2) {
  112. if (line.startsWith('DOMAIN-KEYWORD')) {
  113. const [, ...keywords] = line.split(',');
  114. domainKeywordsSet.add(keywords.join(',').trim());
  115. } else if (line.startsWith('DOMAIN-SUFFIX')) {
  116. const [, ...keywords] = line.split(',');
  117. domainSuffixSet.add(keywords.join(',').trim());
  118. }
  119. }
  120. const rl3 = readline.createInterface({
  121. input: fs.createReadStream(pathResolve(__dirname, '../List/domainset/reject_phishing.conf'), { encoding: 'utf-8' }),
  122. crlfDelay: Infinity
  123. });
  124. for await (const line of rl3) {
  125. const l = processLine(line);
  126. if (l) {
  127. domainSets.add(l);
  128. }
  129. }
  130. console.log(`Import ${domainKeywordsSet.size} black keywords and ${domainSuffixSet.size} black suffixes!`);
  131. previousSize = domainSets.size;
  132. // Dedupe domainSets
  133. console.log(`Start deduping from black keywords/suffixes! (${previousSize})`);
  134. console.time('* Dedupe from black keywords/suffixes');
  135. const kwfilter = createKeywordFilter(Array.from(domainKeywordsSet));
  136. const trie1 = Trie.from(Array.from(domainSets));
  137. domainSuffixSet.forEach(suffix => {
  138. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  139. });
  140. filterRuleWhitelistDomainSets.forEach(suffix => {
  141. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  142. });
  143. // Build whitelist trie, to handle case like removing `g.msn.com` due to white `.g.msn.com` (`@@||g.msn.com`)
  144. const trieWhite = Trie.from(Array.from(filterRuleWhitelistDomainSets));
  145. for (const domain of domainSets) {
  146. if (domain[0] === '.') {
  147. if (trieWhite.contains(domain)) {
  148. domainSets.delete(domain);
  149. continue;
  150. }
  151. } else if (trieWhite.has(`.${domain}`)) {
  152. domainSets.delete(domain);
  153. continue;
  154. }
  155. // Remove keyword
  156. if (kwfilter.search(domain)) {
  157. domainSets.delete(domain);
  158. }
  159. }
  160. console.timeEnd('* Dedupe from black keywords/suffixes');
  161. console.log(`Deduped ${previousSize} - ${domainSets.size} = ${previousSize - domainSets.size} from black keywords and suffixes!`);
  162. previousSize = domainSets.size;
  163. // Dedupe domainSets
  164. console.log(`Start deduping! (${previousSize})`);
  165. const START_TIME = Date.now();
  166. const dudupedDominArray = domainDeduper(Array.from(domainSets));
  167. console.log(`* Dedupe from covered subdomain - ${(Date.now() - START_TIME) / 1000}s`);
  168. console.log(`Deduped ${previousSize - dudupedDominArray.length} rules!`);
  169. console.time('* Write reject.conf');
  170. const sorter = (a, b) => {
  171. if (a.domain > b.domain) {
  172. return 1;
  173. }
  174. if (a.domain < b.domain) {
  175. return -1;
  176. }
  177. return 0;
  178. };
  179. const sortedDomainSets = dudupedDominArray
  180. .map((v) => {
  181. return { v, domain: getDomain(v.charCodeAt(0) === 46 ? v.slice(1) : v) || v };
  182. })
  183. .sort(sorter)
  184. .map((i) => i.v);
  185. await compareAndWriteFile(
  186. withBannerArray(
  187. 'Sukka\'s Surge Rules - Reject Base',
  188. [
  189. 'License: AGPL 3.0',
  190. 'Homepage: https://ruleset.skk.moe',
  191. 'GitHub: https://github.com/SukkaW/Surge',
  192. '',
  193. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  194. '',
  195. 'Build from:',
  196. ...HOSTS.map(host => ` - ${host[0]}`),
  197. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`)
  198. ],
  199. new Date(),
  200. sortedDomainSets
  201. ),
  202. pathResolve(__dirname, '../List/domainset/reject.conf')
  203. );
  204. // Copy reject_sukka.conf for backward compatibility
  205. await fse.copy(pathResolve(__dirname, '../Source/domainset/reject_sukka.conf'), pathResolve(__dirname, '../List/domainset/reject_sukka.conf'));
  206. console.timeEnd('* Write reject.conf');
  207. console.timeEnd('Total Time - build-reject-domain-set');
  208. })();