build-reject-domainset.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. // @ts-check
  2. const fsp = require('fs/promises');
  3. const path = require('path');
  4. const { processHosts, processFilterRules } = require('./lib/parse-filter');
  5. const createTrie = require('./lib/trie');
  6. const { HOSTS, ADGUARD_FILTERS, PREDEFINED_WHITELIST, PREDEFINED_ENFORCED_BACKLIST } = require('./lib/reject-data-source');
  7. const { createRuleset, compareAndWriteFile } = require('./lib/create-file');
  8. const { processLine } = require('./lib/process-line');
  9. const { domainDeduper } = require('./lib/domain-deduper');
  10. const createKeywordFilter = require('./lib/aho-corasick');
  11. const { readFileByLine } = require('./lib/fetch-remote-text-by-line');
  12. const { createDomainSorter } = require('./lib/stable-sort-domain');
  13. const { traceSync, task } = require('./lib/trace-runner');
  14. const { getGorhillPublicSuffixPromise } = require('./lib/get-gorhill-publicsuffix');
  15. const tldts = require('tldts');
  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. const buildRejectDomainSet = task(__filename, async () => {
  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. const [gorhill] = await Promise.all([
  29. getGorhillPublicSuffixPromise(),
  30. // Parse from remote hosts & domain lists
  31. ...HOSTS.map(entry => processHosts(entry[0], entry[1]).then(hosts => {
  32. hosts.forEach(host => {
  33. if (host) {
  34. domainSets.add(host);
  35. }
  36. });
  37. })),
  38. ...ADGUARD_FILTERS.map(input => {
  39. const promise = typeof input === 'string'
  40. ? processFilterRules(input)
  41. : processFilterRules(input[0], input[1] || undefined);
  42. return promise.then((i) => {
  43. if (i) {
  44. const { white, black, foundDebugDomain } = i;
  45. if (foundDebugDomain) {
  46. shouldStop = true;
  47. // we should not break here, as we want to see full matches from all data source
  48. }
  49. white.forEach(i => filterRuleWhitelistDomainSets.add(i));
  50. black.forEach(i => domainSets.add(i));
  51. } else {
  52. process.exitCode = 1;
  53. throw new Error('Failed to process AdGuard Filter Rules!');
  54. }
  55. });
  56. }),
  57. ...([
  58. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exceptions.txt',
  59. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exclusions.txt'
  60. ].map(input => processFilterRules(input).then((i) => {
  61. if (i) {
  62. const { white, black } = i;
  63. white.forEach(i => {
  64. filterRuleWhitelistDomainSets.add(i);
  65. });
  66. black.forEach(i => {
  67. filterRuleWhitelistDomainSets.add(i);
  68. });
  69. } else {
  70. process.exitCode = 1;
  71. throw new Error('Failed to process AdGuard Filter Rules!');
  72. }
  73. })))
  74. ]);
  75. // remove pre-defined enforced blacklist from whitelist
  76. const trie0 = createTrie(filterRuleWhitelistDomainSets);
  77. PREDEFINED_ENFORCED_BACKLIST.forEach(enforcedBlack => {
  78. trie0.find(enforcedBlack).forEach(found => filterRuleWhitelistDomainSets.delete(found));
  79. });
  80. console.timeEnd('* Download and process Hosts / AdBlock Filter Rules');
  81. if (shouldStop) {
  82. // eslint-disable-next-line n/no-process-exit -- force stop
  83. process.exit(1);
  84. }
  85. let previousSize = domainSets.size;
  86. console.log(`Import ${previousSize} rules from Hosts / AdBlock Filter Rules!`);
  87. for await (const line of readFileByLine(path.resolve(__dirname, '../Source/domainset/reject_sukka.conf'))) {
  88. const l = processLine(line);
  89. if (l) {
  90. domainSets.add(l);
  91. }
  92. }
  93. previousSize = domainSets.size - previousSize;
  94. console.log(`Import ${previousSize} rules from reject_sukka.conf!`);
  95. for await (const line of readFileByLine(path.resolve(__dirname, '../Source/non_ip/reject.conf'))) {
  96. if (line.startsWith('DOMAIN-KEYWORD')) {
  97. const [, ...keywords] = line.split(',');
  98. domainKeywordsSet.add(keywords.join(',').trim());
  99. } else if (line.startsWith('DOMAIN-SUFFIX')) {
  100. const [, ...keywords] = line.split(',');
  101. domainSuffixSet.add(keywords.join(',').trim());
  102. }
  103. }
  104. for await (const line of readFileByLine(path.resolve(__dirname, '../List/domainset/reject_phishing.conf'))) {
  105. const l = processLine(line);
  106. if (l && l[0] === '.') {
  107. domainSuffixSet.add(l.slice(1));
  108. }
  109. }
  110. console.log(`Import ${domainKeywordsSet.size} black keywords and ${domainSuffixSet.size} black suffixes!`);
  111. previousSize = domainSets.size;
  112. // Dedupe domainSets
  113. console.log(`Start deduping from black keywords/suffixes! (${previousSize})`);
  114. console.time('* Dedupe from black keywords/suffixes');
  115. const trie1 = createTrie(domainSets);
  116. domainSuffixSet.forEach(suffix => {
  117. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  118. });
  119. filterRuleWhitelistDomainSets.forEach(suffix => {
  120. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  121. });
  122. // remove pre-defined enforced blacklist from whitelist
  123. const kwfilter = createKeywordFilter(domainKeywordsSet);
  124. // Build whitelist trie, to handle case like removing `g.msn.com` due to white `.g.msn.com` (`@@||g.msn.com`)
  125. const trieWhite = createTrie(filterRuleWhitelistDomainSets);
  126. for (const domain of domainSets) {
  127. if (domain[0] === '.') {
  128. if (trieWhite.contains(domain)) {
  129. domainSets.delete(domain);
  130. continue;
  131. }
  132. } else if (trieWhite.has(`.${domain}`)) {
  133. domainSets.delete(domain);
  134. continue;
  135. }
  136. // Remove keyword
  137. if (kwfilter.search(domain)) {
  138. domainSets.delete(domain);
  139. }
  140. }
  141. console.timeEnd('* Dedupe from black keywords/suffixes');
  142. console.log(`Deduped ${previousSize} - ${domainSets.size} = ${previousSize - domainSets.size} from black keywords and suffixes!`);
  143. previousSize = domainSets.size;
  144. // Dedupe domainSets
  145. console.log(`Start deduping! (${previousSize})`);
  146. const dudupedDominArray = traceSync('* Dedupe from covered subdomain', () => domainDeduper(Array.from(domainSets)));
  147. console.log(`Deduped ${previousSize - dudupedDominArray.length} rules!`);
  148. // Create reject stats
  149. /** @type {[string, number][]} */
  150. const rejectDomainsStats = traceSync(
  151. '* Collect reject domain stats',
  152. () => Object.entries(
  153. dudupedDominArray.reduce((acc, cur) => {
  154. const suffix = tldts.getDomain(cur, { allowPrivateDomains: false, detectIp: false });
  155. if (suffix) {
  156. acc[suffix] = (acc[suffix] ?? 0) + 1;
  157. }
  158. return acc;
  159. }, {})
  160. ).filter(a => a[1] > 10).sort((a, b) => {
  161. const t = b[1] - a[1];
  162. if (t !== 0) {
  163. return t;
  164. }
  165. return a[0].localeCompare(b[0]);
  166. })
  167. );
  168. const domainSorter = createDomainSorter(gorhill);
  169. const domainset = traceSync('* Sort reject domainset', () => dudupedDominArray.sort(domainSorter));
  170. const description = [
  171. 'License: AGPL 3.0',
  172. 'Homepage: https://ruleset.skk.moe',
  173. 'GitHub: https://github.com/SukkaW/Surge',
  174. '',
  175. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  176. '',
  177. 'Build from:',
  178. ...HOSTS.map(host => ` - ${host[0]}`),
  179. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`)
  180. ];
  181. return Promise.all([
  182. ...createRuleset(
  183. 'Sukka\'s Ruleset - Reject Base',
  184. description,
  185. new Date(),
  186. domainset,
  187. 'domainset',
  188. path.resolve(__dirname, '../List/domainset/reject.conf'),
  189. path.resolve(__dirname, '../Clash/domainset/reject.txt')
  190. ),
  191. compareAndWriteFile(
  192. rejectDomainsStats.map(([domain, count]) => `${domain}${' '.repeat(100 - domain.length)}${count}`),
  193. path.resolve(__dirname, '../List/internal/reject-stats.txt')
  194. ),
  195. // Copy reject_sukka.conf for backward compatibility
  196. fsp.cp(
  197. path.resolve(__dirname, '../Source/domainset/reject_sukka.conf'),
  198. path.resolve(__dirname, '../List/domainset/reject_sukka.conf'),
  199. { force: true, recursive: true }
  200. )
  201. ]);
  202. });
  203. module.exports.buildRejectDomainSet = buildRejectDomainSet;
  204. if (require.main === module) {
  205. buildRejectDomainSet();
  206. }