parse-filter.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. const { isIP } = require('net');
  2. const { fetchWithRetry } = require('./fetch-retry');
  3. const rDomain = /^(((?!\-))(xn\-\-)?[a-z0-9\-_]{0,61}[a-z0-9]{1,1}\.)*(xn\-\-)?([a-z0-9\-]{1,61}|[a-z0-9\-]{1,30})\.[a-z]{2,}$/m
  4. const DEBUG_DOMAIN_TO_FIND = null; // example.com | null
  5. const warnOnceUrl = new Set();
  6. const warnOnce = (url, isWhite, ...message) => {
  7. const key = `${url}${isWhite ? 'white' : 'black'}`;
  8. if (warnOnceUrl.has(key)) {
  9. return;
  10. }
  11. warnOnceUrl.add(key);
  12. console.warn(url, isWhite ? '(white)' : '(black)', ...message);
  13. }
  14. /**
  15. * @param {string | URL} domainListsUrl
  16. */
  17. async function processDomainLists (domainListsUrl) {
  18. if (typeof domainListsUrl === 'string') {
  19. domainListsUrl = new URL(domainListsUrl);
  20. }
  21. /** @type Set<string> */
  22. const domainSets = new Set();
  23. /** @type string[] */
  24. const domains = (await (await fetchWithRetry(domainListsUrl)).text()).split('\n');
  25. domains.forEach(line => {
  26. if (
  27. line.startsWith('#')
  28. || line.startsWith('!')
  29. || line.startsWith(' ')
  30. || line === ''
  31. || line.startsWith('\r')
  32. || line.startsWith('\n')
  33. ) {
  34. return;
  35. }
  36. const domainToAdd = line.trim();
  37. if (DEBUG_DOMAIN_TO_FIND && domainToAdd.includes(DEBUG_DOMAIN_TO_FIND)) {
  38. warnOnce(domainListsUrl.toString(), false, DEBUG_DOMAIN_TO_FIND);
  39. }
  40. domainSets.add(domainToAdd);
  41. });
  42. return [...domainSets];
  43. }
  44. /**
  45. * @param {string | URL} hostsUrl
  46. */
  47. async function processHosts (hostsUrl, includeAllSubDomain = false) {
  48. console.time(` - processHosts: ${hostsUrl}`);
  49. if (typeof hostsUrl === 'string') {
  50. hostsUrl = new URL(hostsUrl);
  51. }
  52. /** @type Set<string> */
  53. const domainSets = new Set();
  54. /** @type string[] */
  55. const hosts = (await (await fetchWithRetry(hostsUrl)).text()).split('\n');
  56. hosts.forEach(line => {
  57. if (line.includes('#')) {
  58. return;
  59. }
  60. if (line.startsWith(' ') || line.startsWith('\r') || line.startsWith('\n') || line.trim() === '') {
  61. return;
  62. }
  63. const [, ...domains] = line.split(' ');
  64. const domain = domains.join(' ').trim();
  65. if (DEBUG_DOMAIN_TO_FIND && domain.includes(DEBUG_DOMAIN_TO_FIND)) {
  66. warnOnce(hostsUrl.toString(), false, DEBUG_DOMAIN_TO_FIND);
  67. }
  68. if (rDomain.test(domain)) {
  69. if (includeAllSubDomain) {
  70. domainSets.add(`.${domain}`);
  71. } else {
  72. domainSets.add(domain);
  73. }
  74. }
  75. });
  76. console.timeEnd(` - processHosts: ${hostsUrl}`);
  77. return [...domainSets];
  78. }
  79. /**
  80. * @param {string | URL} filterRulesUrl
  81. * @param {(string | URL)[] | undefined} fallbackUrls
  82. * @returns {Promise<{ white: Set<string>, black: Set<string> }>}
  83. */
  84. async function processFilterRules (filterRulesUrl, fallbackUrls) {
  85. console.time(` - processFilterRules: ${filterRulesUrl}`);
  86. /** @type Set<string> */
  87. const whitelistDomainSets = new Set();
  88. /** @type Set<string> */
  89. const blacklistDomainSets = new Set();
  90. let filterRules;
  91. try {
  92. /** @type string[] */
  93. filterRules = (
  94. await Promise.any(
  95. [filterRulesUrl, ...(fallbackUrls || [])].map(
  96. async url => (await fetchWithRetry(url)).text()
  97. )
  98. )
  99. ).split('\n').map(line => line.trim());
  100. } catch (e) {
  101. console.log('Download Rule for [' + filterRulesUrl + '] failed');
  102. throw e;
  103. }
  104. filterRules.forEach(line => {
  105. const lineStartsWithDoubleVerticalBar = line.startsWith('||');
  106. if (
  107. line === ''
  108. || line.includes('#')
  109. || line.includes('!')
  110. || line.includes('*')
  111. || line.includes('/')
  112. || line.includes('[')
  113. || line.includes('$') && !lineStartsWithDoubleVerticalBar
  114. || line === ''
  115. || isIP(line) !== 0
  116. ) {
  117. return;
  118. }
  119. const lineEndsWithCaret = line.endsWith('^');
  120. const lineEndsWithCaretVerticalBar = line.endsWith('^|');
  121. if (lineStartsWithDoubleVerticalBar && line.endsWith('^$badfilter')) {
  122. const domain = line.replace('||', '').replace('^$badfilter', '').trim();
  123. if (rDomain.test(domain)) {
  124. if (DEBUG_DOMAIN_TO_FIND && domain.includes(DEBUG_DOMAIN_TO_FIND)) {
  125. warnOnce(filterRulesUrl.toString(), true, DEBUG_DOMAIN_TO_FIND);
  126. }
  127. whitelistDomainSets.add(domain);
  128. }
  129. } else if (line.startsWith('@@||')
  130. && (
  131. lineEndsWithCaret
  132. || lineEndsWithCaretVerticalBar
  133. || line.endsWith('^$badfilter')
  134. || line.endsWith('^$1p')
  135. )
  136. ) {
  137. const domain = line
  138. .replaceAll('@@||', '')
  139. .replaceAll('^$badfilter', '')
  140. .replaceAll('^$1p', '')
  141. .replaceAll('^|', '')
  142. .replaceAll('^', '')
  143. .trim();
  144. if (rDomain.test(domain)) {
  145. if (DEBUG_DOMAIN_TO_FIND && domain.includes(DEBUG_DOMAIN_TO_FIND)) {
  146. warnOnce(filterRulesUrl.toString(), true, DEBUG_DOMAIN_TO_FIND);
  147. }
  148. whitelistDomainSets.add(domain);
  149. }
  150. } else if (
  151. lineStartsWithDoubleVerticalBar
  152. && (
  153. lineEndsWithCaret
  154. || lineEndsWithCaretVerticalBar
  155. || line.endsWith('^$all')
  156. )
  157. ) {
  158. const domain = line
  159. .replaceAll('||', '')
  160. .replaceAll('^|', '')
  161. .replaceAll('^$all', '')
  162. .replaceAll('^', '')
  163. .trim();
  164. if (rDomain.test(domain)) {
  165. if (DEBUG_DOMAIN_TO_FIND && domain.includes(DEBUG_DOMAIN_TO_FIND)) {
  166. warnOnce(filterRulesUrl.toString(), false, DEBUG_DOMAIN_TO_FIND);
  167. }
  168. blacklistDomainSets.add(`.${domain}`);
  169. }
  170. } else if (line.startsWith('://')
  171. && (
  172. lineEndsWithCaret
  173. || lineEndsWithCaretVerticalBar
  174. )
  175. ) {
  176. const domain = `${line.replaceAll('://', '').replaceAll('^|', '').replaceAll('^', '')}`.trim();
  177. if (rDomain.test(domain)) {
  178. if (DEBUG_DOMAIN_TO_FIND && domain.includes(DEBUG_DOMAIN_TO_FIND)) {
  179. warnOnce(filterRulesUrl.toString(), false, DEBUG_DOMAIN_TO_FIND);
  180. }
  181. blacklistDomainSets.add(domain);
  182. }
  183. }
  184. });
  185. console.timeEnd(` - processFilterRules: ${filterRulesUrl}`);
  186. return {
  187. white: whitelistDomainSets,
  188. black: blacklistDomainSets
  189. };
  190. }
  191. function preprocessFullDomainSetBeforeUsedAsWorkerData (data) {
  192. return data.filter(domain => (
  193. domain.charCodeAt(0) === 46
  194. && !canExcludeFromDedupe(domain)
  195. ));
  196. }
  197. // duckdns.org domain will not overlap and doesn't need dedupe
  198. function canExcludeFromDedupe (domain) {
  199. if (
  200. // starts with a dot
  201. domain.charCodeAt(0) === 46
  202. && domain.length === 23
  203. && domain.endsWith('.duckdns.org')
  204. ) {
  205. return true;
  206. }
  207. return false;
  208. }
  209. module.exports.processDomainLists = processDomainLists;
  210. module.exports.processHosts = processHosts;
  211. module.exports.processFilterRules = processFilterRules;
  212. module.exports.preprocessFullDomainSetBeforeUsedAsWorkerData = preprocessFullDomainSetBeforeUsedAsWorkerData;
  213. module.exports.canExcludeFromDedupe = canExcludeFromDedupe;