build-reject-domainset.js 8.8 KB

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