build-reject-domainset.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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, preprocessFullDomainSetBeforeUsedAsWorkerData } = 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. /** Whitelists */
  14. const filterRuleWhitelistDomainSets = new Set(PREDEFINED_WHITELIST);
  15. /** @type {Set<string>} Dedupe domains inclued by DOMAIN-KEYWORD */
  16. const domainKeywordsSet = new Set();
  17. /** @type {Set<string>} Dedupe domains included by DOMAIN-SUFFIX */
  18. const domainSuffixSet = new Set();
  19. (async () => {
  20. console.time('Total Time - build-reject-domain-set');
  21. /** @type Set<string> */
  22. const domainSets = new Set();
  23. // Parse from AdGuard Filters
  24. console.time('* Download and process Hosts / AdBlock Filter Rules');
  25. let shouldStop = false;
  26. await Promise.all([
  27. // Parse from remote hosts & domain lists
  28. Promise.all(HOSTS.map(entry => processHosts(entry[0], entry[1])))
  29. .then(r => r.forEach(hosts => {
  30. hosts.forEach(host => {
  31. if (host) {
  32. domainSets.add(host);
  33. }
  34. });
  35. })),
  36. Promise.all(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.exit(1);
  55. }
  56. });
  57. })),
  58. Promise.all([
  59. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exceptions.txt',
  60. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exclusions.txt'
  61. ].map(
  62. 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.exit(1);
  79. }
  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. process.exit(1);
  90. }
  91. let previousSize = domainSets.size;
  92. console.log(`Import ${previousSize} rules from Hosts / AdBlock Filter Rules!`);
  93. const rl1 = readline.createInterface({
  94. input: fs.createReadStream(pathResolve(__dirname, '../Source/domainset/reject_sukka.conf'), { encoding: 'utf-8' }),
  95. crlfDelay: Infinity
  96. });
  97. for await (const line of rl1) {
  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. const rl2 = readline.createInterface({
  106. input: fs.createReadStream(pathResolve(__dirname, '../List/non_ip/reject.conf'), { encoding: 'utf-8' }),
  107. crlfDelay: Infinity
  108. });
  109. for await (const line of rl2) {
  110. if (line.startsWith('DOMAIN-KEYWORD')) {
  111. const [, ...keywords] = line.split(',');
  112. domainKeywordsSet.add(keywords.join(',').trim());
  113. } else if (line.startsWith('DOMAIN-SUFFIX')) {
  114. const [, ...keywords] = line.split(',');
  115. domainSuffixSet.add(keywords.join(',').trim());
  116. }
  117. }
  118. const rl3 = readline.createInterface({
  119. input: fs.createReadStream(pathResolve(__dirname, '../List/domainset/reject_phishing.conf'), { encoding: 'utf-8' }),
  120. crlfDelay: Infinity
  121. });
  122. for await (const line of rl3) {
  123. const l = processLine(line);
  124. if (l) {
  125. domainSets.add(l);
  126. }
  127. }
  128. console.log(`Import ${domainKeywordsSet.size} black keywords and ${domainSuffixSet.size} black suffixes!`);
  129. previousSize = domainSets.size;
  130. // Dedupe domainSets
  131. console.log(`Start deduping from black keywords/suffixes! (${previousSize})`);
  132. console.time('* Dedupe from black keywords/suffixes');
  133. const trie1 = Trie.from(Array.from(domainSets));
  134. domainSuffixSet.forEach(suffix => {
  135. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  136. });
  137. filterRuleWhitelistDomainSets.forEach(suffix => {
  138. trie1.find(suffix, true).forEach(f => domainSets.delete(f));
  139. });
  140. // Build whitelist trie, to handle case like removing `g.msn.com` due to white `.g.msn.com` (`@@||g.msn.com`)
  141. const trieWhite = Trie.from(Array.from(filterRuleWhitelistDomainSets));
  142. for (const domain of domainSets) {
  143. if (domain[0] === '.') {
  144. if (trieWhite.contains(domain)) {
  145. domainSets.delete(domain);
  146. continue;
  147. }
  148. } else if (trieWhite.has(`.${domain}`)) {
  149. domainSets.delete(domain);
  150. continue;
  151. }
  152. // Remove keyword
  153. if (isMatchKeyword(domain)) {
  154. domainSets.delete(domain);
  155. }
  156. }
  157. console.timeEnd('* Dedupe from black keywords/suffixes');
  158. console.log(`Deduped ${previousSize} - ${domainSets.size} = ${previousSize - domainSets.size} from black keywords and suffixes!`);
  159. previousSize = domainSets.size;
  160. // Dedupe domainSets
  161. console.log(`Start deduping! (${previousSize})`);
  162. const START_TIME = Date.now();
  163. const domainSetsArray = Array.from(domainSets);
  164. const trie2 = Trie.from(domainSetsArray);
  165. const fullsetDomainStartsWithADot = preprocessFullDomainSetBeforeUsedAsWorkerData(domainSetsArray);
  166. console.log(fullsetDomainStartsWithADot.length);
  167. for (let j = 0, len = fullsetDomainStartsWithADot.length; j < len; j++) {
  168. const domainStartsWithADotAndFromFullSet = fullsetDomainStartsWithADot[j];
  169. const found = trie2.find(domainStartsWithADotAndFromFullSet, false);
  170. if (found.length) {
  171. found.forEach(f => {
  172. domainSets.delete(f);
  173. });
  174. }
  175. const a = domainStartsWithADotAndFromFullSet.slice(1);
  176. if (trie2.has(a)) {
  177. domainSets.delete(a);
  178. }
  179. }
  180. console.log(`* Dedupe from covered subdomain - ${(Date.now() - START_TIME) / 1000}s`);
  181. console.log(`Deduped ${previousSize - domainSets.size} rules!`);
  182. console.time('* Write reject.conf');
  183. const sorter = (a, b) => {
  184. if (a.domain > b.domain) {
  185. return 1;
  186. }
  187. if (a.domain < b.domain) {
  188. return -1;
  189. }
  190. return 0;
  191. };
  192. const sortedDomainSets = Array.from(domainSets)
  193. .map((v) => {
  194. return { v, domain: getDomain(v.charCodeAt(0) === 46 ? v.slice(1) : v) || v };
  195. })
  196. .sort(sorter)
  197. .map((i) => i.v);
  198. await compareAndWriteFile(
  199. withBannerArray(
  200. 'Sukka\'s Surge Rules - Reject Base',
  201. [
  202. 'License: AGPL 3.0',
  203. 'Homepage: https://ruleset.skk.moe',
  204. 'GitHub: https://github.com/SukkaW/Surge',
  205. '',
  206. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  207. '',
  208. 'Build from:',
  209. ...HOSTS.map(host => ` - ${host[0]}`),
  210. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`)
  211. ],
  212. new Date(),
  213. sortedDomainSets
  214. ),
  215. pathResolve(__dirname, '../List/domainset/reject.conf')
  216. );
  217. // Copy reject_sukka.conf for backward compatibility
  218. await fse.copy(pathResolve(__dirname, '../Source/domainset/reject_sukka.conf'), pathResolve(__dirname, '../List/domainset/reject_sukka.conf'));
  219. console.timeEnd('* Write reject.conf');
  220. console.timeEnd('Total Time - build-reject-domain-set');
  221. })();
  222. /**
  223. * @param {string} domain
  224. */
  225. function isMatchKeyword(domain) {
  226. for (const keyword of domainKeywordsSet) {
  227. if (domain.includes(keyword)) {
  228. return true;
  229. }
  230. }
  231. return false;
  232. }