build-reject-domainset.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. const { promises: fsPromises } = require('fs');
  2. const { resolve: pathResolve } = require('path');
  3. const Piscina = require('piscina');
  4. const { processHosts, processFilterRules, preprocessFullDomainSetBeforeUsedAsWorkerData } = require('./lib/parse-filter');
  5. const cpuCount = require('os').cpus().length;
  6. const { isCI } = require('ci-info');
  7. const threads = isCI ? cpuCount : cpuCount / 2;
  8. (async () => {
  9. console.time('Total Time - build-reject-domain-set');
  10. /** @type Set<string> */
  11. const domainSets = new Set();
  12. console.log('Downloading hosts file...');
  13. console.time('* Download and process Hosts');
  14. // Parse from remote hosts & domain lists
  15. (await Promise.all([
  16. processHosts('https://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&showintro=0&mimetype=plaintext', true),
  17. processHosts('https://raw.githubusercontent.com/hoshsadiq/adblock-nocoin-list/master/hosts.txt'),
  18. processHosts('https://raw.githubusercontent.com/crazy-max/WindowsSpyBlocker/master/data/hosts/spy.txt')
  19. ])).forEach(hosts => {
  20. hosts.forEach(host => {
  21. if (host) {
  22. domainSets.add(host);
  23. }
  24. });
  25. });
  26. console.timeEnd('* Download and process Hosts');
  27. let previousSize = domainSets.size;
  28. console.log(`Import ${previousSize} rules from hosts files!`);
  29. await fsPromises.readFile(pathResolve(__dirname, '../List/domainset/reject_sukka.conf'), { encoding: 'utf-8' }).then(data => {
  30. data.split('\n').forEach(line => {
  31. const trimmed = line.trim();
  32. if (
  33. line.startsWith('#')
  34. || line.startsWith(' ')
  35. || line.startsWith('\r')
  36. || line.startsWith('\n')
  37. || trimmed === ''
  38. ) {
  39. return;
  40. }
  41. /* if (domainSets.has(line) || domainSets.has(`.${line}`)) {
  42. console.warn(`|${line}| is already in the list!`);
  43. } */
  44. domainSets.add(trimmed);
  45. });
  46. });
  47. previousSize = domainSets.size - previousSize;
  48. console.log(`Import ${previousSize} rules from reject_sukka.conf!`);
  49. // Parse from AdGuard Filters
  50. /** @type Set<string> */
  51. const filterRuleWhitelistDomainSets = new Set([
  52. 'localhost',
  53. 'broadcasthost',
  54. 'ip6-loopback',
  55. 'ip6-localnet',
  56. 'ip6-mcastprefix',
  57. 'ip6-allnodes',
  58. 'ip6-allrouters',
  59. 'ip6-allhosts',
  60. 'mcastprefix',
  61. 'skk.moe',
  62. 'analytics.google.com',
  63. 'msa.cdn.mediaset.net', // Added manually using DOMAIN-KEYWORDS
  64. 'cloud.answerhub.com',
  65. 'ae01.alicdn.com',
  66. 'whoami.akamai.net',
  67. 'whoami.ds.akahelp.net',
  68. 'pxlk9.net.', // This one is malformed from EasyList, which I will manually add instead
  69. 'instant.page', // No, it doesn't violate anyone's privacy. I will whitelist it
  70. 'piwik.pro',
  71. 'mixpanel.com',
  72. 'cdn.mxpnl.com',
  73. 'heapanalytics.com',
  74. 'segment.com',
  75. 'segmentify.com',
  76. 't.co', // pgl yoyo add t.co to the blacklist
  77. 'survicate.com', // AdGuardDNSFilter
  78. 'perfops.io', // AdGuardDNSFilter
  79. 'd2axgrpnciinw7.cloudfront.net', // ADGuardDNSFilter
  80. 'tb-lb.sb-cd.com', // AdGuard
  81. 'storage.yandexcloud.net', // phishing list
  82. 'login.microsoftonline.com' // phishing list
  83. ]);
  84. console.time('* Download and process AdBlock Filter Rules');
  85. (await Promise.all([
  86. // Easy List
  87. [
  88. 'https://easylist.to/easylist/easylist.txt',
  89. [
  90. 'https://easylist-downloads.adblockplus.org/easylist.txt',
  91. 'https://raw.githubusercontent.com/easylist/easylist/gh-pages/easylist.txt',
  92. 'https://secure.fanboy.co.nz/easylist.txt'
  93. ]
  94. ],
  95. // AdGuard DNS Filter
  96. 'https://adguardteam.github.io/AdGuardSDNSFilter/Filters/filter.txt',
  97. // uBlock Origin Filter List
  98. 'https://ublockorigin.github.io/uAssetsCDN/filters/filters.txt',
  99. 'https://ublockorigin.github.io/uAssetsCDN/filters/filters-2020.txt',
  100. 'https://ublockorigin.github.io/uAssetsCDN/filters/filters-2021.txt',
  101. 'https://ublockorigin.github.io/uAssetsCDN/filters/filters-2022.txt',
  102. // uBlock Origin Badware Risk List
  103. 'https://ublockorigin.github.io/uAssets/filters/badware.txt',
  104. // uBlock Origin Privacy List
  105. 'https://ublockorigin.github.io/uAssets/filters/privacy.txt',
  106. // uBlock Origin Resource Abuse
  107. 'https://ublockorigin.github.io/uAssets/filters/resource-abuse.txt',
  108. // uBlock Origin Unbreak
  109. 'https://ublockorigin.github.io/uAssets/filters/unbreak.txt',
  110. // AdGuard Base Filter
  111. 'https://filters.adtidy.org/extension/ublock/filters/2_without_easylist.txt',
  112. // AdGuard Mobile AD
  113. 'https://filters.adtidy.org/extension/ublock/filters/11.txt',
  114. // AdGuard Tracking Protection
  115. 'https://filters.adtidy.org/extension/ublock/filters/3.txt',
  116. // AdGuard Japanese filter
  117. 'https://filters.adtidy.org/extension/ublock/filters/7.txt',
  118. // AdGuard Chinese filter (EasyList China + AdGuard Chinese filter)
  119. 'https://filters.adtidy.org/extension/ublock/filters/224.txt',
  120. // Easy Privacy
  121. [
  122. 'https://easylist.to/easylist/easyprivacy.txt',
  123. [
  124. 'https://secure.fanboy.co.nz/easyprivacy.txt',
  125. 'https://raw.githubusercontent.com/easylist/easylist/gh-pages/easyprivacy.txt',
  126. 'https://easylist-downloads.adblockplus.org/easyprivacy.txt'
  127. ]
  128. ],
  129. // Curben's UrlHaus Malicious URL Blocklist
  130. // Prefer mirror, since malware-filter.gitlab.io has not been updated for a while
  131. 'https://curbengh.github.io/urlhaus-filter/urlhaus-filter-agh-online.txt',
  132. // [
  133. // 'https://malware-filter.pages.dev/urlhaus-filter-agh-online.txt',
  134. // [
  135. // 'https://malware-filter.gitlab.io/urlhaus-filter/urlhaus-filter-agh-online.txt'
  136. // ]
  137. // ],
  138. // Curben's Phishing URL Blocklist
  139. // Prefer mirror, since malware-filter.gitlab.io has not been updated for a while
  140. 'https://curbengh.github.io/phishing-filter/phishing-filter-agh.txt',
  141. // [
  142. // 'https://phishing-filter.pages.dev/phishing-filter-agh.txt',
  143. // [
  144. // 'https://malware-filter.gitlab.io/malware-filter/phishing-filter-agh.txt'
  145. // ]
  146. // ],
  147. // Curben's PUP Domains Blocklist
  148. 'https://curbengh.github.io/pup-filter/pup-filter-agh.txt',
  149. // Prefer mirror, since malware-filter.gitlab.io has not been updated for a while
  150. // [
  151. // 'https://pup-filter.pages.dev/pup-filter-agh.txt',
  152. // [
  153. // 'https://malware-filter.gitlab.io/malware-filter/pup-filter-agh.txt'
  154. // ]
  155. // ],
  156. // GameConsoleAdblockList
  157. 'https://raw.githubusercontent.com/DandelionSprout/adfilt/master/GameConsoleAdblockList.txt',
  158. // PiHoleBlocklist
  159. 'https://raw.githubusercontent.com/Perflyst/PiHoleBlocklist/master/SmartTV-AGH.txt',
  160. // Spam404
  161. 'https://raw.githubusercontent.com/Spam404/lists/master/adblock-list.txt'
  162. ].map(input => {
  163. if (typeof input === 'string') {
  164. return processFilterRules(input);
  165. }
  166. if (Array.isArray(input) && input.length === 2) {
  167. return processFilterRules(input[0], input[1]);
  168. }
  169. }))).forEach(({ white, black }) => {
  170. white.forEach(i => filterRuleWhitelistDomainSets.add(i));
  171. black.forEach(i => domainSets.add(i));
  172. });
  173. console.timeEnd('* Download and process AdBlock Filter Rules');
  174. previousSize = domainSets.size - previousSize;
  175. console.log(`Import ${previousSize} rules from adguard filters!`);
  176. // Read DOMAIN Keyword
  177. const domainKeywordsSet = new Set();
  178. const domainSuffixSet = new Set();
  179. await fsPromises.readFile(pathResolve(__dirname, '../List/non_ip/reject.conf'), { encoding: 'utf-8' }).then(data => {
  180. data.split('\n').forEach(line => {
  181. if (line.startsWith('DOMAIN-KEYWORD')) {
  182. const [, ...keywords] = line.split(',');
  183. domainKeywordsSet.add(keywords.join(',').trim());
  184. } else if (line.startsWith('DOMAIN-SUFFIX')) {
  185. const [, ...keywords] = line.split(',');
  186. domainSuffixSet.add(keywords.join(',').trim());
  187. }
  188. });
  189. });
  190. // Read Special Phishing Suffix list
  191. await fsPromises.readFile(pathResolve(__dirname, '../List/domainset/reject_phishing.conf'), { encoding: 'utf-8' }).then(data => {
  192. data.split('\n').forEach(line => {
  193. const trimmed = line.trim();
  194. if (
  195. line.startsWith('#')
  196. || line.startsWith(' ')
  197. || line.startsWith('\r')
  198. || line.startsWith('\n')
  199. || trimmed === ''
  200. ) {
  201. return;
  202. }
  203. /* if (domainSets.has(line) || domainSets.has(`.${line}`)) {
  204. console.warn(`|${line}| is already in the list!`);
  205. } */
  206. domainSuffixSet.add(trimmed);
  207. });
  208. });
  209. console.log(`Import ${domainKeywordsSet.size} black keywords and ${domainSuffixSet.size} black suffixes!`);
  210. previousSize = domainSets.size;
  211. // Dedupe domainSets
  212. console.log(`Start deduping from black keywords/suffixes! (${previousSize})`);
  213. console.time(`* Dedupe from black keywords/suffixes`);
  214. const toBeRemoved = new Set();
  215. for (const domain of domainSets) {
  216. let isTobeRemoved = false;
  217. for (const keyword of domainKeywordsSet) {
  218. if (domain.includes(keyword)) {
  219. isTobeRemoved = true;
  220. break;
  221. }
  222. }
  223. if (!isTobeRemoved) {
  224. for (const suffix of domainSuffixSet) {
  225. if (domain.endsWith(suffix)) {
  226. isTobeRemoved = true;
  227. break;
  228. }
  229. }
  230. }
  231. if (!isTobeRemoved) {
  232. for (const white of filterRuleWhitelistDomainSets) {
  233. if (domain.includes(white) || white.includes(domain)) {
  234. isTobeRemoved = true;
  235. break;
  236. }
  237. }
  238. }
  239. if (isTobeRemoved) {
  240. toBeRemoved.add(domain);
  241. }
  242. }
  243. toBeRemoved.forEach((removed) => {
  244. domainSets.delete(removed)
  245. });
  246. console.timeEnd(`* Dedupe from black keywords/suffixes`);
  247. console.log(`Deduped ${previousSize} - ${domainSets.size} = ${previousSize - domainSets.size} from black keywords and suffixes!`);
  248. previousSize = domainSets.size;
  249. // Dedupe domainSets
  250. console.log(`Start deduping! (${previousSize})`);
  251. const START_TIME = Date.now();
  252. const piscina = new Piscina({
  253. filename: pathResolve(__dirname, 'worker/build-reject-domainset-worker.js'),
  254. workerData: preprocessFullDomainSetBeforeUsedAsWorkerData([...domainSets]),
  255. idleTimeout: 50,
  256. minThreads: threads,
  257. maxThreads: threads
  258. });
  259. console.log(`Launching ${threads} threads...`)
  260. const tasksArray = Array.from(domainSets)
  261. .reduce((result, element, index) => {
  262. const chunk = index % threads;
  263. result[chunk] ??= [];
  264. result[chunk].push(element);
  265. return result;
  266. }, []);
  267. (
  268. await Promise.all(
  269. Array.from(domainSets)
  270. .reduce((result, element, index) => {
  271. const chunk = index % threads;
  272. result[chunk] ??= [];
  273. result[chunk].push(element);
  274. return result;
  275. }, [])
  276. .map(chunk => piscina.run({ chunk }, { name: 'dedupe' }))
  277. )
  278. ).forEach((result, taskIndex) => {
  279. const chunk = tasksArray[taskIndex];
  280. result.forEach((value, index) => {
  281. if (value === 1) {
  282. domainSets.delete(chunk[index])
  283. }
  284. })
  285. });
  286. console.log(`* Dedupe from covered subdomain - ${(Date.now() - START_TIME) / 1000}s`);
  287. console.log(`Deduped ${previousSize - domainSets.size} rules!`);
  288. await Promise.all([
  289. fsPromises.writeFile(
  290. pathResolve(__dirname, '../List/domainset/reject.conf'),
  291. `${[...domainSets].join('\n')}\n`,
  292. { encoding: 'utf-8' }
  293. ),
  294. piscina.destroy()
  295. ]);
  296. console.timeEnd('Total Time - build-reject-domain-set');
  297. if (piscina.queueSize === 0) {
  298. process.exit(0);
  299. }
  300. })();