build-reject-domainset.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. let shouldStop = false;
  35. await 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 => filterRuleWhitelistDomainSets.add(i));
  46. black.forEach(i => domainSets.add(i));
  47. } else {
  48. process.exit(1);
  49. }
  50. });
  51. }));
  52. console.timeEnd('* Download and process AdBlock Filter Rules');
  53. if (shouldStop) {
  54. process.exit(1);
  55. }
  56. previousSize = domainSets.size - previousSize;
  57. console.log(`Import ${previousSize} rules from adguard filters!`);
  58. await fsPromises.readFile(pathResolve(__dirname, '../Source/domainset/reject_sukka.conf'), { encoding: 'utf-8' }).then(data => {
  59. data.split('\n').forEach(line => {
  60. const trimmed = line.trim();
  61. if (
  62. line.startsWith('#')
  63. || line.startsWith(' ')
  64. || line.startsWith('\r')
  65. || line.startsWith('\n')
  66. || trimmed === ''
  67. ) {
  68. return;
  69. }
  70. domainSets.add(trimmed);
  71. });
  72. });
  73. // Copy reject_sukka.conf for backward compatibility
  74. await fse.copy(pathResolve(__dirname, '../Source/domainset/reject_sukka.conf'), pathResolve(__dirname, '../List/domainset/reject_sukka.conf'))
  75. previousSize = domainSets.size - previousSize;
  76. console.log(`Import ${previousSize} rules from reject_sukka.conf!`);
  77. // Read DOMAIN Keyword
  78. const domainKeywordsSet = new Set();
  79. const domainSuffixSet = new Set();
  80. await fsPromises.readFile(pathResolve(__dirname, '../List/non_ip/reject.conf'), { encoding: 'utf-8' }).then(data => {
  81. data.split('\n').forEach(line => {
  82. if (line.startsWith('DOMAIN-KEYWORD')) {
  83. const [, ...keywords] = line.split(',');
  84. domainKeywordsSet.add(keywords.join(',').trim());
  85. } else if (line.startsWith('DOMAIN-SUFFIX')) {
  86. const [, ...keywords] = line.split(',');
  87. domainSuffixSet.add(keywords.join(',').trim());
  88. }
  89. });
  90. });
  91. // Read Special Phishing Suffix list
  92. await fsPromises.readFile(pathResolve(__dirname, '../List/domainset/reject_phishing.conf'), { encoding: 'utf-8' }).then(data => {
  93. data.split('\n').forEach(line => {
  94. const trimmed = line.trim();
  95. if (
  96. line.startsWith('#')
  97. || line.startsWith(' ')
  98. || line.startsWith('\r')
  99. || line.startsWith('\n')
  100. || trimmed === ''
  101. ) {
  102. return;
  103. }
  104. domainSuffixSet.add(trimmed);
  105. });
  106. });
  107. console.log(`Import ${domainKeywordsSet.size} black keywords and ${domainSuffixSet.size} black suffixes!`);
  108. previousSize = domainSets.size;
  109. // Dedupe domainSets
  110. console.log(`Start deduping from black keywords/suffixes! (${previousSize})`);
  111. console.time(`* Dedupe from black keywords/suffixes`);
  112. for (const domain of domainSets) {
  113. let isTobeRemoved = false;
  114. for (const suffix of domainSuffixSet) {
  115. if (domain.endsWith(suffix)) {
  116. isTobeRemoved = true;
  117. break;
  118. }
  119. }
  120. if (!isTobeRemoved) {
  121. for (const keyword of domainKeywordsSet) {
  122. if (domain.includes(keyword)) {
  123. isTobeRemoved = true;
  124. break;
  125. }
  126. }
  127. }
  128. if (!isTobeRemoved) {
  129. if (isInWhiteList(domain)) {
  130. isTobeRemoved = true;
  131. }
  132. }
  133. if (isTobeRemoved) {
  134. domainSets.delete(domain);
  135. }
  136. }
  137. console.timeEnd(`* Dedupe from black keywords/suffixes`);
  138. console.log(`Deduped ${previousSize} - ${domainSets.size} = ${previousSize - domainSets.size} from black keywords and suffixes!`);
  139. previousSize = domainSets.size;
  140. // Dedupe domainSets
  141. console.log(`Start deduping! (${previousSize})`);
  142. const START_TIME = Date.now();
  143. const piscina = new Piscina({
  144. filename: pathResolve(__dirname, 'worker/build-reject-domainset-worker.js'),
  145. workerData: preprocessFullDomainSetBeforeUsedAsWorkerData([...domainSets]),
  146. idleTimeout: 50,
  147. minThreads: threads,
  148. maxThreads: threads
  149. });
  150. console.log(`Launching ${threads} threads...`)
  151. const tasksArray = Array.from(domainSets)
  152. .reduce((result, element, index) => {
  153. const chunk = index % threads;
  154. result[chunk] ??= [];
  155. result[chunk].push(element);
  156. return result;
  157. }, []);
  158. (
  159. await Promise.all(
  160. Array.from(domainSets)
  161. .reduce((result, element, index) => {
  162. const chunk = index % threads;
  163. result[chunk] ??= [];
  164. result[chunk].push(element);
  165. return result;
  166. }, [])
  167. .map(chunk => piscina.run({ chunk }, { name: 'dedupe' }))
  168. )
  169. ).forEach((result, taskIndex) => {
  170. const chunk = tasksArray[taskIndex];
  171. for (let i = 0, len = result.length; i < len; i++) {
  172. if (result[i]) {
  173. domainSets.delete(chunk[i]);
  174. }
  175. }
  176. });
  177. console.log(`* Dedupe from covered subdomain - ${(Date.now() - START_TIME) / 1000}s`);
  178. console.log(`Deduped ${previousSize - domainSets.size} rules!`);
  179. await piscina.destroy();
  180. console.time('* Write reject.conf');
  181. await compareAndWriteFile(
  182. withBannerArray(
  183. 'Sukka\'s Surge Rules - Reject Base',
  184. [
  185. 'License: AGPL 3.0',
  186. 'Homepage: https://ruleset.skk.moe',
  187. 'GitHub: https://github.com/SukkaW/Surge',
  188. '',
  189. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  190. '',
  191. 'Build from:',
  192. ...HOSTS.map(host => ` - ${host[0]}`),
  193. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`),
  194. ],
  195. new Date(),
  196. [...domainSets].sort()
  197. ),
  198. pathResolve(__dirname, '../List/domainset/reject.conf')
  199. );
  200. console.timeEnd('* Write reject.conf');
  201. console.timeEnd('Total Time - build-reject-domain-set');
  202. if (piscina.queueSize === 0) {
  203. process.exit(0);
  204. }
  205. })();
  206. function isInWhiteList (domain) {
  207. for (const white of filterRuleWhitelistDomainSets) {
  208. if (domain === white || domain.endsWith(white)) {
  209. return true;
  210. }
  211. if (white.endsWith(domain)) {
  212. // If a whole domain is in blacklist but a subdomain is in whitelist
  213. // We have no choice but to remove the whole domain from blacklist
  214. return true;
  215. }
  216. }
  217. return false;
  218. }