build-reject-domainset.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 piscina = new Piscina({
  160. filename: pathResolve(__dirname, 'worker/build-reject-domainset-worker.js'),
  161. workerData: preprocessFullDomainSetBeforeUsedAsWorkerData(Array.from(domainSetsArray)),
  162. idleTimeout: 50,
  163. minThreads: threads,
  164. maxThreads: threads
  165. });
  166. console.log(preprocessFullDomainSetBeforeUsedAsWorkerData(Array.from(domainSetsArray)).length);
  167. console.log(`Launching ${threads} threads...`);
  168. const tasksArray = domainSetsArray.reduce((result, element, index) => {
  169. const chunk = index % threads;
  170. result[chunk] ??= [];
  171. result[chunk].push(element);
  172. return result;
  173. }, /** @type {string[][]} */([]));
  174. (await Promise.all(
  175. tasksArray.map(chunk => piscina.run({ chunk }))
  176. )).forEach((result, taskIndex) => {
  177. const chunk = tasksArray[taskIndex];
  178. for (let i = 0, len = result.length; i < len; i++) {
  179. if (result[i]) {
  180. domainSets.delete(chunk[i]);
  181. }
  182. }
  183. });
  184. console.log(`* Dedupe from covered subdomain - ${(Date.now() - START_TIME) / 1000}s`);
  185. console.log(`Deduped ${previousSize - domainSets.size} rules!`);
  186. await piscina.destroy();
  187. console.time('* Write reject.conf');
  188. const sorter = (a, b) => {
  189. if (a.domain > b.domain) {
  190. return 1;
  191. }
  192. if (a.domain < b.domain) {
  193. return -1;
  194. }
  195. return 0;
  196. };
  197. const sortedDomainSets = Array.from(domainSets)
  198. .map((v) => {
  199. return { v, domain: getDomain(v.charCodeAt(0) === 46 ? v.slice(1) : v)?.toLowerCase() || v };
  200. })
  201. .sort(sorter)
  202. .map((i) => {
  203. return i.v;
  204. });
  205. await compareAndWriteFile(
  206. withBannerArray(
  207. 'Sukka\'s Surge Rules - Reject Base',
  208. [
  209. 'License: AGPL 3.0',
  210. 'Homepage: https://ruleset.skk.moe',
  211. 'GitHub: https://github.com/SukkaW/Surge',
  212. '',
  213. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  214. '',
  215. 'Build from:',
  216. ...HOSTS.map(host => ` - ${host[0]}`),
  217. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`),
  218. ],
  219. new Date(),
  220. sortedDomainSets
  221. ),
  222. pathResolve(__dirname, '../List/domainset/reject.conf')
  223. );
  224. console.timeEnd('* Write reject.conf');
  225. console.timeEnd('Total Time - build-reject-domain-set');
  226. if (piscina.queueSize === 0) {
  227. process.exit(0);
  228. }
  229. })();
  230. /**
  231. * @param {string} domain
  232. */
  233. function isMatchKeyword(domain) {
  234. for (const keyword of domainKeywordsSet) {
  235. if (domain.includes(keyword)) {
  236. return true;
  237. }
  238. }
  239. return false;
  240. }
  241. /**
  242. * @param {string} domain
  243. */
  244. function isMatchSuffix(domain) {
  245. for (const suffix of domainSuffixSet) {
  246. if (domain.endsWith(suffix)) {
  247. return true;
  248. }
  249. }
  250. return false;
  251. }
  252. /**
  253. * @param {string} domain
  254. */
  255. function isInWhiteList(domain) {
  256. for (const white of filterRuleWhitelistDomainSets) {
  257. if (domain === white || domain.endsWith(white)) {
  258. return true;
  259. }
  260. if (white.endsWith(domain)) {
  261. // If a whole domain is in blacklist but a subdomain is in whitelist
  262. // We have no choice but to remove the whole domain from blacklist
  263. return true;
  264. }
  265. }
  266. return false;
  267. }