build-reject-domainset.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. const { default: got } = require('got-cjs');
  2. const { promises: fsPromises } = require('fs');
  3. const { resolve: pathResolve } = require('path');
  4. const { cpus } = require('os');
  5. const threads = Math.max(cpus().length, 12);
  6. const rIPv4 = /((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/;
  7. const Piscina = require('piscina');
  8. /**
  9. * @param {string | URL} domainListsUrl
  10. */
  11. async function processDomainLists(domainListsUrl) {
  12. if (typeof domainListsUrl === 'string') {
  13. domainListsUrl = new URL(domainListsUrl);
  14. }
  15. /** @type Set<string> */
  16. const domainSets = new Set();
  17. /** @type string[] */
  18. const domains = (await got(domainListsUrl).text()).split('\n');
  19. domains.forEach(line => {
  20. if (
  21. line.startsWith('#')
  22. || line.startsWith('!')
  23. || line.startsWith(' ')
  24. || line === ''
  25. || line.startsWith('\r')
  26. || line.startsWith('\n')
  27. ) {
  28. return;
  29. }
  30. domainSets.add(line.trim());
  31. });
  32. return [...domainSets];
  33. }
  34. /**
  35. * @param {string | URL} hostsUrl
  36. */
  37. async function processHosts(hostsUrl, includeAllSubDomain = false) {
  38. if (typeof hostsUrl === 'string') {
  39. hostsUrl = new URL(hostsUrl);
  40. }
  41. /** @type Set<string> */
  42. const domainSets = new Set();
  43. /** @type string[] */
  44. const hosts = (await got(hostsUrl).text()).split('\n');
  45. hosts.forEach(line => {
  46. if (line.includes('#')) {
  47. return;
  48. }
  49. if (line.startsWith(' ') || line.startsWith('\r') || line.startsWith('\n') || line.trim() === '') {
  50. return;
  51. }
  52. const [, ...domains] = line.split(' ');
  53. if (includeAllSubDomain) {
  54. domainSets.add(`.${domains.join(' ')}`.trim());
  55. } else {
  56. domainSets.add(domains.join(' ').trim());
  57. }
  58. });
  59. return [...domainSets];
  60. }
  61. /**
  62. * @param {string | URL} filterRulesUrl
  63. * @returns {Promise<{ white: Set<string>, black: Set<string> }>}
  64. */
  65. async function processFilterRules(filterRulesUrl) {
  66. if (typeof filterRulesUrl === 'string') {
  67. filterRulesUrl = new URL(filterRulesUrl);
  68. }
  69. /** @type Set<string> */
  70. const whitelistDomainSets = new Set([
  71. 'localhost',
  72. 'broadcasthost',
  73. 'ip6-loopback',
  74. 'ip6-localnet',
  75. 'ip6-mcastprefix',
  76. 'ip6-allnodes',
  77. 'ip6-allrouters',
  78. 'ip6-allhosts',
  79. 'mcastprefix',
  80. 'analytics.google.com',
  81. 'msa.cdn.mediaset.net', // Added manually using DOMAIN-KEYWORDS
  82. 'cloud.answerhub.com',
  83. 'ae01.alicdn.com',
  84. 'whoami.akamai.net',
  85. 'whoami.ds.akahelp.net',
  86. 'pxlk9.net.' // This one is malformed from EasyList, which I will manually add instead
  87. ]);
  88. /** @type Set<string> */
  89. const blacklistDomainSets = new Set();
  90. /** @type Set<string> */
  91. const blackIPSets = new Set();
  92. /** @type string[] */
  93. const filterRules = (await got(filterRulesUrl).text()).split('\n');
  94. filterRules.forEach(line => {
  95. if (
  96. line.includes('#')
  97. || line.includes('!')
  98. || line.startsWith(' ')
  99. || line.startsWith('\r')
  100. || line.startsWith('\n')
  101. || line.includes('*')
  102. || line.includes('/')
  103. || line.includes('$')
  104. || line.trim() === ''
  105. || rIPv4.test(line)
  106. ) {
  107. return;
  108. }
  109. if (line.startsWith('@@||')
  110. && (
  111. line.endsWith('^')
  112. || line.endsWith('^|')
  113. )
  114. ) {
  115. whitelistDomainSets.add(`${line.replaceAll('@@||', '').replaceAll('^|', '').replaceAll('^', '')}`.trim());
  116. } else if (
  117. line.startsWith('||')
  118. && (
  119. line.endsWith('^')
  120. || line.endsWith('^|')
  121. )
  122. ) {
  123. blacklistDomainSets.add(`.${line.replaceAll('||', '').replaceAll('^|', '').replaceAll('^', '')}`.trim());
  124. } else if (line.startsWith('://')
  125. && (
  126. line.endsWith('^')
  127. || line.endsWith('^|')
  128. )
  129. ) {
  130. blacklistDomainSets.add(`${line.replaceAll('://', '').replaceAll('^|', '').replaceAll('^', '')}`.trim());
  131. }
  132. });
  133. return {
  134. white: whitelistDomainSets,
  135. black: blacklistDomainSets
  136. };
  137. }
  138. (async () => {
  139. /** @type Set<string> */
  140. const domainSets = new Set();
  141. // Parse from remote hosts & domain lists
  142. (await Promise.all([
  143. processHosts('https://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&showintro=0&mimetype=plaintext', true),
  144. processHosts('https://raw.githubusercontent.com/hoshsadiq/adblock-nocoin-list/master/hosts.txt')
  145. ])).forEach(hosts => {
  146. hosts.forEach(host => {
  147. if (host) {
  148. domainSets.add(host);
  149. }
  150. });
  151. });
  152. const hostsSize = domainSets.size;
  153. console.log(`Import ${hostsSize} rules from hosts files!`);
  154. await fsPromises.readFile(pathResolve(__dirname, '../List/domainset/reject_sukka.conf'), { encoding: 'utf-8' }).then(data => {
  155. data.split('\n').forEach(line => {
  156. if (
  157. line.startsWith('#')
  158. || line.startsWith(' ')
  159. || line === '' || line === ' '
  160. || line.startsWith('\r')
  161. || line.startsWith('\n')
  162. ) {
  163. return;
  164. }
  165. /* if (domainSets.has(line) || domainSets.has(`.${line}`)) {
  166. console.warn(`|${line}| is already in the list!`);
  167. } */
  168. domainSets.add(line.trim());
  169. });
  170. });
  171. const sukkaSize = domainSets.size - hostsSize;
  172. console.log(`Import ${sukkaSize} rules from reject_sukka.conf!`);
  173. // Parse from AdGuard Filters
  174. /** @type Set<string> */
  175. const filterRuleWhitelistDomainSets = new Set();
  176. (await Promise.all([
  177. processFilterRules('https://easylist.to/easylist/easylist.txt'),
  178. processFilterRules('https://adguardteam.github.io/AdGuardSDNSFilter/Filters/filter.txt'),
  179. processFilterRules('https://raw.githubusercontent.com/AdguardTeam/FiltersRegistry/master/filters/filter_11_Mobile/filter.txt'),
  180. processFilterRules('https://raw.githubusercontent.com/AdguardTeam/FiltersRegistry/master/filters/filter_3_Spyware/filter.txt'),
  181. processFilterRules('https://raw.githubusercontent.com/AdguardTeam/FiltersRegistry/master/filters/filter_2_English/filter.txt'),
  182. processFilterRules('https://raw.githubusercontent.com/AdguardTeam/FiltersRegistry/master/filters/filter_224_Chinese/filter.txt'),
  183. processFilterRules('https://filters.adtidy.org/extension/ublock/filters/224.txt'),
  184. processFilterRules('https://easylist.to/easylist/easyprivacy.txt'),
  185. processFilterRules('https://raw.githubusercontent.com/DandelionSprout/adfilt/master/GameConsoleAdblockList.txt'),
  186. processFilterRules('https://raw.githubusercontent.com/Perflyst/PiHoleBlocklist/master/SmartTV-AGH.txt'),
  187. processFilterRules('https://curben.gitlab.io/malware-filter/urlhaus-filter-agh-online.txt'),
  188. processFilterRules('https://curben.gitlab.io/malware-filter/pup-filter-agh.txt'),
  189. processFilterRules('https://curben.gitlab.io/malware-filter/phishing-filter-agh.txt'),
  190. processFilterRules('https://curben.gitlab.io/malware-filter/pup-filter-agh.txt')
  191. ])).forEach(({ white, black }) => {
  192. white.forEach(i => filterRuleWhitelistDomainSets.add(i));
  193. black.forEach(i => domainSets.add(i));
  194. });
  195. const adguardSize = domainSets.size - hostsSize - sukkaSize;
  196. console.log(`Import ${adguardSize} rules from adguard filters!`);
  197. // Read DOMAIN Keyword
  198. const domainKeywordsSet = new Set();
  199. const domainSuffixSet = new Set();
  200. await fsPromises.readFile(pathResolve(__dirname, '../List/non_ip/reject.conf'), { encoding: 'utf-8' }).then(data => {
  201. data.split('\n').forEach(line => {
  202. if (line.startsWith('DOMAIN-KEYWORD')) {
  203. const [, ...keywords] = line.split(',');
  204. domainKeywordsSet.add(keywords.join(',').trim());
  205. } else if (line.startsWith('DOMAIN-SUFFIX')) {
  206. const [, ...keywords] = line.split(',');
  207. domainSuffixSet.add(keywords.join(',').trim());
  208. }
  209. });
  210. });
  211. console.log(`Import ${domainKeywordsSet.size} black keywords!`);
  212. const beforeDeduping = domainSets.size;
  213. // Dedupe domainSets
  214. console.log(`Start deduping! (${beforeDeduping})`);
  215. const piscina = new Piscina({
  216. filename: pathResolve(__dirname, 'worker/build-reject-domainset-worker.js')
  217. });
  218. (await Promise.all([
  219. piscina.run({ keywords: domainKeywordsSet, suffixes: domainSuffixSet, input: domainSets }, { name: 'dedupeKeywords' }),
  220. piscina.run({ whiteList: filterRuleWhitelistDomainSets, input: domainSets }, { name: 'whitelisted' })
  221. ])).forEach(set => {
  222. set.forEach(i => domainSets.delete(i));
  223. });
  224. const originalFullSet = new Set([...domainSets]);
  225. (await Promise.all(
  226. Array.from(domainSets).reduce((result, element, index) => {
  227. const chunk = index % threads;
  228. result[chunk] ??= [];
  229. result[chunk].push(element);
  230. return result;
  231. }, []).map(chunk => piscina.run({ input: chunk, fullSet: originalFullSet }, { name: 'dedupe' }))
  232. )).forEach(set => {
  233. set.forEach(i => domainSets.delete(i));
  234. });
  235. console.log(`Deduped ${beforeDeduping - domainSets.size} rules!`);
  236. return fsPromises.writeFile(
  237. pathResolve(__dirname, '../List/domainset/reject.conf'),
  238. `${[...domainSets].join('\n')}\n`,
  239. { encoding: 'utf-8' });
  240. })();