build-reject-domainset.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. 'instant.page' // No, it doesn't violate anyone's privacy. I will whitelist it
  88. ]);
  89. /** @type Set<string> */
  90. const blacklistDomainSets = new Set();
  91. /** @type Set<string> */
  92. const blackIPSets = new Set();
  93. /** @type string[] */
  94. const filterRules = (await got(filterRulesUrl).text()).split('\n');
  95. filterRules.forEach(line => {
  96. if (
  97. line.includes('#')
  98. || line.includes('!')
  99. || line.startsWith(' ')
  100. || line.startsWith('\r')
  101. || line.startsWith('\n')
  102. || line.includes('*')
  103. || line.includes('/')
  104. || line.includes('$')
  105. || line.trim() === ''
  106. || rIPv4.test(line)
  107. ) {
  108. return;
  109. }
  110. if (line.startsWith('@@||')
  111. && (
  112. line.endsWith('^')
  113. || line.endsWith('^|')
  114. )
  115. ) {
  116. whitelistDomainSets.add(`${line.replaceAll('@@||', '').replaceAll('^|', '').replaceAll('^', '')}`.trim());
  117. } else if (
  118. line.startsWith('||')
  119. && (
  120. line.endsWith('^')
  121. || line.endsWith('^|')
  122. )
  123. ) {
  124. blacklistDomainSets.add(`.${line.replaceAll('||', '').replaceAll('^|', '').replaceAll('^', '')}`.trim());
  125. } else if (line.startsWith('://')
  126. && (
  127. line.endsWith('^')
  128. || line.endsWith('^|')
  129. )
  130. ) {
  131. blacklistDomainSets.add(`${line.replaceAll('://', '').replaceAll('^|', '').replaceAll('^', '')}`.trim());
  132. }
  133. });
  134. return {
  135. white: whitelistDomainSets,
  136. black: blacklistDomainSets
  137. };
  138. }
  139. (async () => {
  140. /** @type Set<string> */
  141. const domainSets = new Set();
  142. // Parse from remote hosts & domain lists
  143. (await Promise.all([
  144. processHosts('https://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&showintro=0&mimetype=plaintext', true),
  145. processHosts('https://raw.githubusercontent.com/hoshsadiq/adblock-nocoin-list/master/hosts.txt')
  146. ])).forEach(hosts => {
  147. hosts.forEach(host => {
  148. if (host) {
  149. domainSets.add(host);
  150. }
  151. });
  152. });
  153. const hostsSize = domainSets.size;
  154. console.log(`Import ${hostsSize} rules from hosts files!`);
  155. await fsPromises.readFile(pathResolve(__dirname, '../List/domainset/reject_sukka.conf'), { encoding: 'utf-8' }).then(data => {
  156. data.split('\n').forEach(line => {
  157. if (
  158. line.startsWith('#')
  159. || line.startsWith(' ')
  160. || line === '' || line === ' '
  161. || line.startsWith('\r')
  162. || line.startsWith('\n')
  163. ) {
  164. return;
  165. }
  166. /* if (domainSets.has(line) || domainSets.has(`.${line}`)) {
  167. console.warn(`|${line}| is already in the list!`);
  168. } */
  169. domainSets.add(line.trim());
  170. });
  171. });
  172. const sukkaSize = domainSets.size - hostsSize;
  173. console.log(`Import ${sukkaSize} rules from reject_sukka.conf!`);
  174. // Parse from AdGuard Filters
  175. /** @type Set<string> */
  176. const filterRuleWhitelistDomainSets = new Set();
  177. (await Promise.all([
  178. processFilterRules('https://easylist.to/easylist/easylist.txt'),
  179. processFilterRules('https://adguardteam.github.io/AdGuardSDNSFilter/Filters/filter.txt'),
  180. processFilterRules('https://raw.githubusercontent.com/AdguardTeam/FiltersRegistry/master/filters/filter_11_Mobile/filter.txt'),
  181. processFilterRules('https://raw.githubusercontent.com/AdguardTeam/FiltersRegistry/master/filters/filter_3_Spyware/filter.txt'),
  182. processFilterRules('https://raw.githubusercontent.com/AdguardTeam/FiltersRegistry/master/filters/filter_2_English/filter.txt'),
  183. processFilterRules('https://raw.githubusercontent.com/AdguardTeam/FiltersRegistry/master/filters/filter_224_Chinese/filter.txt'),
  184. processFilterRules('https://filters.adtidy.org/extension/ublock/filters/224.txt'),
  185. processFilterRules('https://easylist.to/easylist/easyprivacy.txt'),
  186. processFilterRules('https://raw.githubusercontent.com/DandelionSprout/adfilt/master/GameConsoleAdblockList.txt'),
  187. processFilterRules('https://raw.githubusercontent.com/Perflyst/PiHoleBlocklist/master/SmartTV-AGH.txt'),
  188. processFilterRules('https://curben.gitlab.io/malware-filter/urlhaus-filter-agh-online.txt'),
  189. processFilterRules('https://curben.gitlab.io/malware-filter/pup-filter-agh.txt'),
  190. processFilterRules('https://curben.gitlab.io/malware-filter/phishing-filter-agh.txt'),
  191. processFilterRules('https://curben.gitlab.io/malware-filter/pup-filter-agh.txt')
  192. ])).forEach(({ white, black }) => {
  193. white.forEach(i => filterRuleWhitelistDomainSets.add(i));
  194. black.forEach(i => domainSets.add(i));
  195. });
  196. const adguardSize = domainSets.size - hostsSize - sukkaSize;
  197. console.log(`Import ${adguardSize} rules from adguard filters!`);
  198. // Read DOMAIN Keyword
  199. const domainKeywordsSet = new Set();
  200. const domainSuffixSet = new Set();
  201. await fsPromises.readFile(pathResolve(__dirname, '../List/non_ip/reject.conf'), { encoding: 'utf-8' }).then(data => {
  202. data.split('\n').forEach(line => {
  203. if (line.startsWith('DOMAIN-KEYWORD')) {
  204. const [, ...keywords] = line.split(',');
  205. domainKeywordsSet.add(keywords.join(',').trim());
  206. } else if (line.startsWith('DOMAIN-SUFFIX')) {
  207. const [, ...keywords] = line.split(',');
  208. domainSuffixSet.add(keywords.join(',').trim());
  209. }
  210. });
  211. });
  212. console.log(`Import ${domainKeywordsSet.size} black keywords!`);
  213. const beforeDeduping = domainSets.size;
  214. // Dedupe domainSets
  215. console.log(`Start deduping! (${beforeDeduping})`);
  216. const piscina = new Piscina({
  217. filename: pathResolve(__dirname, 'worker/build-reject-domainset-worker.js')
  218. });
  219. (await Promise.all([
  220. piscina.run({ keywords: domainKeywordsSet, suffixes: domainSuffixSet, input: domainSets }, { name: 'dedupeKeywords' }),
  221. piscina.run({ whiteList: filterRuleWhitelistDomainSets, input: domainSets }, { name: 'whitelisted' })
  222. ])).forEach(set => {
  223. set.forEach(i => domainSets.delete(i));
  224. });
  225. const originalFullSet = new Set([...domainSets]);
  226. (await Promise.all(
  227. Array.from(domainSets).reduce((result, element, index) => {
  228. const chunk = index % threads;
  229. result[chunk] ??= [];
  230. result[chunk].push(element);
  231. return result;
  232. }, []).map(chunk => piscina.run({ input: chunk, fullSet: originalFullSet }, { name: 'dedupe' }))
  233. )).forEach(set => {
  234. set.forEach(i => domainSets.delete(i));
  235. });
  236. console.log(`Deduped ${beforeDeduping - domainSets.size} rules!`);
  237. return fsPromises.writeFile(
  238. pathResolve(__dirname, '../List/domainset/reject.conf'),
  239. `${[...domainSets].join('\n')}\n`,
  240. { encoding: 'utf-8' });
  241. })();