parse-filter.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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 DEBUG_DOMAIN_TO_FIND = null; // example.com | null
  7. let foundDebugDomain = false;
  8. const warnOnceUrl = new Set();
  9. const warnOnce = (url, isWhite, ...message) => {
  10. const key = `${url}${isWhite ? 'white' : 'black'}`;
  11. if (warnOnceUrl.has(key)) {
  12. return;
  13. }
  14. warnOnceUrl.add(key);
  15. console.warn(url, isWhite ? '(white)' : '(black)', ...message);
  16. };
  17. /**
  18. * @param {string | URL} domainListsUrl
  19. */
  20. async function processDomainLists(domainListsUrl) {
  21. if (typeof domainListsUrl === 'string') {
  22. domainListsUrl = new URL(domainListsUrl);
  23. }
  24. /** @type Set<string> */
  25. const domainSets = new Set();
  26. const rl = await fetchRemoteTextAndCreateReadlineInterface(domainListsUrl);
  27. for await (const line of rl) {
  28. if (
  29. line.startsWith('#')
  30. || line.startsWith('!')
  31. || line.startsWith(' ')
  32. || line === ''
  33. || line.startsWith('\r')
  34. || line.startsWith('\n')
  35. ) {
  36. continue;
  37. }
  38. const domainToAdd = line.trim();
  39. if (DEBUG_DOMAIN_TO_FIND && domainToAdd.includes(DEBUG_DOMAIN_TO_FIND)) {
  40. warnOnce(domainListsUrl.toString(), false, DEBUG_DOMAIN_TO_FIND);
  41. foundDebugDomain = true;
  42. }
  43. domainSets.add(domainToAdd);
  44. }
  45. return domainSets;
  46. }
  47. /**
  48. * @param {string | URL} hostsUrl
  49. */
  50. async function processHosts(hostsUrl, includeAllSubDomain = false) {
  51. console.time(` - processHosts: ${hostsUrl}`);
  52. if (typeof hostsUrl === 'string') {
  53. hostsUrl = new URL(hostsUrl);
  54. }
  55. /** @type Set<string> */
  56. const domainSets = new Set();
  57. const rl = await fetchRemoteTextAndCreateReadlineInterface(hostsUrl);
  58. for await (const line of rl) {
  59. if (line.includes('#')) {
  60. continue;
  61. }
  62. if (line.startsWith(' ') || line.startsWith('\r') || line.startsWith('\n') || line.trim() === '') {
  63. continue;
  64. }
  65. const [, ...domains] = line.split(' ');
  66. const _domain = domains.join(' ').trim();
  67. if (DEBUG_DOMAIN_TO_FIND && _domain.includes(DEBUG_DOMAIN_TO_FIND)) {
  68. warnOnce(hostsUrl.toString(), false, DEBUG_DOMAIN_TO_FIND);
  69. foundDebugDomain = true;
  70. }
  71. const domain = normalizeDomain(_domain);
  72. if (domain) {
  73. if (includeAllSubDomain) {
  74. domainSets.add(`.${domain}`);
  75. } else {
  76. domainSets.add(domain);
  77. }
  78. }
  79. }
  80. console.timeEnd(` - processHosts: ${hostsUrl}`);
  81. return domainSets;
  82. }
  83. const R_KNOWN_NOT_NETWORK_FILTER_PATTERN = /[#&%~=]/;
  84. const R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2 = /(\$popup|\$removeparam|\$popunder)/;
  85. /**
  86. * @param {string | URL} filterRulesUrl
  87. * @param {readonly (string | URL)[] | undefined} [fallbackUrls]
  88. * @returns {Promise<{ white: Set<string>, black: Set<string>, foundDebugDomain: boolean, parseFailed: boolean }>}
  89. */
  90. async function processFilterRules(filterRulesUrl, fallbackUrls, includeThirdParties = false) {
  91. console.time(` - processFilterRules: ${filterRulesUrl}`);
  92. /** @type Set<string> */
  93. const whitelistDomainSets = new Set();
  94. /** @type Set<string> */
  95. const blacklistDomainSets = new Set();
  96. const addToBlackList = (domainToBeAddedToBlack, isSubDomain) => {
  97. if (DEBUG_DOMAIN_TO_FIND && domainToBeAddedToBlack.includes(DEBUG_DOMAIN_TO_FIND)) {
  98. warnOnce(filterRulesUrl.toString(), false, DEBUG_DOMAIN_TO_FIND);
  99. foundDebugDomain = true;
  100. }
  101. if (isSubDomain && !domainToBeAddedToBlack.startsWith('.')) {
  102. blacklistDomainSets.add(`.${domainToBeAddedToBlack}`);
  103. } else {
  104. blacklistDomainSets.add(domainToBeAddedToBlack);
  105. }
  106. };
  107. const addToWhiteList = (domainToBeAddedToWhite) => {
  108. if (DEBUG_DOMAIN_TO_FIND && domainToBeAddedToWhite.includes(DEBUG_DOMAIN_TO_FIND)) {
  109. warnOnce(filterRulesUrl.toString(), true, DEBUG_DOMAIN_TO_FIND);
  110. foundDebugDomain = true;
  111. }
  112. whitelistDomainSets.add(domainToBeAddedToWhite);
  113. };
  114. let filterRules;
  115. try {
  116. /** @type string[] */
  117. filterRules = (
  118. await Promise.any(
  119. [filterRulesUrl, ...(fallbackUrls || [])].map(
  120. async url => (await fetchWithRetry(url)).text()
  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. /**
  358. * @param {string[]} data
  359. */
  360. function preprocessFullDomainSetBeforeUsedAsWorkerData(data) {
  361. return data
  362. .filter(domain => domain[0] === '.')
  363. .sort((a, b) => a.length - b.length);
  364. }
  365. module.exports.processDomainLists = processDomainLists;
  366. module.exports.processHosts = processHosts;
  367. module.exports.processFilterRules = processFilterRules;
  368. module.exports.preprocessFullDomainSetBeforeUsedAsWorkerData = preprocessFullDomainSetBeforeUsedAsWorkerData;