build-reject-domainset.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. // @ts-check
  2. const { promises: fsPromises } = require('fs');
  3. const fse = require('fs-extra');
  4. const { resolve: pathResolve } = require('path');
  5. const Piscina = require('piscina');
  6. const { processHosts, processFilterRules, preprocessFullDomainSetBeforeUsedAsWorkerData } = require('./lib/parse-filter');
  7. const cpuCount = require('os').cpus().length;
  8. const { isCI } = require('ci-info');
  9. const threads = isCI ? cpuCount : cpuCount / 2;
  10. const { getDomain } = require('tldts');
  11. const { HOSTS, ADGUARD_FILTERS, PREDEFINED_WHITELIST, PREDEFINED_ENFORCED_BACKLIST } = require('./lib/reject-data-source');
  12. const { withBannerArray } = require('./lib/with-banner');
  13. const { compareAndWriteFile } = require('./lib/string-array-compare');
  14. /** Whitelists */
  15. const filterRuleWhitelistDomainSets = new Set(PREDEFINED_WHITELIST);
  16. /** @type {Set<string>} Dedupe domains inclued by DOMAIN-KEYWORD */
  17. const domainKeywordsSet = new Set();
  18. /** @type {Set<string>} Dedupe domains included by DOMAIN-SUFFIX */
  19. const domainSuffixSet = new Set();
  20. (async () => {
  21. console.time('Total Time - build-reject-domain-set');
  22. /** @type Set<string> */
  23. const domainSets = new Set();
  24. console.log('Downloading hosts file...');
  25. console.time('* Download and process Hosts');
  26. // Parse from remote hosts & domain lists
  27. (await Promise.all(
  28. HOSTS.map(entry => processHosts(entry[0], entry[1]))
  29. )).forEach(hosts => {
  30. hosts.forEach(host => {
  31. if (host) {
  32. domainSets.add(host);
  33. }
  34. });
  35. });
  36. console.timeEnd('* Download and process Hosts');
  37. let previousSize = domainSets.size;
  38. console.log(`Import ${previousSize} rules from hosts files!`);
  39. // Parse from AdGuard Filters
  40. console.time('* Download and process AdBlock Filter Rules');
  41. let shouldStop = false;
  42. await Promise.all(ADGUARD_FILTERS.map(input => {
  43. const promise = typeof input === 'string'
  44. ? processFilterRules(input, undefined, false)
  45. : processFilterRules(input[0], input[1] || undefined, input[2] ?? false)
  46. return promise.then((i) => {
  47. if (i) {
  48. const { white, black, foundDebugDomain } = i;
  49. if (foundDebugDomain) {
  50. shouldStop = true;
  51. }
  52. white.forEach(i => {
  53. if (PREDEFINED_ENFORCED_BACKLIST.some(j => i.endsWith(j))) {
  54. return;
  55. }
  56. filterRuleWhitelistDomainSets.add(i);
  57. });
  58. black.forEach(i => domainSets.add(i));
  59. } else {
  60. process.exit(1);
  61. }
  62. });
  63. }));
  64. await Promise.all([
  65. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exceptions.txt',
  66. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exclusions.txt'
  67. ].map(
  68. input => processFilterRules(input).then((i) => {
  69. if (i) {
  70. const { white, black } = i;
  71. white.forEach(i => {
  72. if (PREDEFINED_ENFORCED_BACKLIST.some(j => i.endsWith(j))) {
  73. return;
  74. }
  75. filterRuleWhitelistDomainSets.add(i)
  76. });
  77. black.forEach(i => {
  78. if (PREDEFINED_ENFORCED_BACKLIST.some(j => i.endsWith(j))) {
  79. return;
  80. }
  81. filterRuleWhitelistDomainSets.add(i)
  82. });
  83. } else {
  84. process.exit(1);
  85. }
  86. })
  87. ));
  88. console.timeEnd('* Download and process AdBlock Filter Rules');
  89. if (shouldStop) {
  90. process.exit(1);
  91. }
  92. previousSize = domainSets.size - previousSize;
  93. console.log(`Import ${previousSize} rules from adguard filters!`);
  94. await fsPromises.readFile(pathResolve(__dirname, '../Source/domainset/reject_sukka.conf'), { encoding: 'utf-8' }).then(data => {
  95. data.split('\n').forEach(line => {
  96. const trimmed = line.trim();
  97. if (
  98. line.startsWith('#')
  99. || line.startsWith(' ')
  100. || line.startsWith('\r')
  101. || line.startsWith('\n')
  102. || trimmed === ''
  103. ) {
  104. return;
  105. }
  106. domainSets.add(trimmed);
  107. });
  108. });
  109. previousSize = domainSets.size - previousSize;
  110. console.log(`Import ${previousSize} rules from reject_sukka.conf!`);
  111. await Promise.all([
  112. // Copy reject_sukka.conf for backward compatibility
  113. fse.copy(pathResolve(__dirname, '../Source/domainset/reject_sukka.conf'), pathResolve(__dirname, '../List/domainset/reject_sukka.conf')),
  114. fsPromises.readFile(pathResolve(__dirname, '../List/non_ip/reject.conf'), { encoding: 'utf-8' }).then(data => {
  115. data.split('\n').forEach(line => {
  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. }),
  125. // Read Special Phishing Suffix list
  126. fsPromises.readFile(pathResolve(__dirname, '../List/domainset/reject_phishing.conf'), { encoding: 'utf-8' }).then(data => {
  127. data.split('\n').forEach(line => {
  128. const trimmed = line.trim();
  129. if (
  130. line.startsWith('#')
  131. || line.startsWith(' ')
  132. || line.startsWith('\r')
  133. || line.startsWith('\n')
  134. || trimmed === ''
  135. ) {
  136. return;
  137. }
  138. domainSuffixSet.add(trimmed);
  139. });
  140. })
  141. ]);
  142. console.log(`Import ${domainKeywordsSet.size} black keywords and ${domainSuffixSet.size} black suffixes!`);
  143. previousSize = domainSets.size;
  144. // Dedupe domainSets
  145. console.log(`Start deduping from black keywords/suffixes! (${previousSize})`);
  146. console.time(`* Dedupe from black keywords/suffixes`);
  147. for (const domain of domainSets) {
  148. if (isMatchKeyword(domain) || isMatchSuffix(domain) || isInWhiteList(domain)) {
  149. domainSets.delete(domain);
  150. }
  151. }
  152. console.timeEnd(`* Dedupe from black keywords/suffixes`);
  153. console.log(`Deduped ${previousSize} - ${domainSets.size} = ${previousSize - domainSets.size} from black keywords and suffixes!`);
  154. previousSize = domainSets.size;
  155. // Dedupe domainSets
  156. console.log(`Start deduping! (${previousSize})`);
  157. const START_TIME = Date.now();
  158. const domainSetsArray = Array.from(domainSets);
  159. const workerData = preprocessFullDomainSetBeforeUsedAsWorkerData(domainSetsArray);
  160. const piscina = new Piscina({
  161. filename: pathResolve(__dirname, 'worker/build-reject-domainset-worker.js'),
  162. workerData,
  163. idleTimeout: 50,
  164. minThreads: threads,
  165. maxThreads: threads
  166. });
  167. console.log(workerData.length);
  168. console.log(`Launching ${threads} threads...`);
  169. const tasksArray = domainSetsArray.reduce((result, element, index) => {
  170. const chunk = index % threads;
  171. result[chunk] ??= [];
  172. result[chunk].push(element);
  173. return result;
  174. }, /** @type {string[][]} */([]));
  175. (await Promise.all(
  176. tasksArray.map(chunk => piscina.run({ chunk }))
  177. )).forEach((result, taskIndex) => {
  178. const chunk = tasksArray[taskIndex];
  179. for (let i = 0, len = result.length; i < len; i++) {
  180. if (result[i]) {
  181. domainSets.delete(chunk[i]);
  182. }
  183. }
  184. });
  185. console.log(`* Dedupe from covered subdomain - ${(Date.now() - START_TIME) / 1000}s`);
  186. console.log(`Deduped ${previousSize - domainSets.size} rules!`);
  187. await piscina.destroy();
  188. console.time('* Write reject.conf');
  189. const sorter = (a, b) => {
  190. if (a.domain > b.domain) {
  191. return 1;
  192. }
  193. if (a.domain < b.domain) {
  194. return -1;
  195. }
  196. return 0;
  197. };
  198. const sortedDomainSets = Array.from(domainSets)
  199. .map((v) => {
  200. return { v, domain: getDomain(v.charCodeAt(0) === 46 ? v.slice(1) : v)?.toLowerCase() || v };
  201. })
  202. .sort(sorter)
  203. .map((i) => {
  204. return i.v;
  205. });
  206. await compareAndWriteFile(
  207. withBannerArray(
  208. 'Sukka\'s Surge Rules - Reject Base',
  209. [
  210. 'License: AGPL 3.0',
  211. 'Homepage: https://ruleset.skk.moe',
  212. 'GitHub: https://github.com/SukkaW/Surge',
  213. '',
  214. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  215. '',
  216. 'Build from:',
  217. ...HOSTS.map(host => ` - ${host[0]}`),
  218. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`),
  219. ],
  220. new Date(),
  221. sortedDomainSets
  222. ),
  223. pathResolve(__dirname, '../List/domainset/reject.conf')
  224. );
  225. console.timeEnd('* Write reject.conf');
  226. console.timeEnd('Total Time - build-reject-domain-set');
  227. if (piscina.queueSize === 0) {
  228. process.exit(0);
  229. }
  230. })();
  231. /**
  232. * @param {string} domain
  233. */
  234. function isMatchKeyword(domain) {
  235. for (const keyword of domainKeywordsSet) {
  236. if (domain.includes(keyword)) {
  237. return true;
  238. }
  239. }
  240. return false;
  241. }
  242. /**
  243. * @param {string} domain
  244. */
  245. function isMatchSuffix(domain) {
  246. for (const suffix of domainSuffixSet) {
  247. if (domain.endsWith(suffix)) {
  248. return true;
  249. }
  250. }
  251. return false;
  252. }
  253. /**
  254. * @param {string} domain
  255. */
  256. function isInWhiteList(domain) {
  257. for (const white of filterRuleWhitelistDomainSets) {
  258. if (domain === white || domain.endsWith(white)) {
  259. return true;
  260. }
  261. if (white.endsWith(domain)) {
  262. // If a whole domain is in blacklist but a subdomain is in whitelist
  263. // We have no choice but to remove the whole domain from blacklist
  264. return true;
  265. }
  266. }
  267. return false;
  268. }