build-reject-domainset.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. const { promises: fsPromises } = require('fs');
  2. const fse = require('fs-extra');
  3. const { resolve: pathResolve } = require('path');
  4. const Piscina = require('piscina');
  5. const { processHosts, processFilterRules, preprocessFullDomainSetBeforeUsedAsWorkerData } = require('./lib/parse-filter');
  6. const cpuCount = require('os').cpus().length;
  7. const { isCI } = require('ci-info');
  8. const threads = isCI ? cpuCount : cpuCount / 2;
  9. const { HOSTS, ADGUARD_FILTERS, PREDEFINED_WHITELIST } = require('./lib/reject-data-source');
  10. const { withBannerArray } = require('./lib/with-banner');
  11. const { compareAndWriteFile } = require('./lib/string-array-compare');
  12. const filterRuleWhitelistDomainSets = new Set(PREDEFINED_WHITELIST);
  13. (async () => {
  14. console.time('Total Time - build-reject-domain-set');
  15. /** @type Set<string> */
  16. const domainSets = new Set();
  17. console.log('Downloading hosts file...');
  18. console.time('* Download and process Hosts');
  19. // Parse from remote hosts & domain lists
  20. (await Promise.all(
  21. HOSTS.map(entry => processHosts(entry[0], entry[1]))
  22. )).forEach(hosts => {
  23. hosts.forEach(host => {
  24. if (host) {
  25. domainSets.add(host);
  26. }
  27. });
  28. });
  29. console.timeEnd('* Download and process Hosts');
  30. let previousSize = domainSets.size;
  31. console.log(`Import ${previousSize} rules from hosts files!`);
  32. // Parse from AdGuard Filters
  33. console.time('* Download and process AdBlock Filter Rules');
  34. await Promise.all(ADGUARD_FILTERS.map(input => {
  35. const promise = Array.isArray(input) && input.length === 2
  36. ? processFilterRules(input[0], input[1])
  37. : processFilterRules(input);
  38. return promise.then((i) => {
  39. if (i) {
  40. const { white, black, foundDebugDomain } = i;
  41. if (foundDebugDomain) {
  42. process.exit(1);
  43. };
  44. white.forEach(i => filterRuleWhitelistDomainSets.add(i));
  45. black.forEach(i => domainSets.add(i));
  46. } else {
  47. process.exit(1);
  48. }
  49. });
  50. }));
  51. console.timeEnd('* Download and process AdBlock Filter Rules');
  52. previousSize = domainSets.size - previousSize;
  53. console.log(`Import ${previousSize} rules from adguard filters!`);
  54. await fsPromises.readFile(pathResolve(__dirname, '../Source/domainset/reject_sukka.conf'), { encoding: 'utf-8' }).then(data => {
  55. data.split('\n').forEach(line => {
  56. const trimmed = line.trim();
  57. if (
  58. line.startsWith('#')
  59. || line.startsWith(' ')
  60. || line.startsWith('\r')
  61. || line.startsWith('\n')
  62. || trimmed === ''
  63. ) {
  64. return;
  65. }
  66. domainSets.add(trimmed);
  67. });
  68. });
  69. // Copy reject_sukka.conf for backward compatibility
  70. await fse.copy(pathResolve(__dirname, '../Source/domainset/reject_sukka.conf'), pathResolve(__dirname, '../List/domainset/reject_sukka.conf'))
  71. previousSize = domainSets.size - previousSize;
  72. console.log(`Import ${previousSize} rules from reject_sukka.conf!`);
  73. // Read DOMAIN Keyword
  74. const domainKeywordsSet = new Set();
  75. const domainSuffixSet = new Set();
  76. await fsPromises.readFile(pathResolve(__dirname, '../List/non_ip/reject.conf'), { encoding: 'utf-8' }).then(data => {
  77. data.split('\n').forEach(line => {
  78. if (line.startsWith('DOMAIN-KEYWORD')) {
  79. const [, ...keywords] = line.split(',');
  80. domainKeywordsSet.add(keywords.join(',').trim());
  81. } else if (line.startsWith('DOMAIN-SUFFIX')) {
  82. const [, ...keywords] = line.split(',');
  83. domainSuffixSet.add(keywords.join(',').trim());
  84. }
  85. });
  86. });
  87. // Read Special Phishing Suffix list
  88. await fsPromises.readFile(pathResolve(__dirname, '../List/domainset/reject_phishing.conf'), { encoding: 'utf-8' }).then(data => {
  89. data.split('\n').forEach(line => {
  90. const trimmed = line.trim();
  91. if (
  92. line.startsWith('#')
  93. || line.startsWith(' ')
  94. || line.startsWith('\r')
  95. || line.startsWith('\n')
  96. || trimmed === ''
  97. ) {
  98. return;
  99. }
  100. domainSuffixSet.add(trimmed);
  101. });
  102. });
  103. console.log(`Import ${domainKeywordsSet.size} black keywords and ${domainSuffixSet.size} black suffixes!`);
  104. previousSize = domainSets.size;
  105. // Dedupe domainSets
  106. console.log(`Start deduping from black keywords/suffixes! (${previousSize})`);
  107. console.time(`* Dedupe from black keywords/suffixes`);
  108. for (const domain of domainSets) {
  109. let isTobeRemoved = false;
  110. for (const suffix of domainSuffixSet) {
  111. if (domain.endsWith(suffix)) {
  112. isTobeRemoved = true;
  113. break;
  114. }
  115. }
  116. if (!isTobeRemoved) {
  117. for (const keyword of domainKeywordsSet) {
  118. if (domain.includes(keyword)) {
  119. isTobeRemoved = true;
  120. break;
  121. }
  122. }
  123. }
  124. if (!isTobeRemoved) {
  125. if (isInWhiteList(domain)) {
  126. isTobeRemoved = true;
  127. }
  128. }
  129. if (isTobeRemoved) {
  130. domainSets.delete(domain);
  131. }
  132. }
  133. console.timeEnd(`* Dedupe from black keywords/suffixes`);
  134. console.log(`Deduped ${previousSize} - ${domainSets.size} = ${previousSize - domainSets.size} from black keywords and suffixes!`);
  135. previousSize = domainSets.size;
  136. // Dedupe domainSets
  137. console.log(`Start deduping! (${previousSize})`);
  138. const START_TIME = Date.now();
  139. const piscina = new Piscina({
  140. filename: pathResolve(__dirname, 'worker/build-reject-domainset-worker.js'),
  141. workerData: preprocessFullDomainSetBeforeUsedAsWorkerData([...domainSets]),
  142. idleTimeout: 50,
  143. minThreads: threads,
  144. maxThreads: threads
  145. });
  146. console.log(`Launching ${threads} threads...`)
  147. const tasksArray = Array.from(domainSets)
  148. .reduce((result, element, index) => {
  149. const chunk = index % threads;
  150. result[chunk] ??= [];
  151. result[chunk].push(element);
  152. return result;
  153. }, []);
  154. (
  155. await Promise.all(
  156. Array.from(domainSets)
  157. .reduce((result, element, index) => {
  158. const chunk = index % threads;
  159. result[chunk] ??= [];
  160. result[chunk].push(element);
  161. return result;
  162. }, [])
  163. .map(chunk => piscina.run({ chunk }, { name: 'dedupe' }))
  164. )
  165. ).forEach((result, taskIndex) => {
  166. const chunk = tasksArray[taskIndex];
  167. for (let i = 0, len = result.length; i < len; i++) {
  168. if (result[i]) {
  169. domainSets.delete(chunk[i]);
  170. }
  171. }
  172. });
  173. console.log(`* Dedupe from covered subdomain - ${(Date.now() - START_TIME) / 1000}s`);
  174. console.log(`Deduped ${previousSize - domainSets.size} rules!`);
  175. await piscina.destroy();
  176. console.time('* Write reject.conf');
  177. await compareAndWriteFile(
  178. withBannerArray(
  179. 'Sukka\'s Surge Rules - Reject Base',
  180. [
  181. 'License: AGPL 3.0',
  182. 'Homepage: https://ruleset.skk.moe',
  183. 'GitHub: https://github.com/SukkaW/Surge',
  184. '',
  185. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  186. '',
  187. 'Build from:',
  188. ...HOSTS.map(host => ` - ${host[0]}`),
  189. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`),
  190. ],
  191. new Date(),
  192. [...domainSets].sort()
  193. ),
  194. pathResolve(__dirname, '../List/domainset/reject.conf')
  195. );
  196. console.timeEnd('* Write reject.conf');
  197. console.timeEnd('Total Time - build-reject-domain-set');
  198. if (piscina.queueSize === 0) {
  199. process.exit(0);
  200. }
  201. })();
  202. function isInWhiteList (domain) {
  203. for (const white of filterRuleWhitelistDomainSets) {
  204. if (domain === white || domain.endsWith(white)) {
  205. return true;
  206. }
  207. }
  208. return false;
  209. }