build-reject-domainset.js 8.0 KB

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