parse-filter.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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[0] === '!') {
  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[0] !== '.') {
  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[0] === '/'
  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. // ends with
  152. || line.endsWith('.')
  153. || line.endsWith('-')
  154. || line.endsWith('_')
  155. // special modifier
  156. || R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2.test(line)
  157. || ((line.includes('/') || line.includes(':')) && !line.includes('://'))
  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[0] === '@' && line[1] === '@') {
  215. if (line.endsWith('$cname')) {
  216. continue;
  217. }
  218. if (
  219. // (line.startsWith('@@|') || line.startsWith('@@.'))
  220. (
  221. line[2] === '|'
  222. || line[2] === '.'
  223. )
  224. && (
  225. lineEndsWithCaret
  226. || lineEndsWithCaretVerticalBar
  227. || line.endsWith('$genericblock')
  228. || line.endsWith('$document')
  229. )
  230. ) {
  231. const _domain = line
  232. .replace('@@||', '')
  233. .replace('@@|', '')
  234. .replace('@@.', '')
  235. .replace('^|', '')
  236. .replace('^$genericblock', '')
  237. .replace('$genericblock', '')
  238. .replace('^$document', '')
  239. .replace('$document', '')
  240. .replaceAll('^', '')
  241. .trim();
  242. const domain = normalizeDomain(_domain);
  243. if (domain) {
  244. addToWhiteList(domain);
  245. } else {
  246. console.warn(' * [parse-filter E0001] (black) invalid domain:', _domain);
  247. }
  248. continue;
  249. }
  250. }
  251. if (
  252. line.startsWith('||')
  253. && (
  254. lineEndsWithCaret
  255. || lineEndsWithCaretVerticalBar
  256. || line.endsWith('$cname')
  257. )
  258. ) {
  259. const _domain = line
  260. .replace('||', '')
  261. .replace('^|', '')
  262. .replace('$cname', '')
  263. .replaceAll('^', '')
  264. .trim();
  265. const domain = normalizeDomain(_domain);
  266. if (domain) {
  267. addToBlackList(domain, true);
  268. } else {
  269. console.warn(' * [parse-filter E0002] (black) invalid domain:', _domain);
  270. }
  271. continue;
  272. }
  273. const lineStartsWithSingleDot = line.startsWith('.');
  274. if (
  275. lineStartsWithSingleDot
  276. && (
  277. lineEndsWithCaret
  278. || lineEndsWithCaretVerticalBar
  279. )
  280. ) {
  281. const _domain = line
  282. .replace('^|', '')
  283. .replaceAll('^', '')
  284. .slice(1)
  285. .trim();
  286. const domain = normalizeDomain(_domain);
  287. if (domain) {
  288. addToBlackList(domain, true);
  289. } else {
  290. console.warn(' * [parse-filter E0003] (black) invalid domain:', _domain);
  291. }
  292. continue;
  293. }
  294. if (
  295. (
  296. line.startsWith('://')
  297. || line.startsWith('http://')
  298. || line.startsWith('https://')
  299. || line.startsWith('|http://')
  300. || line.startsWith('|https://')
  301. )
  302. && (
  303. lineEndsWithCaret
  304. || lineEndsWithCaretVerticalBar
  305. )
  306. ) {
  307. const _domain = line
  308. .replace('|https://', '')
  309. .replace('https://', '')
  310. .replace('|http://', '')
  311. .replace('http://', '')
  312. .replace('://', '')
  313. .replace('^|', '')
  314. .replaceAll('^', '')
  315. .trim();
  316. const domain = normalizeDomain(_domain);
  317. if (domain) {
  318. addToBlackList(domain, false);
  319. } else {
  320. console.warn(' * [parse-filter E0004] (black) invalid domain:', _domain);
  321. }
  322. continue;
  323. }
  324. if (line[0] !== '|' && lineEndsWithCaret) {
  325. const _domain = line.slice(0, -1);
  326. const domain = normalizeDomain(_domain);
  327. if (domain) {
  328. addToBlackList(domain, false);
  329. } else {
  330. console.warn(' * [parse-filter E0005] (black) invalid domain:', _domain);
  331. }
  332. continue;
  333. }
  334. const tryNormalizeDomain = normalizeDomain(lineStartsWithSingleDot ? line.slice(1) : line);
  335. if (
  336. tryNormalizeDomain
  337. && (
  338. lineStartsWithSingleDot
  339. ? tryNormalizeDomain.length === line.length - 1
  340. : tryNormalizeDomain === line
  341. )
  342. ) {
  343. addToBlackList(line, true);
  344. continue;
  345. }
  346. if (
  347. !line.endsWith('.js')
  348. ) {
  349. hasParseFailed = true;
  350. console.warn(' * [parse-filter E0010] can not parse:', line);
  351. }
  352. }
  353. console.timeEnd(` - processFilterRules: ${filterRulesUrl}`);
  354. return {
  355. white: whitelistDomainSets,
  356. black: blacklistDomainSets,
  357. foundDebugDomain,
  358. parseFailed: hasParseFailed
  359. };
  360. }
  361. module.exports.processDomainLists = processDomainLists;
  362. module.exports.processHosts = processHosts;
  363. module.exports.processFilterRules = processFilterRules;