parse-filter.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. // @ts-check
  2. const { fetchWithRetry } = require('./fetch-retry');
  3. const { fetchRemoteTextAndCreateReadlineInterface } = require('./fetch-remote-text-by-line');
  4. const { NetworkFilter } = require('@cliqz/adblocker');
  5. const { normalizeDomain } = require('./is-domain-loose');
  6. const { processLine } = require('./process-line');
  7. const DEBUG_DOMAIN_TO_FIND = null; // example.com | null
  8. let foundDebugDomain = false;
  9. const warnOnceUrl = new Set();
  10. const warnOnce = (url, isWhite, ...message) => {
  11. const key = `${url}${isWhite ? 'white' : 'black'}`;
  12. if (warnOnceUrl.has(key)) {
  13. return;
  14. }
  15. warnOnceUrl.add(key);
  16. console.warn(url, isWhite ? '(white)' : '(black)', ...message);
  17. };
  18. /**
  19. * @param {string | URL} domainListsUrl
  20. */
  21. async function processDomainLists(domainListsUrl) {
  22. if (typeof domainListsUrl === 'string') {
  23. domainListsUrl = new URL(domainListsUrl);
  24. }
  25. /** @type Set<string> */
  26. const domainSets = new Set();
  27. for await (const line of await fetchRemoteTextAndCreateReadlineInterface(domainListsUrl)) {
  28. if (line.startsWith('!')) {
  29. continue;
  30. }
  31. const domainToAdd = processLine(line);
  32. if (!domainToAdd) {
  33. continue;
  34. }
  35. if (DEBUG_DOMAIN_TO_FIND && domainToAdd.includes(DEBUG_DOMAIN_TO_FIND)) {
  36. warnOnce(domainListsUrl.toString(), false, DEBUG_DOMAIN_TO_FIND);
  37. foundDebugDomain = true;
  38. }
  39. domainSets.add(domainToAdd);
  40. }
  41. return domainSets;
  42. }
  43. /**
  44. * @param {string | URL} hostsUrl
  45. */
  46. async function processHosts(hostsUrl, includeAllSubDomain = false) {
  47. console.time(` - processHosts: ${hostsUrl}`);
  48. if (typeof hostsUrl === 'string') {
  49. hostsUrl = new URL(hostsUrl);
  50. }
  51. /** @type Set<string> */
  52. const domainSets = new Set();
  53. for await (const l of await fetchRemoteTextAndCreateReadlineInterface(hostsUrl)) {
  54. const line = processLine(l);
  55. if (!line) {
  56. continue;
  57. }
  58. const [, ...domains] = line.split(' ');
  59. const _domain = domains.join(' ').trim();
  60. if (DEBUG_DOMAIN_TO_FIND && _domain.includes(DEBUG_DOMAIN_TO_FIND)) {
  61. warnOnce(hostsUrl.toString(), false, DEBUG_DOMAIN_TO_FIND);
  62. foundDebugDomain = true;
  63. }
  64. const domain = normalizeDomain(_domain);
  65. if (domain) {
  66. if (includeAllSubDomain) {
  67. domainSets.add(`.${domain}`);
  68. } else {
  69. domainSets.add(domain);
  70. }
  71. }
  72. }
  73. console.timeEnd(` - processHosts: ${hostsUrl}`);
  74. return domainSets;
  75. }
  76. const R_KNOWN_NOT_NETWORK_FILTER_PATTERN = /[#&%~=]/;
  77. const R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2 = /(\$popup|\$removeparam|\$popunder)/;
  78. /**
  79. * @param {string | URL} filterRulesUrl
  80. * @param {readonly (string | URL)[] | undefined} [fallbackUrls]
  81. * @returns {Promise<{ white: Set<string>, black: Set<string>, foundDebugDomain: boolean, parseFailed: boolean }>}
  82. */
  83. async function processFilterRules(filterRulesUrl, fallbackUrls, includeThirdParties = false) {
  84. console.time(` - processFilterRules: ${filterRulesUrl}`);
  85. /** @type Set<string> */
  86. const whitelistDomainSets = new Set();
  87. /** @type Set<string> */
  88. const blacklistDomainSets = new Set();
  89. const addToBlackList = (domainToBeAddedToBlack, isSubDomain) => {
  90. if (DEBUG_DOMAIN_TO_FIND && domainToBeAddedToBlack.includes(DEBUG_DOMAIN_TO_FIND)) {
  91. warnOnce(filterRulesUrl.toString(), false, DEBUG_DOMAIN_TO_FIND);
  92. foundDebugDomain = true;
  93. }
  94. if (isSubDomain && !domainToBeAddedToBlack.startsWith('.')) {
  95. blacklistDomainSets.add(`.${domainToBeAddedToBlack}`);
  96. } else {
  97. blacklistDomainSets.add(domainToBeAddedToBlack);
  98. }
  99. };
  100. const addToWhiteList = (domainToBeAddedToWhite) => {
  101. if (DEBUG_DOMAIN_TO_FIND && domainToBeAddedToWhite.includes(DEBUG_DOMAIN_TO_FIND)) {
  102. warnOnce(filterRulesUrl.toString(), true, DEBUG_DOMAIN_TO_FIND);
  103. foundDebugDomain = true;
  104. }
  105. whitelistDomainSets.add(domainToBeAddedToWhite);
  106. };
  107. let filterRules;
  108. try {
  109. const controller = new AbortController();
  110. const signal = controller.signal;
  111. /** @type string[] */
  112. filterRules = (
  113. await Promise.any(
  114. [filterRulesUrl, ...(fallbackUrls || [])].map(
  115. url => fetchWithRetry(url, { signal })
  116. .then(r => r.text())
  117. .then(text => {
  118. controller.abort();
  119. return text;
  120. })
  121. )
  122. )
  123. ).split('\n').map(line => line.trim());
  124. } catch (e) {
  125. console.log(`Download Rule for [${filterRulesUrl}] failed`);
  126. throw e;
  127. }
  128. let hasParseFailed = false;
  129. for (let i = 0, len = filterRules.length; i < len; i++) {
  130. const line = filterRules[i].trim();
  131. if (
  132. line === ''
  133. || line.startsWith('/')
  134. || R_KNOWN_NOT_NETWORK_FILTER_PATTERN.test(line)
  135. // doesn't include
  136. || !line.includes('.') // rule with out dot can not be a domain
  137. // includes
  138. // || line.includes('#')
  139. || line.includes('!')
  140. || line.includes('?')
  141. || line.includes('*')
  142. // || line.includes('=')
  143. || line.includes('[')
  144. || line.includes('(')
  145. || line.includes(']')
  146. || line.includes(')')
  147. || line.includes(',')
  148. // || line.includes('~')
  149. // || line.includes('&')
  150. // || line.includes('%')
  151. || ((line.includes('/') || line.includes(':')) && !line.includes('://'))
  152. // ends with
  153. || line.endsWith('.')
  154. || line.endsWith('-')
  155. || line.endsWith('_')
  156. // special modifier
  157. || R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2.test(line)
  158. // || line.includes('$popup')
  159. // || line.includes('$removeparam')
  160. // || line.includes('$popunder')
  161. ) {
  162. continue;
  163. }
  164. const filter = NetworkFilter.parse(line);
  165. if (filter) {
  166. if (
  167. filter.isElemHide()
  168. || filter.isGenericHide()
  169. || filter.isSpecificHide()
  170. || filter.isRedirect()
  171. || filter.isRedirectRule()
  172. || filter.hasDomains()
  173. || filter.isCSP() // must not be csp rule
  174. || (!filter.fromAny() && !filter.fromDocument())
  175. ) {
  176. // not supported type
  177. continue;
  178. }
  179. if (
  180. filter.hasHostname() // must have
  181. && filter.isPlain()
  182. && (!filter.isRegex())
  183. && (!filter.isFullRegex())
  184. ) {
  185. const hostname = normalizeDomain(filter.getHostname());
  186. if (hostname) {
  187. if (filter.isException() || filter.isBadFilter()) {
  188. addToWhiteList(hostname);
  189. continue;
  190. }
  191. if (filter.firstParty() === filter.thirdParty()) {
  192. addToBlackList(hostname, true);
  193. continue;
  194. }
  195. if (filter.thirdParty()) {
  196. if (includeThirdParties) {
  197. addToBlackList(hostname, true);
  198. }
  199. continue;
  200. }
  201. if (filter.firstParty()) {
  202. continue;
  203. }
  204. } else {
  205. continue;
  206. }
  207. }
  208. }
  209. if (line.includes('$third-party') || line.includes('$frame')) {
  210. continue;
  211. }
  212. const lineEndsWithCaret = line.endsWith('^');
  213. const lineEndsWithCaretVerticalBar = line.endsWith('^|');
  214. if (line.startsWith('@@')) {
  215. if (line.endsWith('$cname')) {
  216. continue;
  217. }
  218. if (
  219. (line.startsWith('@@|') || line.startsWith('@@.'))
  220. && (
  221. lineEndsWithCaret
  222. || lineEndsWithCaretVerticalBar
  223. || line.endsWith('$genericblock')
  224. || line.endsWith('$document')
  225. )
  226. ) {
  227. const _domain = line
  228. .replace('@@||', '')
  229. .replace('@@|', '')
  230. .replace('@@.', '')
  231. .replace('^|', '')
  232. .replace('^$genericblock', '')
  233. .replace('$genericblock', '')
  234. .replace('^$document', '')
  235. .replace('$document', '')
  236. .replaceAll('^', '')
  237. .trim();
  238. const domain = normalizeDomain(_domain);
  239. if (domain) {
  240. addToWhiteList(domain);
  241. } else {
  242. console.warn(' * [parse-filter E0001] (black) invalid domain:', _domain);
  243. }
  244. continue;
  245. }
  246. }
  247. if (
  248. line.startsWith('||')
  249. && (
  250. lineEndsWithCaret
  251. || lineEndsWithCaretVerticalBar
  252. || line.endsWith('$cname')
  253. )
  254. ) {
  255. const _domain = line
  256. .replace('||', '')
  257. .replace('^|', '')
  258. .replace('$cname', '')
  259. .replaceAll('^', '')
  260. .trim();
  261. const domain = normalizeDomain(_domain);
  262. if (domain) {
  263. addToBlackList(domain, true);
  264. } else {
  265. console.warn(' * [parse-filter E0002] (black) invalid domain:', _domain);
  266. }
  267. continue;
  268. }
  269. const lineStartsWithSingleDot = line.startsWith('.');
  270. if (
  271. lineStartsWithSingleDot
  272. && (
  273. lineEndsWithCaret
  274. || lineEndsWithCaretVerticalBar
  275. )
  276. ) {
  277. const _domain = line
  278. .replace('^|', '')
  279. .replaceAll('^', '')
  280. .slice(1)
  281. .trim();
  282. const domain = normalizeDomain(_domain);
  283. if (domain) {
  284. addToBlackList(domain, true);
  285. } else {
  286. console.warn(' * [parse-filter E0003] (black) invalid domain:', _domain);
  287. }
  288. continue;
  289. }
  290. if (
  291. (
  292. line.startsWith('://')
  293. || line.startsWith('http://')
  294. || line.startsWith('https://')
  295. || line.startsWith('|http://')
  296. || line.startsWith('|https://')
  297. )
  298. && (
  299. lineEndsWithCaret
  300. || lineEndsWithCaretVerticalBar
  301. )
  302. ) {
  303. const _domain = line
  304. .replace('|https://', '')
  305. .replace('https://', '')
  306. .replace('|http://', '')
  307. .replace('http://', '')
  308. .replace('://', '')
  309. .replace('^|', '')
  310. .replaceAll('^', '')
  311. .trim();
  312. const domain = normalizeDomain(_domain);
  313. if (domain) {
  314. addToBlackList(domain, false);
  315. } else {
  316. console.warn(' * [parse-filter E0004] (black) invalid domain:', _domain);
  317. }
  318. continue;
  319. }
  320. if (!line.startsWith('|') && lineEndsWithCaret) {
  321. const _domain = line.slice(0, -1);
  322. const domain = normalizeDomain(_domain);
  323. if (domain) {
  324. addToBlackList(domain, false);
  325. } else {
  326. console.warn(' * [parse-filter E0005] (black) invalid domain:', _domain);
  327. }
  328. continue;
  329. }
  330. const tryNormalizeDomain = normalizeDomain(lineStartsWithSingleDot ? line.slice(1) : line);
  331. if (
  332. tryNormalizeDomain
  333. && (
  334. lineStartsWithSingleDot
  335. ? tryNormalizeDomain.length === line.length - 1
  336. : tryNormalizeDomain === line
  337. )
  338. ) {
  339. addToBlackList(line, true);
  340. continue;
  341. }
  342. if (
  343. !line.endsWith('.js')
  344. ) {
  345. hasParseFailed = true;
  346. console.warn(' * [parse-filter E0010] can not parse:', line);
  347. }
  348. }
  349. console.timeEnd(` - processFilterRules: ${filterRulesUrl}`);
  350. return {
  351. white: whitelistDomainSets,
  352. black: blacklistDomainSets,
  353. foundDebugDomain,
  354. parseFailed: hasParseFailed
  355. };
  356. }
  357. module.exports.processDomainLists = processDomainLists;
  358. module.exports.processHosts = processHosts;
  359. module.exports.processFilterRules = processFilterRules;